org.apache.shiro.realm.ldap
Class JndiLdapRealm

java.lang.Object
  extended by org.apache.shiro.realm.CachingRealm
      extended by org.apache.shiro.realm.AuthenticatingRealm
          extended by org.apache.shiro.realm.AuthorizingRealm
              extended by org.apache.shiro.realm.ldap.JndiLdapRealm
All Implemented Interfaces:
LogoutAware, Authorizer, PermissionResolverAware, RolePermissionResolverAware, CacheManagerAware, Realm, Initializable, Nameable

public class JndiLdapRealm
extends AuthorizingRealm

An LDAP Realm implementation utilizing Sun's/Oracle's JNDI API as an LDAP API. This is Shiro's default implementation for supporting LDAP, as using the JNDI API has been a common approach for Java LDAP support for many years.

This realm implementation and its backing JndiLdapContextFactory should cover 99% of all Shiro-related LDAP authentication and authorization needs. However, if it does not suit your needs, you might want to look into creating your own realm using an alternative, perhaps more robust, LDAP communication API, such as the Apache LDAP API.

Authentication

During an authentication attempt, if the submitted AuthenticationToken's principal is a simple username, but the LDAP directory expects a complete User Distinguished Name (User DN) to establish a connection, the userDnTemplate property must be configured. If not configured, the property will pass the simple username directly as the User DN, which is often incorrect in most LDAP environments (maybe Microsoft ActiveDirectory being the exception).

Authorization

By default, authorization is effectively disabled due to the default doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection) implementation returning null. If you wish to perform authorization based on an LDAP schema, you must subclass this one and override that method to reflect your organization's data model.

Configuration

This class primarily provides the userDnTemplate property to allow you to specify the your LDAP server's User DN format. Most other configuration is performed via the nested contextFactory property.

For example, defining this realm in Shiro .ini:

 [main]
 ldapRealm = org.apache.shiro.realm.ldap.JndiLdapRealm
 ldapRealm.userDnTemplate = uid={0},ou=users,dc=mycompany,dc=com
 ldapRealm.contextFactory.url = ldap://ldapHost:389
 ldapRealm.contextFactory.authenticationMechanism = DIGEST-MD5
 ldapRealm.contextFactory.environment[some.obscure.jndi.key] = some value
 ...
 
The default contextFactory instance is a JndiLdapContextFactory. See that class's JavaDoc for more information on configuring the LDAP connection as well as specifying JNDI environment properties as necessary.

Since:
1.1
See Also:
JndiLdapContextFactory

Constructor Summary
JndiLdapRealm()
          Default no-argument constructor that defaults the internal LdapContextFactory instance to a JndiLdapContextFactory.
 
Method Summary
protected  AuthenticationInfo createAuthenticationInfo(AuthenticationToken token, Object ldapPrincipal, Object ldapCredentials, LdapContext ldapContext)
          Returns the AuthenticationInfo resulting from a Subject's successful LDAP authentication attempt.
protected  AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
          Delegates to queryForAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken, LdapContextFactory), wrapping any NamingExceptions in a Shiro AuthenticationException to satisfy the parent method signature.
protected  AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals)
          Retrieves the AuthorizationInfo for the given principals from the underlying data store.
 LdapContextFactory getContextFactory()
          Returns the LdapContextFactory instance used to acquire connections to the LDAP directory during authentication attempts and authorization queries.
protected  Object getLdapPrincipal(AuthenticationToken token)
          Returns the principal to use when creating the LDAP connection for an authentication attempt.
protected  String getUserDn(String principal)
          Returns the LDAP User Distinguished Name (DN) to use when acquiring an LdapContext from the LdapContextFactory.
protected  String getUserDnPrefix()
          Returns the User DN prefix to use when building a runtime User DN value or null if no userDnTemplate has been configured.
protected  String getUserDnSuffix()
          Returns the User DN suffix to use when building a runtime User DN value.
 String getUserDnTemplate()
          Returns the User Distinguished Name (DN) template to use when creating User DNs at runtime - see the setUserDnTemplate JavaDoc for a full explanation.
protected  AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token, LdapContextFactory ldapContextFactory)
          This implementation opens an LDAP connection using the token's discovered principal and provided credentials.
protected  AuthorizationInfo queryForAuthorizationInfo(PrincipalCollection principals, LdapContextFactory ldapContextFactory)
          Method that should be implemented by subclasses to build an AuthorizationInfo object by querying the LDAP context for the specified principal.
 void setContextFactory(LdapContextFactory contextFactory)
          Sets the LdapContextFactory instance used to acquire connections to the LDAP directory during authentication attempts and authorization queries.
 void setUserDnTemplate(String template)
          Sets the User Distinguished Name (DN) template to use when creating User DNs at runtime.
 
Methods inherited from class org.apache.shiro.realm.AuthorizingRealm
afterCacheManagerSet, checkPermission, checkPermission, checkPermission, checkPermissions, checkPermissions, checkPermissions, checkRole, checkRole, checkRoles, checkRoles, checkRoles, clearCachedAuthorizationInfo, doClearCache, getAuthorizationCache, getAuthorizationCacheKey, getAuthorizationCacheName, getAuthorizationInfo, getPermissionResolver, getRolePermissionResolver, hasAllRoles, hasRole, hasRole, hasRoles, hasRoles, isAuthorizationCachingEnabled, isPermitted, isPermitted, isPermitted, isPermitted, isPermitted, isPermittedAll, isPermittedAll, isPermittedAll, onInit, setAuthorizationCache, setAuthorizationCacheName, setAuthorizationCachingEnabled, setName, setPermissionResolver, setRolePermissionResolver
 
Methods inherited from class org.apache.shiro.realm.AuthenticatingRealm
assertCredentialsMatch, clearCachedAuthenticationInfo, getAuthenticationCache, getAuthenticationCacheKey, getAuthenticationCacheKey, getAuthenticationCacheName, getAuthenticationInfo, getAuthenticationTokenClass, getCredentialsMatcher, init, isAuthenticationCachingEnabled, isAuthenticationCachingEnabled, setAuthenticationCache, setAuthenticationCacheName, setAuthenticationCachingEnabled, setAuthenticationTokenClass, setCredentialsMatcher, supports
 
Methods inherited from class org.apache.shiro.realm.CachingRealm
clearCache, getAvailablePrincipal, getCacheManager, getName, isCachingEnabled, onLogout, setCacheManager, setCachingEnabled
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface org.apache.shiro.util.Initializable
init
 

Constructor Detail

JndiLdapRealm

public JndiLdapRealm()
Default no-argument constructor that defaults the internal LdapContextFactory instance to a JndiLdapContextFactory.

Method Detail

getUserDnPrefix

protected String getUserDnPrefix()
Returns the User DN prefix to use when building a runtime User DN value or null if no userDnTemplate has been configured. If configured, this value is the text that occurs before the USERDN_SUBSTITUTION_TOKEN in the userDnTemplate value.

Returns:
the the User DN prefix to use when building a runtime User DN value or null if no userDnTemplate has been configured.

getUserDnSuffix

protected String getUserDnSuffix()
Returns the User DN suffix to use when building a runtime User DN value. or null if no userDnTemplate has been configured. If configured, this value is the text that occurs after the USERDN_SUBSTITUTION_TOKEN in the userDnTemplate value.

Returns:
the User DN suffix to use when building a runtime User DN value or null if no userDnTemplate has been configured.

setUserDnTemplate

public void setUserDnTemplate(String template)
                       throws IllegalArgumentException
Sets the User Distinguished Name (DN) template to use when creating User DNs at runtime. A User DN is an LDAP fully-qualified unique user identifier which is required to establish a connection with the LDAP directory to authenticate users and query for authorization information.

Usage

User DN formats are unique to the LDAP directory's schema, and each environment differs - you will need to specify the format corresponding to your directory. You do this by specifying the full User DN as normal, but but you use a {0} placeholder token in the string representing the location where the user's submitted principal (usually a username or uid) will be substituted at runtime.

For example, if your directory uses an LDAP uid attribute to represent usernames, the User DN for the jsmith user may look like this:

uid=jsmith,ou=users,dc=mycompany,dc=com

in which case you would set this property with the following template value:

uid={0},ou=users,dc=mycompany,dc=com

If no template is configured, the raw AuthenticationToken principal will be used as the LDAP principal. This is likely incorrect as most LDAP directories expect a fully-qualified User DN as opposed to the raw uid or username. So, ensure you set this property to match your environment!

Parameters:
template - the User Distinguished Name template to use for runtime substitution
Throws:
IllegalArgumentException - if the template is null, empty, or does not contain the {0} substitution token.
See Also:
LdapContextFactory.getLdapContext(Object,Object)

getUserDnTemplate

public String getUserDnTemplate()
Returns the User Distinguished Name (DN) template to use when creating User DNs at runtime - see the setUserDnTemplate JavaDoc for a full explanation.

Returns:
the User Distinguished Name (DN) template to use when creating User DNs at runtime.

getUserDn

protected String getUserDn(String principal)
                    throws IllegalArgumentException,
                           IllegalStateException
Returns the LDAP User Distinguished Name (DN) to use when acquiring an LdapContext from the LdapContextFactory.

If the the userDnTemplate property has been set, this implementation will construct the User DN by substituting the specified principal into the configured template. If the userDnTemplate has not been set, the method argument will be returned directly (indicating that the submitted authentication token principal is the User DN).

Parameters:
principal - the principal to substitute into the configured userDnTemplate.
Returns:
the constructed User DN to use at runtime when acquiring an LdapContext.
Throws:
IllegalArgumentException - if the method argument is null or empty
IllegalStateException - if the userDnTemplate has not been set.
See Also:
LdapContextFactory.getLdapContext(Object, Object)

setContextFactory

public void setContextFactory(LdapContextFactory contextFactory)
Sets the LdapContextFactory instance used to acquire connections to the LDAP directory during authentication attempts and authorization queries. Unless specified otherwise, the default is a JndiLdapContextFactory instance.

Parameters:
contextFactory - the LdapContextFactory instance used to acquire connections to the LDAP directory during authentication attempts and authorization queries

getContextFactory

public LdapContextFactory getContextFactory()
Returns the LdapContextFactory instance used to acquire connections to the LDAP directory during authentication attempts and authorization queries. Unless specified otherwise, the default is a JndiLdapContextFactory instance.

Returns:
the LdapContextFactory instance used to acquire connections to the LDAP directory during authentication attempts and authorization queries

doGetAuthenticationInfo

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
                                              throws AuthenticationException
Delegates to queryForAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken, LdapContextFactory), wrapping any NamingExceptions in a Shiro AuthenticationException to satisfy the parent method signature.

Specified by:
doGetAuthenticationInfo in class AuthenticatingRealm
Parameters:
token - the authentication token containing the user's principal and credentials.
Returns:
the AuthenticationInfo acquired after a successful authentication attempt
Throws:
AuthenticationException - if the authentication attempt fails or if a NamingException occurs.

doGetAuthorizationInfo

protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals)
Description copied from class: AuthorizingRealm
Retrieves the AuthorizationInfo for the given principals from the underlying data store. When returning an instance from this method, you might want to consider using an instance of SimpleAuthorizationInfo, as it is suitable in most cases.

Specified by:
doGetAuthorizationInfo in class AuthorizingRealm
Parameters:
principals - the primary identifying principals of the AuthorizationInfo that should be retrieved.
Returns:
the AuthorizationInfo associated with this principals.
See Also:
SimpleAuthorizationInfo

getLdapPrincipal

protected Object getLdapPrincipal(AuthenticationToken token)
Returns the principal to use when creating the LDAP connection for an authentication attempt.

This implementation uses a heuristic: it checks to see if the specified token's principal is a String, and if so, converts it from what is assumed to be a raw uid or username String into a User DN String. Almost all LDAP directories expect the authentication connection to present a User DN and not an unqualified username or uid.

If the token's principal is not a String, it is assumed to already be in the format supported by the underlying LdapContextFactory implementation and the raw principal is returned directly.

Parameters:
token - the AuthenticationToken submitted during the authentication process
Returns:
the User DN or raw principal to use to acquire the LdapContext.
See Also:
LdapContextFactory.getLdapContext(Object, Object)

queryForAuthenticationInfo

protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token,
                                                        LdapContextFactory ldapContextFactory)
                                                 throws NamingException
This implementation opens an LDAP connection using the token's discovered principal and provided credentials. If the connection opens successfully, the authentication attempt is immediately considered successful and a new AuthenticationInfo instance is created and returned. If the connection cannot be opened, either because LDAP authentication failed or some other JNDI problem, an NamingException will be thrown.

Parameters:
token - the submitted authentication token that triggered the authentication attempt.
ldapContextFactory - factory used to retrieve LDAP connections.
Returns:
an AuthenticationInfo instance representing the authenticated user's information.
Throws:
NamingException - if any LDAP errors occur.

createAuthenticationInfo

protected AuthenticationInfo createAuthenticationInfo(AuthenticationToken token,
                                                      Object ldapPrincipal,
                                                      Object ldapCredentials,
                                                      LdapContext ldapContext)
                                               throws NamingException
Returns the AuthenticationInfo resulting from a Subject's successful LDAP authentication attempt.

This implementation ignores the ldapPrincipal, ldapCredentials, and the opened ldapContext arguments and merely returns an AuthenticationInfo instance mirroring the submitted token's principal and credentials. This is acceptable because this method is only ever invoked after a successful authentication attempt, which means the provided principal and credentials were correct, and can be used directly to populate the (now verified) AuthenticationInfo.

Subclasses however are free to override this method for more advanced construction logic.

Parameters:
token - the submitted AuthenticationToken that resulted in a successful authentication
ldapPrincipal - the LDAP principal used when creating the LDAP connection. Unlike the token's principal, this value is usually a constructed User DN and not a simple username or uid. The exact value is depending on the configured LDAP authentication mechanism in use.
ldapCredentials - the LDAP credentials used when creating the LDAP connection.
ldapContext - the LdapContext created that resulted in a successful authentication. It can be used further by subclasses for more complex operations. It does not need to be closed - it will be closed automatically after this method returns.
Returns:
the AuthenticationInfo resulting from a Subject's successful LDAP authentication attempt.
Throws:
NamingException - if there was any problem using the LdapContext

queryForAuthorizationInfo

protected AuthorizationInfo queryForAuthorizationInfo(PrincipalCollection principals,
                                                      LdapContextFactory ldapContextFactory)
                                               throws NamingException
Method that should be implemented by subclasses to build an AuthorizationInfo object by querying the LDAP context for the specified principal.

Parameters:
principals - the principals of the Subject whose AuthenticationInfo should be queried from the LDAP server.
ldapContextFactory - factory used to retrieve LDAP connections.
Returns:
an AuthorizationInfo instance containing information retrieved from the LDAP server.
Throws:
NamingException - if any LDAP errors occur during the search.


Copyright © 2004-2012 The Apache Software Foundation. All Rights Reserved.