【发布时间】:2017-06-22 14:05:02
【问题描述】:
Spring Boot here。我刚刚阅读了有关 Spring Security 的 excellent Baeldung article 并用它实现了基本身份验证。我有兴趣为我需要构建的简单 REST 服务(所以 no UI/webapp)实现它。
我对@987654323@ impl 特别感兴趣。在这个 impl 的 commence 覆盖中,作者:
- 在响应中添加
WWW-Authenticate标头;和 - 在响应中设置 HTTP 状态码;和
- 将实际响应实体直接写入响应;和
- 设置领域的名称
我想按照作者的示例为我的应用程序实现基本身份验证,但我已经有一个运行良好的 ResponseEntityExceptionHandler 为我的应用程序工作:
@ControllerAdvice
public class MyAppExceptionMapper extends ResponseEntityExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
@ResponseBody
public ResponseEntity<ErrorResponse> handleIllegalArgumentExeption(IllegalArgumentException iaEx) {
return new ResponseEntity<ErrorResponse>(buildErrorResponse(iaEx,
iaEx.message,
"Please check your request and make sure it contains a valid entity/body."),
HttpStatus.BAD_REQUEST);
}
// other exceptions handled down here, etc.
// TODO: Handle Spring Security-related auth exceptions as well!
}
有什么方法可以将 Spring Security 和 Basic Auth 失败绑定到我现有/正在工作的ResponseEntityExceptionHandler?
理想情况下,有一种方法可以将我的 WebSecurityConfigurerAdapter impl 绑定到异常处理程序中,这样失败的身份验证或授权尝试会引发异常,然后由我的异常处理程序捕获。
我这样做的动机是让我的异常处理程序成为在发生任何异常时管理和配置 HTTP 响应的中心位置,无论其是否与身份验证相关。
这有可能吗,如果可以,怎么做?如果可能的话,我是否还需要将 WWW-Authenticate 添加到我的异常处理程序的响应中(为什么/为什么不)?提前致谢!
【问题讨论】:
-
你错了。 Spring 和 Spring Security(曾经是 ACEGI)是具有不同历史的不同项目。见Wikipedia。因此集成并不完美。
-
我同意您作为 Spring 用户的观点,但看到历史并不奇怪(这就是我的观点)。 Spring Security 的很多核心部分仍然来自 ACEGI。如果你有问题,你可以尝试更改 Spring Security(成为提交者或至少创建一个功能请求),接受它或根本不使用 Spring。
标签: spring spring-security exception-handling