【问题标题】:How to add handler to HttpSecurity during runtime?如何在运行时向 HttpSecurity 添加处理程序?
【发布时间】:2022-01-22 09:26:57
【问题描述】:

通常,我会编写一个自己的 WebSecurityConfig 文件并编写类似于此的代码:

@Configuration
@EnableWebSecurity
open class WebSecurityConfig : WebSecurityConfigurerAdapter() {

    @Bean
    open fun accessDeniedHandler(): AccessDeniedHandler? {
        return CustomAccessDeniedHandler()
    }

    override fun configure(http: HttpSecurity) {
        ...
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
        ...
    }
}

问题:有没有什么方法可以在运行时访问HttpSecurity对象添加accessDeniedHandler,而不需要在configure(http: HttpSecurity)方法中定义?

【问题讨论】:

  • 我正在编写一个库并希望将此库设置为 AccessDeniedHandler。但是我不希望开发人员强制使用我的 WebSecurityConfigurerAdapter 实现来继续配置,而是我想以某种方式设置这个 AccessDeniedHandler。

标签: spring-boot spring-security


【解决方案1】:

你正在犯一个许多人在编写 spring boot 代码时犯的经典错误。

在这里,您将自定义访问拒绝处理程序注册为一个 bean,它将被 ApplicationContext 自动拾取。

@Bean
open fun accessDeniedHandler(): AccessDeniedHandler? {
    return CustomAccessDeniedHandler()
}

然后在这里,您手动注册了相同的AccessDeniedHandler,您知道,您在上面几行注册的那个会被上下文自动拾取并在需要的地方注入。

http.exceptionHandling().accessDeniedHandler(accessDeniedHandler());

完全不需要自动注册和手动注册同一个类。你基本上是在做同样的事情两次。

如果你想创建一个库,你应该编写一个使用第一个代码的启动器(将AccessDeniedHandler注册为一个 bean),ApplicationContext 将选择该 bean 并自动使用它。

如果已经注册为bean就不需要手动设置了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    相关资源
    最近更新 更多