问题遇到的现象和发生背景
我在Spring Security中配置了两个异常处理,一个是自定AuthenticationEntryPoint,一个是自定义AccessDeniedHandler。但发现无论抛什么异常都进入了AuthenticationEntryPoint。该抛什么异常才能进入AccessDeniedHandler啊。
问题相关代码,请勿粘贴截图
自定义AuthenticationEntryPoint
/**
* 用户未登录或token失效时的返回结果
* @author 刘昌兴
*/
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
PrintWriter printWriter=response.getWriter();
ResultBean resultBean=ResultBean.error(authException.getMessage(), null);
resultBean.setCode(401);
printWriter.write(new ObjectMapper().writeValueAsString(resultBean));
printWriter.flush();
printWriter.close();
}
}
自定义AccessDeniedHandler
/**
* 没有权限访问时返回的结果
* @author 刘昌兴
*
*/
@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler{
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
PrintWriter printWriter=response.getWriter();
ResultBean resultBean=ResultBean.error("权限不足,请联系管理员!", null);
resultBean.setCode(403);
printWriter.write(new ObjectMapper().writeValueAsString(resultBean));
printWriter.flush();
printWriter.close();
}
}
Spring Security配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
/* .antMatchers("/login","/doc.html","/swagger-resources/**",
"/v2/api-docs/**","/webjars/**","/capture","/test/**","/ws/**","/logOut",
"/admins/userFaces","/index.html","/css/**","/js/**","/fonts/**").permitAll()//放行相关请求和资源*/
.anyRequest().authenticated()//除了上面的其他都需要认证
.withObjectPostProcessor(getObjectPostProcessor())//动态权限配置
.and()
.addFilterBefore(getJwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class)//添加登陆过滤器
.exceptionHandling()//添加异常处理过滤器
.accessDeniedHandler(restfulAccessDeniedHandler)//访问拒绝处理器
.authenticationEntryPoint(restAuthenticationEntryPoint)//权限异常过滤器
.and()
.csrf().disable()//使用jwt,不需要使用csrf拦截器
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)//不需要使用session
.and()
.headers().cacheControl();//禁用缓存
}