【问题标题】:Configuring Spring WebSecurityConfigurerAdapter to use exception handler配置 Spring WebSecurityConfigurerAdapter 以使用异常处理程序
【发布时间】:2017-06-22 14:05:02
【问题描述】:

Spring Boot here。我刚刚阅读了有关 Spring Security 的 excellent Baeldung article 并用它实现了基本身份验证。我有兴趣为我需要构建的简单 REST 服务(所以 no UI/webapp)实现它。

我对@9​​87654323@ impl 特别感兴趣。在这个 impl 的 commence 覆盖中,作者:

  1. 在响应中添加WWW-Authenticate 标头;和
  2. 在响应中设置 HTTP 状态码;和
  3. 将实际响应实体直接写入响应;和
  4. 设置领域的名称

我想按照作者的示例为我的应用程序实现基本身份验证,但我已经有一个运行良好的 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


【解决方案1】:

我认为这是不可能的。 Spring Security 作为 ServletFilter 应用,在请求到达任何 @Controller 注释类之前 - 因此 Spring Security 抛出的异常不能被异常处理程序(使用 @ControllerAdvice 注释)捕获。

遇到类似问题,我最终使用了自定义org.springframework.security.web.AuthenticationEntryPoint,它发送错误,然后将错误转发到自定义org.springframework.boot.autoconfigure.web.ErrorController

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 2017-12-15
    • 1970-01-01
    • 2019-12-28
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多