2015年7月21日 星期二

Apache shiro ldap multiple OU

Problem:

Shiro provide the LDAP access, but the accessing links is only complete CN.
such as
ldapRealm.userDnTemplate = cn={0},ou=eee,dc=gp,dc=mycompany

If you want to access the different ou such as
ldapRealm.userDnTemplate = cn={0},ou=eee,dc=gp,dc=mycompany
ldapRealm.userDnTemplate = cn={0},ou=aaa,dc=gp,dc=mycompany

It will use the ou=aaa, how to I access the two ou in same ldap content ?


Solution:

I define the access multiple ou format in shiro and inheritance the JndiLdapRealm

a. Shiro format  in shiro.ini
  - Define handle class
     >  ldapRealm = package.LdapMultiOU
  - Using the piple as sepearte
     > ldapRealm.userDnTemplate = cn={0},[cn=aaa|ou=eee],dc=gp,dc=mycompany


b.  The code

public class LdapMultiOU extends JndiLdapRealm {

protected AuthenticationInfo queryForAuthenticationInfo(
AuthenticationToken token, LdapContextFactory ldapContextFactory)
throws NamingException {

Object principal = token.getPrincipal();
Object credentials = token.getCredentials();

// coding
AuthenticationInfo info = null;
NamingException e = null;

principal = getLdapPrincipal(token);
System.out.println("Before ldap cn was " + principal);
String[] CNs= principal.toString().split(",");
StringTokenizer OUs = new StringTokenizer(CNs[1].replaceAll("(\\[|\\])", ""), "|"); 
while (OUs.hasMoreTokens()) {
         principal = CNs[0] + "," + OUs.nextToken() + "," +  CNs[2] + "," + CNs[3];
System.out.println("After ldap cn was " + principal);
       LdapContext ctx = null;
    try {
ctx = ldapContextFactory.getLdapContext(principal, credentials);
// context was opened successfully, which means their credentials
// were valid. Return the AuthenticationInfo:
info = createAuthenticationInfo(token, principal, credentials, ctx);
} catch (NamingException eNam) {
e = eNam;
    } finally {
LdapUtils.closeContext(ctx);
}
    }

if (info != null)  return info;
else throw e;
}
}


Reference:
http://stackoverflow.com/questions/9273631/apache-shiro-ldap-multiple-ous
http://blog.stratio.com/supporting-service-based-multi-realm-authentication-and-authorization/

沒有留言:

張貼留言