相关疑难解决方法(0)

使用@ExceptionHandler处理spring安全性身份验证异常

我正在使用Spring MVC @ControllerAdvice@ExceptionHandler处理REST Api的所有异常.它适用于Web mvc控制器抛出的异常,但它不适用于spring安全自定义过滤器抛出的异常,因为它们在调用控制器方法之前运行.

我有一个自定义弹簧安全过滤器,它执行基于令牌的身份验证:

public class AegisAuthenticationFilter extends GenericFilterBean {

...

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        try {

            ...         
        } catch(AuthenticationException authenticationException) {

            SecurityContextHolder.clearContext();
            authenticationEntryPoint.commence(request, response, authenticationException);

        }

    }

}
Run Code Online (Sandbox Code Playgroud)

使用此自定义入口点:

@Component("restAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage());
    }

}
Run Code Online (Sandbox Code Playgroud)

并使用此类来处理全局异常:

@ControllerAdvice
public class RestEntityResponseExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler({ InvalidTokenException.class, AuthenticationException.class })
    @ResponseStatus(value = HttpStatus.UNAUTHORIZED) …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc spring-security

79
推荐指数
5
解决办法
8万
查看次数

标签 统计

spring ×1

spring-mvc ×1

spring-security ×1