Spring Security 如何在属性文件中提供ldap配置?

ct3nt3jp  于 2023-01-26  发布在  Spring
关注(0)|答案(1)|浏览(117)

我是spring security和ldap的新手。我正在尝试在ldap之上添加自定义身份验证,以便只有本地db中提到的特定用户可以登录。到目前为止,我已经能够实现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??

nzrxty8p

nzrxty8p1#

你可以用spring.ldap.* 把你的属性放到application.properties,Sping Boot 会在运行时自动创建必要的bean,你也可以在任何需要的地方用LdapProperties对象注入它们。
https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

相关问题