gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:01:29 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com