Spring Security : Use Ldap for authentication, and database for authorities

12 03 2009

If you need to use Ldap for authentication and database /repository for authorization with spring security, here is a sample:

LDAP authenticator configuration

<ldap-server id="appLdapServer" url="ldap://ldapserver:port/dc=example,dc=com" manager-dn="uid=admin,ou=system" manager-password="your-pwd" />

<beans:bean id="companyLdapAuthProvider" class="org.springframework.security.providers.ldap.LdapAuthenticationProvider">
  <custom-authentication-provider />
  <beans:constructor-arg>
    <beans:bean class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator">
      <beans:constructor-arg ref="appLdapServer"/>
      <beans:property name="userDnPatterns">
        <beans:list><beans:value>uid={0},ou=Users</beans:value></beans:list>
      </beans:property>
    </beans:bean>
  </beans:constructor-arg>
  <beans:constructor-arg>
    <beans:bean class="com.mycompany.web.security.MyAuthoritiesPopulator">
      <beans:constructor-arg ref="myUserServiceBean"/>
    </beans:bean>
  </beans:constructor-arg>
</beans:bean>

Authorities populator:

public class MyAuthoritiesPopulator implements LdapAuthoritiesPopulator {

	private MyUserService userService;

    public MyAuthoritiesPopulator(MyUserService userService){
       this.userService = userService;
    }

	@Override
	public GrantedAuthority[] getGrantedAuthorities(DirContextOperations userData, String username) {
		Set userPerms = new HashSet();

        //get users permissions from service
		Set permissions = userService.getPermissions(username);

		for (MyPermission perm : permissions) {
				userPerms.add(new GrantedAuthorityImpl(perm.getName()));
		}
		return userPerms.toArray(new GrantedAuthority[userPerms.size()] );
	}
}

Actions

Information

One response

4 05 2009
morion

Hi,

could you post a complete example about this subject. I´m new to Spring Security and I´m interested in your solution.

thanks in advance

Leave a comment