// spring secutity 403请求有两种,一种是登录之前拦截的403,一种是登录之后请求权限处理的403。
// 具体处理是 AccessDeniedHandler AuthenticationEntryPoint 这两个类
// 如何处理这两种403请求
// 继承 extends WebSecurityConfigurerAdapter 这个类中,重写configure方法里添加代码段
@Override
public void configure(HttpSecurity http) throws Exception {
// 代码段如下
http.exceptionHandling()
.authenticationEntryPoint(new SimpleAuthenticationEntryPoint()).accessDeniedHandler(new SimpleAccessDeniedHandler());
// SimpleAuthenticationEntryPoint 这个类定义的是登录时的拦截,就是用户名或密码错误,登录失败的403
// 代码如下,下面时我自己的实现逻辑
public class SimpleAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
// ================这段是我自己的逻辑,参照或者忽略
Object msg = request.getAttribute("msg");
BaseResponse baseResponse = null;
String message = authException.getMessage();
if(msg==null){
baseResponse = new BaseResponse(ResponseEnum.STATUS_CODE_401.getCode(),false,ResponseEnum.STATUS_CODE_401.getCode(),ResponseEnum.STATUS_CODE_401.getMsg(),null);
}else {
baseResponse = new BaseResponse(ResponseEnum.STATUS_CODE_200.getCode(),(String)msg);
request.removeAttribute("msg");
}
// ================这段是我自己的逻辑,参照或者忽略
// 登录失败时,需要指定返回什么样的信息,根据自己的需求去定制实现,重要
response.setStatus(HttpServletResponse.SC_OK);
response.setCharacterEncoding("utf-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
String json = JsonUtils.objectToJson(baseResponse);
PrintWriter printWriter = response.getWriter();
printWriter.print(json);
printWriter.flush();
printWriter.close();
}
}
// SimpleAccessDeniedHandler 登录成功以后权限不足的403实现
@Component
public class SimpleAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
//todo your business
BaseResponse baseResponse = new BaseResponse(ResponseEnum.STATUS_CODE_403.getCode(),false,ResponseEnum.STATUS_CODE_403.getCode(),
ResponseEnum.STATUS_CODE_403.getMsg(),null);
response.setCharacterEncoding("utf-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
String json = JsonUtils.objectToJson(baseResponse);
PrintWriter printWriter = response.getWriter();
printWriter.print(json);
printWriter.flush();
printWriter.close();
}
}