权限校验失败处理器
package com.lzy.security;
import cn.hutool.json.JSONUtil;
import com.lzy.common.lang.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
// 将响应的内容类型设置为JSON
response.setContentType("application/json;charset=utf-8");
// 设置响应状态码为403(Forbidden)权限不足
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
// 获取响应的输出流
ServletOutputStream out = response.getOutputStream();
// 创建一个包含异常消息的Result对象
Result result = Result.fail(accessDeniedException.getMessage());
// 将Result对象转换为JSON字符串,并写入输出流
out.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));
// 刷新输出流
out.flush();
// 关闭输出流
out.close();
}
}
认证失败处理器
package com.lzy.security;
import cn.hutool.json.JSONUtil;
import com.lzy.common.lang.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
// 将响应的内容类型设置为JSON
response.setContentType("application/json;charset=utf-8");
// 设置响应状态码为401未认证
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
// 获取响应的输出流
ServletOutputStream out = response.getOutputStream();
Result result = Result.fail("未登录或登录已过期,请重新登录");
// 将Result对象转换为JSON字符串,并写入输出流
out.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));
// 刷新输出流
out.flush();
// 关闭输出流
out.close();
}
}
配置里引用,在异常处理器注释那里
package com.lzy.config;
import com.lzy.security.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法级别的权限注解
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
LoginFailureHandler loginFailureHandler;
@Autowired
LoginSuccessHandler loginSuccessHandler;
@Autowired
CaptchaFilter captchaFilter;
@Autowired
JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Autowired
JwtAccessDeniedHandler jwtAccessDeniedHandler;
@Bean
JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
return new JwtAuthenticationFilter(authenticationManager());
}
private static final String[] URL_WHITELIST = {
"/login",
"/logout",
"/captcha",
"/favicon.ico", // 防止 favicon 请求被拦截
};
protected void configure(HttpSecurity http) throws Exception {
//跨域配置
http.cors().and().csrf().disable()
//登录配置
.formLogin()
.successHandler(loginSuccessHandler).failureHandler(loginFailureHandler)
//禁用session
.and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
//配置拦截规则
.and().authorizeRequests()
//白名单
.antMatchers(URL_WHITELIST).permitAll()
//其他请求都需要认证
.anyRequest().authenticated()
//异常处理器
.and().exceptionHandling()
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
.accessDeniedHandler(jwtAccessDeniedHandler)
//JWT验证过滤器
.and().addFilter(jwtAuthenticationFilter())
//配置自定义的过滤器
.addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class);
}
}