mark
mark

Reputation: 31

spring boot - how to provide ldap config in properties file?

i am new to spring security and ldap. i am trying to add custom authentication on top of ldap, so that only specific users mentioned in a local db can login. so far i have been able to implement ldap authentication. this is what i have tried so far -

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);
    }

}

here, i am trying to add a CustomAuthenticationProvider which just checks for a single specific user name, but I am not using it. if i use this authProvider how do i tell spring about my ldap server, userSearchBase etc? should i move these to application.properties? how?

Upvotes: 2

Views: 11045

Answers (1)

sparse
sparse

Reputation: 139

You can put your properties in application.properties with spring.ldap.* and Spring Boot automatically will create necessary beans on runtime. Also, you can inject them with a LdapProperties object wherever you need.

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

Upvotes: 1

Related Questions