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 aCacheManager
of course), but NOTE: ONLY enable authentication caching if either of the following is true for your realm implementation:- The
doGetAuthenticationInfo
implementation returnsAuthenticationInfo
instances where thecredentials
are securely obfuscated and NOT plaintext (raw) credentials. For example, if your realm references accounts with passwords, that theAuthenticationInfo
'scredentials
are safely hashed and salted or otherwise fully encrypted. - The
doGetAuthenticationInfo
implementation returnsAuthenticationInfo
instances where thecredentials
are plaintext (raw) AND the cache region storing theAuthenticationInfo
instances 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 void
afterCacheManagerSet()
This implementation attempts to acquire an authentication cache if one is not already configured.protected void
assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info)
Asserts that the submittedAuthenticationToken
's credentials match the stored accountAuthenticationInfo
's credentials, and if not, throws anAuthenticationException
.protected void
clearCachedAuthenticationInfo(PrincipalCollection principals)
Clears out the AuthenticationInfo cache entry for the specified account.protected void
doClearCache(PrincipalCollection principals)
This implementation clears out any cached authentication data by callingclearCachedAuthenticationInfo(org.apache.shiro.subject.PrincipalCollection)
.protected abstract AuthenticationInfo
doGetAuthenticationInfo(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 aCache
instance to use for authentication caching, ornull
if no cache has been set.protected Object
getAuthenticationCacheKey(AuthenticationToken token)
Returns the key under whichAuthenticationInfo
instances are cached if authentication caching is enabled.protected Object
getAuthenticationCacheKey(PrincipalCollection principals)
Returns the key under whichAuthenticationInfo
instances are cached if authentication caching is enabled.String
getAuthenticationCacheName()
Returns the name of aCache
to lookup from any availablecacheManager
if a cache is not explicitly configured viasetAuthenticationCache(org.apache.shiro.cache.Cache)
.AuthenticationInfo
getAuthenticationInfo(AuthenticationToken token)
This implementation functions as follows: It attempts to acquire any cachedAuthenticationInfo
corresponding to the specifiedAuthenticationToken
argument.Class
getAuthenticationTokenClass()
Returns the authenticationToken class supported by this realm.CredentialsMatcher
getCredentialsMatcher()
Returns theCredentialsMatcher
used during an authentication attempt to verify submitted credentials with those stored in the system.void
init()
Initializes this realm and potentially enables an authentication cache, depending on configuration.boolean
isAuthenticationCachingEnabled()
Returnstrue
if authentication caching should be utilized if aCacheManager
has beenconfigured
,false
otherwise.protected boolean
isAuthenticationCachingEnabled(AuthenticationToken token, AuthenticationInfo info)
Returnstrue
if authentication caching should be utilized based on the specifiedAuthenticationToken
and/orAuthenticationInfo
,false
otherwise.protected void
onInit()
Template method for subclasses to implement any initialization logic.void
setAuthenticationCache(org.apache.shiro.cache.Cache<Object,AuthenticationInfo> authenticationCache)
Sets an explicitCache
instance to use for authentication caching.void
setAuthenticationCacheName(String authenticationCacheName)
Sets the name of aCache
to lookup from any availablecacheManager
if a cache is not explicitly configured viasetAuthenticationCache(org.apache.shiro.cache.Cache)
.void
setAuthenticationCachingEnabled(boolean authenticationCachingEnabled)
Sets whether or not authentication caching should be utilized if aCacheManager
has beenconfigured
,false
otherwise.void
setAuthenticationTokenClass(Class<? extends AuthenticationToken> authenticationTokenClass)
Sets the authenticationToken class supported by this realm.void
setCredentialsMatcher(CredentialsMatcher credentialsMatcher)
Sets the CrendialsMatcher used during an authentication attempt to verify submitted credentials with those stored in the system.void
setName(String name)
boolean
supports(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 theCredentialsMatcher
used during an authentication attempt to verify submitted credentials with those stored in the system.Unless overridden by the
setCredentialsMatcher
method, the default value is aSimpleCredentialsMatcher
instance.- Returns:
- the
CredentialsMatcher
used 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
SimpleCredentialsMatcher
instance.- 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 class
if 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.class
to 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 explicitCache
instance to use for authentication caching. If not set and authentication caching isenabled
, any availablecacheManager
will 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 explicitCache
instance to use for authentication caching ornull
if 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 aCache
instance to use for authentication caching, ornull
if no cache has been set.- Returns:
- a
Cache
instance to use for authentication caching, ornull
if 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 aCache
to lookup from any availablecacheManager
if 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
Cache
to lookup from any availablecacheManager
if 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 aCache
to lookup from any availablecacheManager
if 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 aCache
to lookup from any availablecacheManager
if a cache is not explicitly configured viasetAuthenticationCache(org.apache.shiro.cache.Cache)
.- Since:
- 1.2
- See Also:
isAuthenticationCachingEnabled()
-
isAuthenticationCachingEnabled
public boolean isAuthenticationCachingEnabled()
Returnstrue
if authentication caching should be utilized if aCacheManager
has beenconfigured
,false
otherwise. The default value istrue
.- Returns:
true
if authentication caching should be utilized,false
otherwise.
-
setAuthenticationCachingEnabled
public void setAuthenticationCachingEnabled(boolean authenticationCachingEnabled)
Sets whether or not authentication caching should be utilized if aCacheManager
has beenconfigured
,false
otherwise. The default value isfalse
to retain backwards compatibility with Shiro 1.1 and earlier. WARNING: Only set this property totrue
if 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:
setName
in interfaceorg.apache.shiro.util.Nameable
- Overrides:
setName
in 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
cache
property 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
cache
property has not been set, thecacheManager
property will be checked. If acacheManager
has 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) authenticationCache
orcacheManager
properties 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:
init
in 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:
afterCacheManagerSet
in classCachingRealm
- Since:
- 1.2
-
isAuthenticationCachingEnabled
protected boolean isAuthenticationCachingEnabled(AuthenticationToken token, AuthenticationInfo info)
Returnstrue
if authentication caching should be utilized based on the specifiedAuthenticationToken
and/orAuthenticationInfo
,false
otherwise. 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
- theAuthenticationInfo
acquired from data source lookup viadoGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
- Returns:
true
if authentication caching should be utilized based on the specifiedAuthenticationToken
and/orAuthenticationInfo
,false
otherwise.- Since:
- 1.2
-
getAuthenticationInfo
public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException
This implementation functions as follows:- It attempts to acquire any cached
AuthenticationInfo
corresponding to the specifiedAuthenticationToken
argument. 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
AuthenticationInfo
found, 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 becached
to be used in future authentication attempts. - If an AuthenticationInfo instance is not found in the cache or by lookup,
null
is 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:
getAuthenticationInfo
in interfaceRealm
- Parameters:
token
- the submitted account principal and credentials.- Returns:
- the AuthenticationInfo corresponding to the given
token
, ornull
if 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 whichAuthenticationInfo
instances 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 cachedAuthenticationInfo
on 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
AuthenticationInfo
after a successful authentication. - Since:
- 1.2
-
getAuthenticationCacheKey
protected Object getAuthenticationCacheKey(PrincipalCollection principals)
Returns the key under whichAuthenticationInfo
instances 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 cachedAuthenticationInfo
on 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
AuthenticationInfo
instances. - 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.doClearCache
to ensure this behavior is maintained.- Overrides:
doClearCache
in 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. Anull
return 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
AuthenticationInfo
object 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
-
-