Class AuthenticatingRealm
- java.lang.Object
-
- org.apache.shiro.realm.CachingRealm
-
- org.apache.shiro.realm.AuthenticatingRealm
-
- All Implemented Interfaces:
LogoutAware,org.apache.shiro.cache.CacheManagerAware,Realm,org.apache.shiro.util.Initializable,org.apache.shiro.util.Nameable
- Direct Known Subclasses:
AuthorizingRealm
public abstract class AuthenticatingRealm extends CachingRealm implements org.apache.shiro.util.Initializable
A top-level abstract implementation of the Realm interface that only implements authentication support (log-in) operations and leaves authorization (access control) behavior to subclasses.Authentication Caching
For applications that perform frequent repeated authentication of the same accounts (e.g. as is often done in REST or Soap applications that authenticate on every request), it might be prudent to enable authentication caching to alleviate constant load on any back-end data sources. This feature is disabled by default to retain backwards-compatibility with Shiro 1.1 and earlier. It may be enabled by settingauthenticationCachingEnabled=true(and configuring Shiro with aCacheManagerof course), but NOTE: ONLY enable authentication caching if either of the following is true for your realm implementation:- The
doGetAuthenticationInfoimplementation returnsAuthenticationInfoinstances where thecredentialsare securely obfuscated and NOT plaintext (raw) credentials. For example, if your realm references accounts with passwords, that theAuthenticationInfo'scredentialsare safely hashed and salted or otherwise fully encrypted. - The
doGetAuthenticationInfoimplementation returnsAuthenticationInfoinstances where thecredentialsare plaintext (raw) AND the cache region storing theAuthenticationInfoinstances WILL NOT overflow to disk and WILL NOT transmit cache entries over an unprotected (non TLS/SSL) network (as might be the case with a networked/distributed enterprise cache). This should be the case even in private/trusted/corporate networks.
cache.put(cacheKey, subclassAuthenticationInfoInstance);
Enabling authentication caching is ONLY safe to do if the above two scenarios apply. It is NOT safe to enable under any other scenario. When possible, always represent and store credentials in a safe form (hash+salt or encrypted) to eliminate plaintext visibility.Authentication Cache Invalidation on Logout
If authentication caching is enabled, this implementation will attempt to evict (remove) cached authentication data for an account during logout. This can only occur if thegetAuthenticationCacheKey(org.apache.shiro.authc.AuthenticationToken)andgetAuthenticationCacheKey(org.apache.shiro.subject.PrincipalCollection)methods return the exact same value. The default implementations of these methods expect that theAuthenticationToken.getPrincipal()(what the user submits during login) andgetAvailablePrincipal(what is returned by the realm after account lookup) return the same exact value. For example, the user submitted username is also the primary account identifier. However, if your application uses, say, a username for end-user login, but returns a primary key ID as the primary principal after authentication, then you will need to override eithergetAuthenticationCacheKey(token)orgetAuthenticationCacheKey(principals)(or both) to ensure that the same cache key can be used for either object. This guarantees that the same cache key used to cache the data during authentication (derived from theAuthenticationToken) will be used to remove the cached data during logout (derived from thePrincipalCollection).Unmatching Cache Key Values
If the return values fromgetAuthenticationCacheKey(org.apache.shiro.authc.AuthenticationToken)andgetAuthenticationCacheKey(org.apache.shiro.subject.PrincipalCollection)are not identical, cached authentication data removal is at the mercy of your cache provider settings. For example, often cache implementations will evict cache entries based on a timeToIdle or timeToLive (TTL) value. If this lazy eviction capability of the cache product is not sufficient and you want discrete behavior (highly recommended for authentication data), ensure that the return values from those two methods are identical in the subclass implementation.- Since:
- 0.2
-
-
Constructor Summary
Constructors Constructor Description AuthenticatingRealm()AuthenticatingRealm(CredentialsMatcher matcher)AuthenticatingRealm(org.apache.shiro.cache.CacheManager cacheManager)AuthenticatingRealm(org.apache.shiro.cache.CacheManager cacheManager, CredentialsMatcher matcher)
-
Method Summary
All Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description protected voidafterCacheManagerSet()This implementation attempts to acquire an authentication cache if one is not already configured.protected voidassertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info)Asserts that the submittedAuthenticationToken's credentials match the stored accountAuthenticationInfo's credentials, and if not, throws anAuthenticationException.protected voidclearCachedAuthenticationInfo(PrincipalCollection principals)Clears out the AuthenticationInfo cache entry for the specified account.protected voiddoClearCache(PrincipalCollection principals)This implementation clears out any cached authentication data by callingclearCachedAuthenticationInfo(org.apache.shiro.subject.PrincipalCollection).protected abstract AuthenticationInfodoGetAuthenticationInfo(AuthenticationToken token)Retrieves authentication data from an implementation-specific datasource (RDBMS, LDAP, etc) for the given authentication token.org.apache.shiro.cache.Cache<Object,AuthenticationInfo>getAuthenticationCache()Returns aCacheinstance to use for authentication caching, ornullif no cache has been set.protected ObjectgetAuthenticationCacheKey(AuthenticationToken token)Returns the key under whichAuthenticationInfoinstances are cached if authentication caching is enabled.protected ObjectgetAuthenticationCacheKey(PrincipalCollection principals)Returns the key under whichAuthenticationInfoinstances are cached if authentication caching is enabled.StringgetAuthenticationCacheName()Returns the name of aCacheto lookup from any availablecacheManagerif a cache is not explicitly configured viasetAuthenticationCache(org.apache.shiro.cache.Cache).AuthenticationInfogetAuthenticationInfo(AuthenticationToken token)This implementation functions as follows: It attempts to acquire any cachedAuthenticationInfocorresponding to the specifiedAuthenticationTokenargument.ClassgetAuthenticationTokenClass()Returns the authenticationToken class supported by this realm.CredentialsMatchergetCredentialsMatcher()Returns theCredentialsMatcherused during an authentication attempt to verify submitted credentials with those stored in the system.voidinit()Initializes this realm and potentially enables an authentication cache, depending on configuration.booleanisAuthenticationCachingEnabled()Returnstrueif authentication caching should be utilized if aCacheManagerhas beenconfigured,falseotherwise.protected booleanisAuthenticationCachingEnabled(AuthenticationToken token, AuthenticationInfo info)Returnstrueif authentication caching should be utilized based on the specifiedAuthenticationTokenand/orAuthenticationInfo,falseotherwise.protected voidonInit()Template method for subclasses to implement any initialization logic.voidsetAuthenticationCache(org.apache.shiro.cache.Cache<Object,AuthenticationInfo> authenticationCache)Sets an explicitCacheinstance to use for authentication caching.voidsetAuthenticationCacheName(String authenticationCacheName)Sets the name of aCacheto lookup from any availablecacheManagerif a cache is not explicitly configured viasetAuthenticationCache(org.apache.shiro.cache.Cache).voidsetAuthenticationCachingEnabled(boolean authenticationCachingEnabled)Sets whether or not authentication caching should be utilized if aCacheManagerhas beenconfigured,falseotherwise.voidsetAuthenticationTokenClass(Class<? extends AuthenticationToken> authenticationTokenClass)Sets the authenticationToken class supported by this realm.voidsetCredentialsMatcher(CredentialsMatcher credentialsMatcher)Sets the CrendialsMatcher used during an authentication attempt to verify submitted credentials with those stored in the system.voidsetName(String name)booleansupports(AuthenticationToken token)Convenience implementation that returns getAuthenticationTokenClass().isAssignableFrom( token.getClass() );.-
Methods inherited from class org.apache.shiro.realm.CachingRealm
clearCache, getAvailablePrincipal, getCacheManager, getName, isCachingEnabled, onLogout, setCacheManager, setCachingEnabled
-
-
-
-
Constructor Detail
-
AuthenticatingRealm
public AuthenticatingRealm()
-
AuthenticatingRealm
public AuthenticatingRealm(org.apache.shiro.cache.CacheManager cacheManager)
-
AuthenticatingRealm
public AuthenticatingRealm(CredentialsMatcher matcher)
-
AuthenticatingRealm
public AuthenticatingRealm(org.apache.shiro.cache.CacheManager cacheManager, CredentialsMatcher matcher)
-
-
Method Detail
-
getCredentialsMatcher
public CredentialsMatcher getCredentialsMatcher()
Returns theCredentialsMatcherused during an authentication attempt to verify submitted credentials with those stored in the system.Unless overridden by the
setCredentialsMatchermethod, the default value is aSimpleCredentialsMatcherinstance.- Returns:
- the
CredentialsMatcherused during an authentication attempt to verify submitted credentials with those stored in the system.
-
setCredentialsMatcher
public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher)
Sets the CrendialsMatcher used during an authentication attempt to verify submitted credentials with those stored in the system. The implementation of this matcher can be switched via configuration to support any number of schemes, including plain text comparisons, hashing comparisons, and others.Unless overridden by this method, the default value is a
SimpleCredentialsMatcherinstance.- Parameters:
credentialsMatcher- the matcher to use.
-
getAuthenticationTokenClass
public Class getAuthenticationTokenClass()
Returns the authenticationToken class supported by this realm.The default value is
UsernamePasswordToken.class, since about 90% of realms use username/password authentication, regardless of their protocol (e.g. over jdbc, ldap, kerberos, http, etc).If subclasses haven't already overridden the
Realm.supports(AuthenticationToken)method, they mustset a new classif they won't support UsernamePasswordToken authentication token submissions.- Returns:
- the authenticationToken class supported by this realm.
- See Also:
setAuthenticationTokenClass(java.lang.Class<? extends org.apache.shiro.authc.AuthenticationToken>)
-
setAuthenticationTokenClass
public void setAuthenticationTokenClass(Class<? extends AuthenticationToken> authenticationTokenClass)
Sets the authenticationToken class supported by this realm.Unless overridden by this method, the default value is
UsernamePasswordToken.classto support the majority of applications.- Parameters:
authenticationTokenClass- the class of authentication token instances supported by this realm.- See Also:
getAuthenticationTokenClass() for more explanation.
-
setAuthenticationCache
public void setAuthenticationCache(org.apache.shiro.cache.Cache<Object,AuthenticationInfo> authenticationCache)
Sets an explicitCacheinstance to use for authentication caching. If not set and authentication caching isenabled, any availablecacheManagerwill be used to acquire the cache instance if available. WARNING: Only set this property if safe caching conditions apply, as documented at the top of this page in the class-level JavaDoc.- Parameters:
authenticationCache- an explicitCacheinstance to use for authentication caching ornullif the cache should possibly be obtained another way.- Since:
- 1.2
- See Also:
isAuthenticationCachingEnabled()
-
getAuthenticationCache
public org.apache.shiro.cache.Cache<Object,AuthenticationInfo> getAuthenticationCache()
Returns aCacheinstance to use for authentication caching, ornullif no cache has been set.- Returns:
- a
Cacheinstance to use for authentication caching, ornullif no cache has been set. - Since:
- 1.2
- See Also:
setAuthenticationCache(org.apache.shiro.cache.Cache),isAuthenticationCachingEnabled()
-
getAuthenticationCacheName
public String getAuthenticationCacheName()
Returns the name of aCacheto lookup from any availablecacheManagerif a cache is not explicitly configured viasetAuthenticationCache(org.apache.shiro.cache.Cache). This name will only be used to look up a cache if authentication caching isenabled. WARNING: Only set this property if safe caching conditions apply, as documented at the top of this page in the class-level JavaDoc.- Returns:
- the name of a
Cacheto lookup from any availablecacheManagerif a cache is not explicitly configured viasetAuthenticationCache(org.apache.shiro.cache.Cache). - Since:
- 1.2
- See Also:
isAuthenticationCachingEnabled()
-
setAuthenticationCacheName
public void setAuthenticationCacheName(String authenticationCacheName)
Sets the name of aCacheto lookup from any availablecacheManagerif a cache is not explicitly configured viasetAuthenticationCache(org.apache.shiro.cache.Cache). This name will only be used to look up a cache if authentication caching isenabled.- Parameters:
authenticationCacheName- the name of aCacheto lookup from any availablecacheManagerif a cache is not explicitly configured viasetAuthenticationCache(org.apache.shiro.cache.Cache).- Since:
- 1.2
- See Also:
isAuthenticationCachingEnabled()
-
isAuthenticationCachingEnabled
public boolean isAuthenticationCachingEnabled()
Returnstrueif authentication caching should be utilized if aCacheManagerhas beenconfigured,falseotherwise. The default value istrue.- Returns:
trueif authentication caching should be utilized,falseotherwise.
-
setAuthenticationCachingEnabled
public void setAuthenticationCachingEnabled(boolean authenticationCachingEnabled)
Sets whether or not authentication caching should be utilized if aCacheManagerhas beenconfigured,falseotherwise. The default value isfalseto retain backwards compatibility with Shiro 1.1 and earlier. WARNING: Only set this property totrueif safe caching conditions apply, as documented at the top of this page in the class-level JavaDoc.- Parameters:
authenticationCachingEnabled- the value to set
-
setName
public void setName(String name)
- Specified by:
setNamein interfaceorg.apache.shiro.util.Nameable- Overrides:
setNamein classCachingRealm
-
supports
public boolean supports(AuthenticationToken token)
Convenience implementation that returns getAuthenticationTokenClass().isAssignableFrom( token.getClass() );. Can be overridden by subclasses for more complex token checking.Most configurations will only need to set a different class via
setAuthenticationTokenClass(java.lang.Class<? extends org.apache.shiro.authc.AuthenticationToken>), as opposed to overriding this method.
-
init
public final void init()
Initializes this realm and potentially enables an authentication cache, depending on configuration. Based on the availability of an authentication cache, this class functions as follows:- If the
cacheproperty has been set, it will be used to cache the AuthenticationInfo objects returned fromgetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)method invocations. All future calls togetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)will attempt to use this cache first to alleviate any potentially unnecessary calls to an underlying data store. - If the
cacheproperty has not been set, thecacheManagerproperty will be checked. If acacheManagerhas been set, it will be used to eagerly acquire an authenticationcache, and this cache which will be used as specified in #1. - If neither the
(org.apache.shiro.cache.Cache) authenticationCacheorcacheManagerproperties are set, caching will not be utilized and authentication look-ups will be delegated to subclass implementations for each authentication attempt.
onInit()is to allow subclasses to perform any init behavior desired.- Specified by:
initin interfaceorg.apache.shiro.util.Initializable- Since:
- 1.2
- If the
-
onInit
protected void onInit()
Template method for subclasses to implement any initialization logic. Called frominit().- Since:
- 1.2
-
afterCacheManagerSet
protected void afterCacheManagerSet()
This implementation attempts to acquire an authentication cache if one is not already configured.- Overrides:
afterCacheManagerSetin classCachingRealm- Since:
- 1.2
-
isAuthenticationCachingEnabled
protected boolean isAuthenticationCachingEnabled(AuthenticationToken token, AuthenticationInfo info)
Returnstrueif authentication caching should be utilized based on the specifiedAuthenticationTokenand/orAuthenticationInfo,falseotherwise. The default implementation simply delegates toisAuthenticationCachingEnabled(), the general-case authentication caching setting. Subclasses can override this to turn on or off caching at runtime based on the specific submitted runtime values.- Parameters:
token- the submitted authentication tokeninfo- theAuthenticationInfoacquired from data source lookup viadoGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)- Returns:
trueif authentication caching should be utilized based on the specifiedAuthenticationTokenand/orAuthenticationInfo,falseotherwise.- Since:
- 1.2
-
getAuthenticationInfo
public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException
This implementation functions as follows:- It attempts to acquire any cached
AuthenticationInfocorresponding to the specifiedAuthenticationTokenargument. If a cached value is found, it will be used for credentials matching, alleviating the need to perform any lookups with a data source. - If there is no cached
AuthenticationInfofound, delegate to thedoGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)method to perform the actual lookup. If authentication caching is enabled and possible, any returned info object will becachedto be used in future authentication attempts. - If an AuthenticationInfo instance is not found in the cache or by lookup,
nullis returned to indicate an account cannot be found. - If an AuthenticationInfo instance is found (either cached or via lookup), ensure the submitted
AuthenticationToken's credentials match the expected
AuthenticationInfo's credentials using thecredentialsMatcher. This means that credentials are always verified for an authentication attempt.
- Specified by:
getAuthenticationInfoin interfaceRealm- Parameters:
token- the submitted account principal and credentials.- Returns:
- the AuthenticationInfo corresponding to the given
token, ornullif no AuthenticationInfo could be found. - Throws:
AuthenticationException- if authentication failed.
- It attempts to acquire any cached
-
assertCredentialsMatch
protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException
Asserts that the submittedAuthenticationToken's credentials match the stored accountAuthenticationInfo's credentials, and if not, throws anAuthenticationException.- Parameters:
token- the submitted authentication tokeninfo- the AuthenticationInfo corresponding to the giventoken- Throws:
AuthenticationException- if the token's credentials do not match the stored account credentials.
-
getAuthenticationCacheKey
protected Object getAuthenticationCacheKey(AuthenticationToken token)
Returns the key under whichAuthenticationInfoinstances are cached if authentication caching is enabled. This implementation defaults to returning the token'sprincipal, which is usually a username in most applications.Cache Invalidation on Logout
NOTE: If you want to be able to invalidate an account's cachedAuthenticationInfoon logout, you must ensure thegetAuthenticationCacheKey(org.apache.shiro.subject.PrincipalCollection)method returns the same value as this method.- Parameters:
token- the authentication token for which any successful authentication will be cached.- Returns:
- the cache key to use to cache the associated
AuthenticationInfoafter a successful authentication. - Since:
- 1.2
-
getAuthenticationCacheKey
protected Object getAuthenticationCacheKey(PrincipalCollection principals)
Returns the key under whichAuthenticationInfoinstances are cached if authentication caching is enabled. This implementation delegates toCachingRealm.getAvailablePrincipal(org.apache.shiro.subject.PrincipalCollection), which returns the primary principal associated with this particular Realm.Cache Invalidation on Logout
NOTE: If you want to be able to invalidate an account's cachedAuthenticationInfoon logout, you must ensure that this method returns the same value as thegetAuthenticationCacheKey(org.apache.shiro.authc.AuthenticationToken)method!- Parameters:
principals- the principals of the account for which to set or remove cachedAuthenticationInfo.- Returns:
- the cache key to use when looking up cached
AuthenticationInfoinstances. - Since:
- 1.2
-
doClearCache
protected void doClearCache(PrincipalCollection principals)
This implementation clears out any cached authentication data by callingclearCachedAuthenticationInfo(org.apache.shiro.subject.PrincipalCollection). If overriding in a subclass, be sure to callsuper.doClearCacheto ensure this behavior is maintained.- Overrides:
doClearCachein classCachingRealm- Parameters:
principals- principals the principals of the account for which to clear any cached data.- Since:
- 1.2
-
clearCachedAuthenticationInfo
protected void clearCachedAuthenticationInfo(PrincipalCollection principals)
Clears out the AuthenticationInfo cache entry for the specified account. This method is provided as a convenience to subclasses so they can invalidate a cache entry when they change an account's authentication data (e.g. reset password) during runtime. Because an account's AuthenticationInfo can be cached, there needs to be a way to invalidate the cache for only that account so that subsequent authentication operations don't used the (old) cached value if account data changes. After this method is called, the next authentication for that same account will result in a call todoGetAuthenticationInfo, and the resulting return value will be cached before being returned so it can be reused for later authentications. If you wish to clear out all associated cached data (and not just authentication data), use theCachingRealm.clearCache(org.apache.shiro.subject.PrincipalCollection)method instead (which will in turn call this method by default).- Parameters:
principals- the principals of the account for which to clear the cached AuthorizationInfo.- Since:
- 1.2
- See Also:
CachingRealm.clearCache(org.apache.shiro.subject.PrincipalCollection)
-
doGetAuthenticationInfo
protected abstract AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException
Retrieves authentication data from an implementation-specific datasource (RDBMS, LDAP, etc) for the given authentication token. For most datasources, this means just 'pulling' authentication data for an associated subject/user and nothing more and letting Shiro do the rest. But in some systems, this method could actually perform EIS specific log-in logic in addition to just retrieving data - it is up to the Realm implementation. Anullreturn value means that no account could be associated with the specified token.- Parameters:
token- the authentication token containing the user's principal and credentials.- Returns:
- an
AuthenticationInfoobject containing account data resulting from the authentication ONLY if the lookup is successful (i.e. account exists and is valid, etc.) - Throws:
AuthenticationException- if there is an error acquiring data or performing realm-specific authentication logic for the specified token
-
-