当前位置:网站首页>Custom failure handling

Custom failure handling

2022-06-09 10:20:00 Leon_ Jinhai_ Sun

We also hope that in case of authentication failure or authorization failure, we can return the same structure as our interface json, This allows the front end to handle the response uniformly . To achieve this function, we need to know SpringSecurity Exception handling mechanism of .

​ stay SpringSecurity in , If an exception occurs in the authentication process ExceptionTranslationFilter Capture to . stay ExceptionTranslationFilter It will judge whether the authentication fails or the authorization fails .

​ If an exception occurs during the authentication process, it will be encapsulated as AuthenticationException And then call AuthenticationEntryPoint Object to handle exceptions .

​ If it is an exception in the authorization process, it will be encapsulated as AccessDeniedException And then call AccessDeniedHandler Object to handle exceptions .

​ So if we need to customize exception handling , We just need to customize AuthenticationEntryPoint and AccessDeniedHandler Then configure it to SpringSecurity that will do .

① Custom implementation class

@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        ResponseResult result = new ResponseResult(HttpStatus.FORBIDDEN.value(), " Insufficient authority ");
        String json = JSON.toJSONString(result);
        WebUtils.renderString(response,json);

    }
}
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        ResponseResult result = new ResponseResult(HttpStatus.UNAUTHORIZED.value(), " Authentication failed. Please login again ");
        String json = JSON.toJSONString(result);
        WebUtils.renderString(response,json);
    }
}

② Configure to SpringSecurity

​ Inject the corresponding processor first

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;

And then we can use it HttpSecurity Object to configure .
 

        http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).
                accessDeniedHandler(accessDeniedHandler);

原网站

版权声明
本文为[Leon_ Jinhai_ Sun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090937210342.html