[spring security] - LDAP configuration - Bind approach

Springsecurity LDAP authentication sample XML.

uid={0},ou=Peoplecnsnuid

1. Implements UserDetailsContextMapper

public class UserDetailsContextMapperImpl implements UserDetailsContextMapper {
	
	@Override
	public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) {
		
		//How to get attribute from DirContextOperations
		try {
			System.out.println("Get DN size: " + ctx.getDn().size());
			for(int i=0; i< ctx.getDn().size(); i++){
				System.out.println("DN[" + i + "] = " + ctx.getDn().get(i));
			}
			
			System.out.println("NameInNamespace = " + ctx.getNameInNamespace());
			
			Attributes attributes = ctx.getAttributes();
			NamingEnumeration ne = attributes.getIDs();
			while(ne.hasMore()){
				String id = ne.next();
				//System.out.println("id = " + id + ", value = " + ctx.getStringAttribute(id));
				//ctx.getStringAttribute(id) is not safe, if attribute is not String object it will throw exception.
				
				Attribute attribute = attributes.get(id);
				System.out.println("attribute id:" + id + ", attribute size: " + attribute.size());
				for(int j = 0; j < attribute.size(); j++){
					System.out.println("        attribute[" + j + "] = " + attribute.get(j));
				}
			}
			
		} catch (NamingException e) {
			e.printStackTrace();
		}
		
		//Decide where you want to get user detail information. DB or anywhere you want
		UserDetails ud = ...;
		
		return ud;
	}

}

2. Implements LdapAuthoritiesPopulator

/**
 * Only return "ROLE_USER"
 */
public class LdapAuthoritiesPopulatorImpl implements LdapAuthoritiesPopulator {
	
	public static final String ROLE_USER = "ROLE_USER";
    
	public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {

		return new ArrayList() {
			private static final long serialVersionUID = 1L;

			{
				add(new SimpleGrantedAuthority(ROLE_USER));
			}
		};
	}
}

3. UserDN pattern

According to practical how do you manage user information on LDAP server.
For example, uid={0},ou=Users

4. User attributes

Attributes will return to application from LDAP server after success authentication. If you don't specify LDAP server will return all the attributes of this authenticated user. 
For example, uid, cn and sn etc.
發佈了53 篇原創文章 · 獲贊 0 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章