最近在学习springsecurity时,发现在自定义过滤器中抛出的异常会被设置的异常处理器捕获,而异常处理器没有携带自己想要设置的异常信息。
springsecurity配置:
http.csrf().disable().cors().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/register","/v2/api-docs", "/swagger-resources/configuration/ui",
"/swagger-resources", "/swagger-resources/configuration/security",
"/swagger-ui.html", "/webjars/**","/verifyCode/**",).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginProcessingUrl("/doLogin")
.successHandler(successAuthenticationHandler)
.failureHandler(loginFailAuthenticationHandler)
.and()
.logout().logoutUrl("/doLogout")
.permitAll()
.invalidateHttpSession(true)
.logoutSuccessHandler(logoutSuccessAuthenticationHandler)
.and() .exceptionHandling().authenticationEntryPoint(customAuthenticationEntryPoint).accessDeniedHandler(accessDeniedHandler)
.and()
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(preLoginCheckCodeFilter,UsernamePasswordAuthenticationFilter.class)
.headers().cacheControl();
customAuthenticationEntryPoint(认证异常处理器):
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
if (!response.isCommitted()) {
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
response.setHeader("Content-Type", "application/json;charset=UTF-8");
try (ServletOutputStream ous = response.getOutputStream()) {
Map<String, Object> map = new HashMap<>(16);
map.put("code", HttpStatus.SC_UNAUTHORIZED);
map.put("success", false);
map.put("message",e.getMessage());
ous.write(JSON.toJSONString(map).getBytes(StandardCharsets.UTF_8));
}
}
}
}
preLoginCheckCodeFilter:
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
httpServletResponse.setContentType("application/json;charset=utf-8");
if(loginUrl.equals(httpServletRequest.getRequestURI())){
//校验图形验证码
checkImageCode(httpServletRequest);
String userName = httpServletRequest.getParameter("username");
//角色状态是否正常
SysUserBO userData = sysUserService.getUserData(userName);
if(userData != null){
//账号被锁定
if(Constants.STRING_ONE.equals(userData.getUserStatus())){
throw new BusinessException(400,"该用户已被锁定!");
}
//账号停用
if(Constants.STRING_ZERO.equals(userData.getUserStatus())){
throw new BusinessException(400,"该用户已停用!");
}
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
测试时发现过滤器中的异常被异常处理器捕获时e.getMessage()的值一直是:Full authentication is required to access this resource,导致前端无法确定错误信息。
代码改进:
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
if (!response.isCommitted()) {
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
response.setHeader("Content-Type", "application/json;charset=UTF-8");
try (ServletOutputStream ous = response.getOutputStream()) {
Map<String, Object> map = new HashMap<>(16);
map.put("code", HttpStatus.SC_UNAUTHORIZED);
map.put("success", false);
map.put("message",Optional.ofNullable(request.getAttribute("errorMessage")).orElse("请先登录").toString());
ous.write(JSON.toJSONString(map).getBytes(StandardCharsets.UTF_8));
}
}
}
}
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
httpServletResponse.setContentType("application/json;charset=utf-8");
if(loginUrl.equals(httpServletRequest.getRequestURI())){
checkImageCode(httpServletRequest);
String userName = httpServletRequest.getParameter("username");
//角色状态是否正常
SysUserBO userData = sysUserService.getUserData(userName);
if(userData != null){
//账号被锁定
if(Constants.STRING_ONE.equals(userData.getUserStatus())){
httpServletRequest.setAttribute("errorMessage","该用户已被锁定!");
throw new BadCredentialsException("");
}
//账号停用
if(Constants.STRING_ZERO.equals(userData.getUserStatus())){
httpServletRequest.setAttribute("errorMessage","该用户已停用!");
throw new BadCredentialsException("");
}
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
当发生异常时,将异常信息保存到request请求中,CustomAuthenticationEntryPoint捕获到异常时直接从request中取异常信息就可以了。