Spring Security支持多个身份验证提供程序LDAP身份验证和JPA

时间:2020-07-20 04:04:08

标签: java spring spring-boot spring-security ldap

我正在尝试为正在进行的spring-boot项目实施身份验证和授权服务。我已经实现了基于JPA的身份验证提供程序,并且运行良好。如何将LDAP身份验证提供程序添加到同一项目中,并根据用户身份验证类型在身份验证方法之间切换?

下面是我的代码

@Configuration
public class ProjectConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UsernamePasswordAuthProvider authProvider;
    @Autowired
    private LdapAuth ldapAuth;
    @Autowired
    private LdapAuthenticationpopulator ldapAuthenticationpopulator;


    private String ldapUrls = "ldap://localhost:3890";
    private String ldapSecurityPrincipal = "cn=admin,dc=mycompany,dc=com";
    private String ldapPrincipalPassword = "admin";
    private String userDnPattern = "uid={0}";
    @Autowired
    private UsernamePasswordAuthFilter usernamePasswordAuthFilter;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Order(1)
    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.ldapAuthentication()
                .contextSource()
                .url(ldapUrls)
                .managerDn(ldapSecurityPrincipal)
                .managerPassword(ldapPrincipalPassword)
                .and()
                .userDnPatterns(userDnPattern)
                .ldapAuthoritiesPopulator(ldapAuthenticationpopulator);
    }

    @Override
    @Order(2)
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(authProvider);
    }

    @Override
    protected void configure(HttpSecurity http) {
        http.addFilterAt(usernamePasswordAuthFilter,
                BasicAuthenticationFilter.class);
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

尽管我的LDAP凭据是正确的,但没有达到该方法。 如何从DB ex(LDAP,JPA,SSO)为我的应用程序获取身份验证方法,并执行相应的身份验证提供程序方法?

我已经遍历了多个用于MultipleAuthenticationProviders的文档,但是找不到很多 请让我知道是否有任何可能的解决方案。 预先感谢

1 个答案:

答案 0 :(得分:0)

我找到了一个解决方案。我已经在数据库中放置了启用LDAP或启用JPA身份验证的属性,并在运行时根据我调用特定身份验证方法的布尔值加载它们。