Package org.apache.shiro.realm.ldap
Class DefaultLdapRealm
- java.lang.Object
-
- org.apache.shiro.realm.CachingRealm
-
- org.apache.shiro.realm.AuthenticatingRealm
-
- org.apache.shiro.realm.AuthorizingRealm
-
- org.apache.shiro.realm.ldap.DefaultLdapRealm
-
- All Implemented Interfaces:
LogoutAware,Authorizer,PermissionResolverAware,RolePermissionResolverAware,org.apache.shiro.cache.CacheManagerAware,Realm,org.apache.shiro.util.Initializable,org.apache.shiro.util.Nameable
- Direct Known Subclasses:
JndiLdapRealm
public class DefaultLdapRealm extends AuthorizingRealm
An LDAPRealmimplementation 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 backingJndiLdapContextFactoryshould 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 submittedAuthenticationToken'sprincipalis a simple username, but the LDAP directory expects a complete User Distinguished Name (User DN) to establish a connection, theuserDnTemplateproperty 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 defaultdoGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)implementation returningnull. 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 theuserDnTemplateproperty to allow you to specify the your LDAP server's User DN format. Most other configuration is performed via the nestedcontextFactoryproperty. For example, defining this realm in Shiro .ini:[main] ldapRealm = org.apache.shiro.realm.ldap.DefaultLdapRealm 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 defaultcontextFactoryinstance is aJndiLdapContextFactory. See that class's JavaDoc for more information on configuring the LDAP connection as well as specifying JNDI environment properties as necessary.- Since:
- 1.3
- See Also:
JndiLdapContextFactory
-
-
Constructor Summary
Constructors Constructor Description DefaultLdapRealm()Default no-argument constructor that defaults the internalLdapContextFactoryinstance to aJndiLdapContextFactory.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description protected AuthenticationInfocreateAuthenticationInfo(AuthenticationToken token, Object ldapPrincipal, Object ldapCredentials, LdapContext ldapContext)Returns theAuthenticationInforesulting from a Subject's successful LDAP authentication attempt.protected AuthenticationInfodoGetAuthenticationInfo(AuthenticationToken token)Delegates toqueryForAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken, LdapContextFactory), wrapping anyNamingExceptions in a ShiroAuthenticationExceptionto satisfy the parent method signature.protected AuthorizationInfodoGetAuthorizationInfo(PrincipalCollection principals)Retrieves the AuthorizationInfo for the given principals from the underlying data store.LdapContextFactorygetContextFactory()Returns the LdapContextFactory instance used to acquire connections to the LDAP directory during authentication attempts and authorization queries.protected ObjectgetLdapPrincipal(AuthenticationToken token)Returns the principal to use when creating the LDAP connection for an authentication attempt.protected StringgetUserDn(String principal)Returns the LDAP User Distinguished Name (DN) to use when acquiring anLdapContextfrom theLdapContextFactory.protected StringgetUserDnPrefix()Returns the User DN prefix to use when building a runtime User DN value ornullif nouserDnTemplatehas been configured.protected StringgetUserDnSuffix()Returns the User DN suffix to use when building a runtime User DN value.StringgetUserDnTemplate()Returns the User Distinguished Name (DN) template to use when creating User DNs at runtime - see thesetUserDnTemplateJavaDoc for a full explanation.protected AuthenticationInfoqueryForAuthenticationInfo(AuthenticationToken token, LdapContextFactory ldapContextFactory)This implementation opens an LDAP connection using the token'sdiscovered principaland providedcredentials.protected AuthorizationInfoqueryForAuthorizationInfo(PrincipalCollection principals, LdapContextFactory ldapContextFactory)Method that should be implemented by subclasses to build anAuthorizationInfoobject by querying the LDAP context for the specified principal.voidsetContextFactory(LdapContextFactory contextFactory)Sets the LdapContextFactory instance used to acquire connections to the LDAP directory during authentication attempts and authorization queries.voidsetUserDnTemplate(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, getPermissions, getRolePermissionResolver, hasAllRoles, hasRole, hasRole, hasRoles, hasRoles, isAuthorizationCachingEnabled, isPermitted, 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
-
-
-
-
Constructor Detail
-
DefaultLdapRealm
public DefaultLdapRealm()
Default no-argument constructor that defaults the internalLdapContextFactoryinstance to aJndiLdapContextFactory.
-
-
Method Detail
-
getUserDnPrefix
protected String getUserDnPrefix()
Returns the User DN prefix to use when building a runtime User DN value ornullif nouserDnTemplatehas been configured. If configured, this value is the text that occurs before theUSERDN_SUBSTITUTION_TOKENin theuserDnTemplatevalue.- Returns:
- the the User DN prefix to use when building a runtime User DN value or
nullif nouserDnTemplatehas been configured.
-
getUserDnSuffix
protected String getUserDnSuffix()
Returns the User DN suffix to use when building a runtime User DN value. ornullif nouserDnTemplatehas been configured. If configured, this value is the text that occurs after theUSERDN_SUBSTITUTION_TOKENin theuserDnTemplatevalue.- Returns:
- the User DN suffix to use when building a runtime User DN value or
nullif nouserDnTemplatehas 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 LDAPuidattribute to represent usernames, the User DN for thejsmithuser 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=comIf no template is configured, the rawAuthenticationTokenprincipalwill 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 thesetUserDnTemplateJavaDoc 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 anLdapContextfrom theLdapContextFactory. If the theuserDnTemplateproperty has been set, this implementation will construct the User DN by substituting the specifiedprincipalinto the configured template. If theuserDnTemplatehas 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 configureduserDnTemplate.- Returns:
- the constructed User DN to use at runtime when acquiring an
LdapContext. - Throws:
IllegalArgumentException- if the method argument is null or emptyIllegalStateException- if theuserDnTemplatehas 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 aJndiLdapContextFactoryinstance.- 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 aJndiLdapContextFactoryinstance.- 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 toqueryForAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken, LdapContextFactory), wrapping anyNamingExceptions in a ShiroAuthenticationExceptionto satisfy the parent method signature.- Specified by:
doGetAuthenticationInfoin classAuthenticatingRealm- Parameters:
token- the authentication token containing the user's principal and credentials.- Returns:
- the
AuthenticationInfoacquired after a successful authentication attempt - Throws:
AuthenticationException- if the authentication attempt fails or if aNamingExceptionoccurs.
-
doGetAuthorizationInfo
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals)
Description copied from class:AuthorizingRealmRetrieves 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 ofSimpleAuthorizationInfo, as it is suitable in most cases.- Specified by:
doGetAuthorizationInfoin classAuthorizingRealm- 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'sprincipalis aString, and if so,converts itfrom what is assumed to be a raw uid or usernameStringinto a User DNString. Almost all LDAP directories expect the authentication connection to present a User DN and not an unqualified username or uid. If the token'sprincipalis not a String, it is assumed to already be in the format supported by the underlyingLdapContextFactoryimplementation and the raw principal is returned directly.- Parameters:
token- theAuthenticationTokensubmitted 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'sdiscovered principaland providedcredentials. If the connection opens successfully, the authentication attempt is immediately considered successful and a newAuthenticationInfoinstance iscreatedand returned. If the connection cannot be opened, either because LDAP authentication failed or some other JNDI problem, anNamingExceptionwill be thrown.- Parameters:
token- the submitted authentication token that triggered the authentication attempt.ldapContextFactory- factory used to retrieve LDAP connections.- Returns:
- an
AuthenticationInfoinstance 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 theAuthenticationInforesulting from a Subject's successful LDAP authentication attempt. This implementation ignores theldapPrincipal,ldapCredentials, and the openedldapContextarguments and merely returns anAuthenticationInfoinstance 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 submittedAuthenticationTokenthat resulted in a successful authenticationldapPrincipal- the LDAP principal used when creating the LDAP connection. Unlike the token'sprincipal, 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
AuthenticationInforesulting from a Subject's successful LDAP authentication attempt. - Throws:
NamingException- if there was any problem using theLdapContext
-
queryForAuthorizationInfo
protected AuthorizationInfo queryForAuthorizationInfo(PrincipalCollection principals, LdapContextFactory ldapContextFactory) throws NamingException
Method that should be implemented by subclasses to build anAuthorizationInfoobject 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
AuthorizationInfoinstance containing information retrieved from the LDAP server. - Throws:
NamingException- if any LDAP errors occur during the search.
-
-