class
JsecLdapRealm {
static
authTokenClass = org.jsecurity.authc.UsernamePasswordToken
def
grailsApplication
def
authenticate(authToken) {
log.info
"Attempting to authenticate ${authToken.username} in LDAP realm..."
def
username = authToken.username
def
password =
new
String(authToken.password)
def
appConfig = grailsApplication.config
def
searchBase = appConfig.ldap.searchBase ?:
""
def
domain = appConfig.ldap.domain ?:
""
def
usernameAttribute = appConfig.ldap.username.attribute ?:
"uid"
def
skipAuthc = appConfig.ldap.skip.authentication ?: false
def
skipCredChk = appConfig.ldap.skip.credentialsCheck ?: false
def
allowEmptyPass = appConfig.ldap.allowEmptyPasswords != [:] ? appConfig.ldap.allowEmptyPasswords : true
if
(skipAuthc) {
log.info
"Skipping authentication in development mode."
return
username
}
if
(username ==
null
) {
throw
new
AccountException(
"Null usernames are not allowed by this realm."
)
}
if
(username ==
""
) {
throw
new
AccountException(
"Empty usernames are not allowed by this realm."
)
}
if
(!allowEmptyPass) {
if
(password ==
null
) {
throw
new
CredentialsException(
"Null password are not allowed by this realm."
)
}
if
(password ==
""
) {
throw
new
CredentialsException(
"Empty passwords are not allowed by this realm."
)
}
}
String[] returnedAtts = [
"sn"
,
"givenName"
,
"mail"
];
String searchFilter =
"(&(objectClass=user)(sAMAccountName="
+ username +
"))"
;
SearchControls searchCtls =
new
SearchControls();
searchCtls.setReturningAttributes(returnedAtts);
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
Hashtable env =
new
Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory"
);
env.put(Context.PROVIDER_URL, ldapHost);
env.put(Context.SECURITY_AUTHENTICATION,
"simple"
);
env.put(Context.SECURITY_PRINCIPAL, username +
"@"
+ domain);
env.put(Context.SECURITY_CREDENTIALS, password);
LdapContext ctxGC =
null
;
try
{
ctxGC =
new
InitialLdapContext(env,
null
);
NamingEnumeration answer = ctxGC.search(searchBase, searchFilter, searchCtls);
while
(answer.hasMoreElements()) {
SearchResult sr = (SearchResult) answer.next();
Attributes attrs = sr.getAttributes();
Map amap =
null
;
if
(attrs !=
null
) {
amap =
new
HashMap();
NamingEnumeration ne = attrs.getAll();
while
(ne.hasMore()) {
Attribute attr = (Attribute) ne.next();
amap.put(attr.getID(), attr.
get
());
}
ne.close();
}
if
(amap !=
null
)
return
username
else
return
false
}
}
catch
(NamingException ex) {
ex.printStackTrace();
}
}
}
Comments
Post a Comment