【问题标题】:Spring Security Java Config - custom AuthenticationProvider and UserDetailsServiceSpring Security Java Config - 自定义 AuthenticationProvider 和 UserDetailsS​​ervice
【发布时间】:2014-10-06 05:19:43
【问题描述】:

我使用java配置来配置Spring Security,并且我自定义了AuthenticationProvider和自定义的UserDetailsS​​ervice,在后面添加了额外的登录字段 http://forum.spring.io/forum/spring-projects/security/95715-extra-login-fields

我很难通过使用 java 配置将这两个自定义类添加到 Spring Security 框架中。 正如 AuthenticationProvider#authenticationProvider 的 java doc 所描述的:

添加基于自定义 AuthenticationProvider 的身份验证 被传入。由于 AuthenticationProvider 实现是 未知,所有自定义必须在外部完成,并且 AuthenticationManagerBuilder 立即返回。

此方法不能确保 UserDetailsS​​ervice 可用 对于 getDefaultUserDetailsS​​ervice() 方法。

所以我的问题是在这种情况下设置 UserDetailsS​​ervice 的方法是什么?

【问题讨论】:

    标签: spring-security spring-java-config


    【解决方案1】:

    这里是自定义AuthenticationProvider和自定义UserDetailsS​​ervice的例子:

    @Configuration
    @EnableWebMvcSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        public void registerGlobalAuthentication(AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(customAuthenticationProvider());
        }
    
        @Bean
        AuthenticationProvider customAuthenticationProvider() {
            CustomAuthenticationProvider impl = new CustomAuthenticationProvider();
            impl.setUserDetailsService(customUserDetailsService());
            /* other properties etc */
            return impl ;
        }
    
        @Bean   
        UserDetailsService customUserDetailsService() {
            /* custom UserDetailsService code here */
        }
    }
    

    【讨论】:

    • 我注意到你手动初始化了customAuthenticationProvidercustomUserDetailsService,直接@Autowired不是更好吗?
    • @Autowired@Configuration 类中使用,当您在 bean 外部进行接线时。在这段代码中,customAuthenticationProvidercustomUserDetailsService bean 被声明在同一个类中,因此 @Autowired 没有用例。另请注意,AuthenticationManagerBuilder 是在其他地方声明的,因此可以使用 @Autowired
    • impl.setUserDetailsS​​ervice(customUserDetailsS​​ervice()); // 这不起作用,- AuthenticationProvider 接口没有 setUserDetailsS​​ervice() 方法。
    • 由于它是一个自定义的 AuthenticationProvider 实现,您可以添加此方法(毕竟任何身份验证提供程序都需要一种机制来加载用户详细信息)。查看AuthenticationProvider 的实现,例如DaoAuthenticationProvider,它具有setUserDetailsService 方法。
    猜你喜欢
    • 2015-10-16
    • 2017-12-08
    • 2013-02-11
    • 2014-10-12
    • 2013-05-12
    • 2017-01-09
    • 2012-12-13
    • 2016-03-09
    • 1970-01-01
    相关资源
    最近更新 更多