in gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/KnoxLdapRealm.java [676:743]
protected String getUserDn( final String principal ) throws IllegalArgumentException, IllegalStateException {
String userDn;
Matcher matchedPrincipal = matchPrincipal( principal );
String userSearchBase = getUserSearchBase();
String userSearchAttributeName = getUserSearchAttributeName();
// If not searching use the userDnTemplate and return.
if ( ( userSearchBase == null || userSearchBase.isEmpty() ) ||
( userSearchAttributeName == null &&
userSearchFilter == null &&
!"object".equalsIgnoreCase( userSearchScope ) ) ) {
userDn = expandTemplate( userDnTemplate, matchedPrincipal );
LOG.computedUserDn( userDn, principal );
return userDn;
}
// Create the searchBase and searchFilter from config.
String searchBase = expandTemplate( getUserSearchBase(), matchedPrincipal );
String searchFilter;
if ( userSearchFilter == null ) {
if ( userSearchAttributeName == null ) {
searchFilter = String.format( Locale.ROOT, "(objectclass=%1$s)", getUserObjectClass() );
} else {
searchFilter = String.format( Locale.ROOT,
"(&(objectclass=%1$s)(%2$s=%3$s))",
getUserObjectClass(),
userSearchAttributeName,
expandTemplate( getUserSearchAttributeTemplate(), matchedPrincipal ) );
}
} else {
searchFilter = expandTemplate( userSearchFilter, matchedPrincipal );
}
SearchControls searchControls = getUserSearchControls();
// Search for userDn and return.
LdapContext systemLdapCtx = null;
NamingEnumeration<SearchResult> searchResultEnum = null;
try {
systemLdapCtx = getContextFactory().getSystemLdapContext();
LOG.searchBaseFilterScope(searchBase, searchFilter, userSearchScope);
searchResultEnum = systemLdapCtx.search( searchBase, searchFilter, searchControls );
// SearchResults contains all the entries in search scope
if (searchResultEnum.hasMore()) {
SearchResult searchResult = searchResultEnum.next();
userDn = searchResult.getNameInNamespace();
LOG.searchedAndFoundUserDn(userDn, principal);
return userDn;
} else {
throw new IllegalArgumentException("Illegal principal name: " + principal);
}
} catch (AuthenticationException e) {
LOG.failedToGetSystemLdapConnection(e);
throw new IllegalArgumentException("Illegal principal name: " + principal, e);
} catch (NamingException e) {
throw new IllegalArgumentException("Hit NamingException", e);
} finally {
try {
if (searchResultEnum != null) {
searchResultEnum.close();
}
} catch (NamingException e) {
// Ignore exception on close.
}
finally {
LdapUtils.closeContext(systemLdapCtx);
}
}
}