SpringSecurity session超期后返回前端401错误码
程序员文章站
2024-03-19 13:44:22
...
想要实现的场景:前后端分离项目,后端session过期后,访问接口返回401 unauthentication错误给前端,前端对401错误进行跳转处理,跳转至登录页。
由于session过期,需要验证的请求(不论是不是Ajax请求)会返回302重定向,因此我们先配置Spring Security使之能对ajax请求返回401错误
1、实现自定义的RequestMatcher,匹配Ajax请求(angular默认不会带上X-Requested-With,这里通过Accept进行判断,也可以在前端对ajax请求添加X-Requested-With头)
public class AjaxRequestMatcher implements RequestMatcher {
/**
* 匹配Ajax请求
* @param request
* @return
*/
@Override
public boolean matches(HttpServletRequest request) {
return "XMLHttpRequest".equals(request.getHeader("X-Requested-With")) ||
request.getHeader("Accept") != null &&
request.getHeader("Accept").contains("application/json");
}
}
2、实现自定义的AuthenticationEntryPoint,返回401错误
@Component
public class AjaxAuthenticationEntryPoint implements AuthenticationEntryPoint {
//返回401错误
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
}
3、配置错误处理
.exceptionHandling()
.defaultAuthenticationEntryPointFor(authenticationEntryPoint,new AjaxRequestMatcher())
配置如下:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
...
...
.permitAll()
.and().csrf().disable()
.exceptionHandling()
.defaultAuthenticationEntryPointFor(authenticationEntryPoint,new AjaxRequestMatcher());
http.addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}