【问题标题】:spring security not able to add custom authentication providersspring security 无法添加自定义身份验证提供程序
【发布时间】:2016-01-06 14:02:55
【问题描述】:

我创建了额外的身份验证提供程序。我正在注册它们,如下所示:

@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(tokenAP());
        auth.authenticationProvider(usernameAndPasswordAP());
        auth.userDetailsService(getUserDetailsService());
    }

稍后在我的代码中,我使用 AuthenticationManager 对用户进行身份验证。问题是我在身份验证管理器中只注册了一个身份验证提供程序,即 DaoAuthenticationProvider。看起来我的身份验证提供程序根本没有注册。我应该做一些额外的配置来使它工作吗?我正在使用 spring boot 1.2.6 提前感谢任何提示。最好的问候

【问题讨论】:

    标签: spring authentication spring-security spring-boot


    【解决方案1】:

    当您覆盖 configure(AuthenticationManagerBuilder auth) 时,底层 AuthenticationManager 会以以下两种方式之一公开:

    1) 在SecurityConfig中,您可以简单地调用authenticationManager()

    2) 如果您需要在 SecurityConfig 之外使用 AuthenticationManager,则需要将其公开为 bean,例如:

    class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(tokenAP());
            auth.authenticationProvider(usernameAndPasswordAP());
            auth.userDetailsService(getUserDetailsService());
        }
    
       @Bean
       @Override
       public AuthenticationManager authenticationManagerBean() throws Exception {
         return super.authenticationManagerBean();
       }
    }
    

    【讨论】:

      【解决方案2】:

      我们在 Spring Boot Web 应用程序中配置身份验证提供程序的方式类似于 the example Spring Security Java configuration from the current release reference guide 中讨论的内容,它修改了默认的自动连接 AuthenticationManagerBuilder。使用您的方法,它可能看起来像:

      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(tokenAP())
          .authenticationProvider(usernameAndPasswordAP())
          .userDetailsService(getUserDetailsService());
      }
      

      如果我正确阅读the Javadocs for the configure(AuthenticationManagerBuilder) method,当您覆盖此方法时,您必须指定您自己的AuthenticationManager。通过使用如上所述的自动装配实例,默认的AuthenticationManager(即ProviderManager,又委托给一个或多个已配置的AuthorizationProvider 实例)。

      您可能还需要注释您的配置类:

      @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
      

      这样您的访问控制规则就会在 Spring Boot 否则为您配置的默认值之前应用。

      【讨论】:

        猜你喜欢
        • 2016-07-19
        • 1970-01-01
        • 2011-02-09
        • 1970-01-01
        • 2016-09-24
        • 2011-01-03
        • 2015-08-16
        • 2023-03-05
        • 1970-01-01
        相关资源
        最近更新 更多