【Spring Security】安全框架学习(十)

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);

            

}
end
  • 作者:dicraft(联系作者)
  • 更新时间:2022-09-03 11:10
  • 版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)
  • 转载声明:如果是转载栈主转载的文章,请附上原文链接
  • 评论

    新增邮件回复功能,回复将会通过邮件形式提醒,请填写有效的邮件!