【问题标题】:spring boot - how to provide ldap config in properties file?spring boot - 如何在属性文件中提供 ldap 配置?
【发布时间】:2019-03-27 17:34:05
【问题描述】:

我是 Spring Security 和 ldap 的新手。 我正在尝试在 ldap 之上添加自定义身份验证,以便只有本地数据库中提到的特定用户才能登录。到目前为止,我已经能够实现 ldap 身份验证。这是我迄今为止尝试过的 -

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${ldap.urls}")
    private String ldapUrl;

    @Autowired
    private CustomAuthenticationProvider authProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().fullyAuthenticated().and().formLogin().loginPage("/login")
                .failureUrl("/login?error").permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.ldapAuthentication().userSearchBase("ou=people").userSearchFilter("(uid={0})").groupSearchBase("ou=groups")
                .groupSearchFilter("(uniqueMember={0})").groupRoleAttribute("ou").rolePrefix("ROLE_").contextSource()
                .url(ldapUrl);

    }

}

public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        final String name = authentication.getName();
        final String password = authentication.getCredentials().toString();
        if (name.equals("user1")) {
            final List<GrantedAuthority> grantedAuths = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
            final UserDetails principal = new User(name, password, grantedAuths);
            final Authentication auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
            return auth;
        } else {
            return null;
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

}

在这里,我正在尝试添加一个 CustomAuthenticationProvider,它只检查单个特定用户名,但我没有使用它。如果我使用这个 authProvider 我如何告诉 spring 我的 ldap 服务器、userSearchBase 等?我应该将这些移至 application.properties 吗?怎么样?

【问题讨论】:

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


    【解决方案1】:

    您可以使用 spring.ldap.* 将您的属性放在 application.properties 中,Spring Boot 会自动在运行时创建必要的 bean。此外,您可以在任何需要的地方为它们注入 LdapProperties 对象。

    https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

    【讨论】:

    • 我理解并感谢您的回复,但这并不能回答关于*如何提供我提到的值的问题
    猜你喜欢
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    相关资源
    最近更新 更多