spring - 使用 @ExceptionHandler 处理 spring 安全认证异常

标签 spring spring-mvc spring-security

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

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

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

        }

    }

}

使用此自定义入口点:

@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());
    }

}

并用这个类来全局处理异常:

@ControllerAdvice
public class RestEntityResponseExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler({ InvalidTokenException.class, AuthenticationException.class })
    @ResponseStatus(value = HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public RestError handleAuthenticationException(Exception ex) {

        int errorCode = AegisErrorCode.GenericAuthenticationError;
        if(ex instanceof AegisException) {
            errorCode = ((AegisException)ex).getCode();
        }

        RestError re = new RestError(
            HttpStatus.UNAUTHORIZED,
            errorCode, 
            "...",
            ex.getMessage());

        return re;
    }
}

我需要做的是返回一个详细的 JSON 正文,即使是 spring security AuthenticationException。有没有办法让 spring security AuthenticationEntryPoint 和 spring mvc @ExceptionHandler 一起工作?

我正在使用 spring security 3.1.4 和 spring mvc 3.2.4。

最佳答案

好的,我尝试按照建议自己从 AuthenticationEntryPoint 编写 json,它可以工作。

只是为了测试,我通过删除 response.sendError 更改了 AutenticationEntryPoint

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

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
    
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getOutputStream().println("{ \"error\": \"" + authenticationException.getMessage() + "\" }");

    }
}

通过这种方式,即使您使用 Spring Security AuthenticationEntryPoint,您也可以发送自定义 json 数据以及 401 未授权。

显然,您不会像我那样构建 json 用于测试目的,但您会序列化一些类实例。

在 Spring Boot 中,您应该将其添加到 SecurityConfiguration 文件的 http.authenticationEntryPoint() 部分。

关于spring - 使用 @ExceptionHandler 处理 spring 安全认证异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19767267/

相关文章:

java - Spring 3.1 验证 - 当您有 2 个单独的表单提交和持久模型时如何使用 @valid

java - NullPointerException hibernate Generic Dao 与 Spring

java - 如何将不同 war 中的 Web 应用程序拆分为模块?

java - Spring MVC View - 解析占位符

java - 服务配置说明

spring-security - Spring SAML 安全性 - 两个不同 ADFS 服务器的多个 IDP 元数据配置

java - Spring Security DelegatingFilterProxy无限递归

spring - 如何在上下文卸载时关闭连接池?

java - Spring 安全 : enable/disable CSRF by client type (browser/non-browser )

java - 使用 @PropertySource 和外部 JSON 文件进行 Spring 属性配置