4 自定义失败处理
我们还希望在认证失败或者是授权失败的情况下也能和我们的接口一样返回相同结构的json,这样可以让前端能对响应进行统一的处理。要实现这个功能我们需要知道Spring Security的异常处理机制。
在Spring Security中,如果我们在认证或者授权的过程中出现了异常会被ExceptionTranslationFilter捕获到。在ExceptionTranslationFilter中会去判断是认证失败还是授权失败出现的异常。
如果是认证过程中出现的异常会被封装成AuthenticationException然后调用AuthenticationEntryPoint对象的方法去进行异常处理。
如果是授权过程中出现的异常会被封装成AccessDeniedException然后调用AccessDeniedHandler对象的方法去进行异常处理。
所以如果我们需要自定义异常处理,我们只需要自定义AuthenticationEntryPoint和AccessDeniedHandler然后配置SpringSecurity即可。
①自定义实现类
package handler;
import ...
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
@Overrride
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException{
ResponseResult result = new ResponseResult(HttpStatus.UNAUTHORIZED, "用户认证失败,请重新登陆");
String json = JSON.toJSONString(result);
//处理异常
WebUtils.renderString(response,json);
}
}
package handler;
import ...
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
@Override
public void handle (HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException{
ResponseResult result = new ResponseResult(HttpStatus.FORBIDDEN, "您的权限不足");
String json = JSON.toJSONString(result);
//处理异常
WebUtils.renderString(response,json);
}
②配置给springSecurity
上面的两个配置配一定要配置给Spring Security,也就是在SecurityConfig类中,在configure 添加过滤器。
我们可以使用HttpSecurity对象的方法去配置。
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationEntryPoint authenticationEntryPoint;
@Autowired
private AccessDeniedHandler accessDeniedHandler;
@Overrride
protected void configure(HttpSecurity http) throws Exception {
//之前的代码
...
//配置异常处理器
http.exceptionHandling()
//认证失败处理器
.authenticationEntryPoint (authenticationEntryPoint)
//授权失败处理器
.accessDeniedHandler(accessDeniedHandler);
}
评论