Package org.apache.shiro.subject
Interface Subject
-
- All Known Implementing Classes:
DelegatingSubject
public interface SubjectASubjectrepresents state and security operations for a single application user. These operations include authentication (login/logout), authorization (access control), and session access. It is Shiro's primary mechanism for single-user security functionality.Acquiring a Subject
To acquire the currently-executingSubject, application developers will almost always useSecurityUtils:
Almost all security operations should be performed with theSecurityUtils.getSubject()Subjectreturned from this method.Permission methods
Note that there are many *Permission methods in this interface overloaded to accept String arguments instead ofPermissioninstances. They are a convenience allowing the caller to use a String representation of aPermissionif desired. The underlying Authorization subsystem implementations will usually simply convert these String values toPermissioninstances and then just call the corresponding type-safe method. (Shiro's default implementations do String-to-Permission conversion for these methods usingPermissionResolvers.) These overloaded *Permission methods forgo type-safety for the benefit of convenience and simplicity, so you should choose which ones to use based on your preferences and needs.- Since:
- 0.1
-
-
Nested Class Summary
Nested Classes Modifier and Type Interface Description static classSubject.BuilderBuilder design pattern implementation for creatingSubjectinstances in a simplified way without requiring knowledge of Shiro's construction techniques.
-
Method Summary
All Methods Instance Methods Abstract Methods Modifier and Type Method Description RunnableassociateWith(Runnable runnable)Returns aRunnableinstance matching the given argument while additionally ensuring that it will retain and execute under this Subject's identity.<V> Callable<V>associateWith(Callable<V> callable)Returns aCallableinstance matching the given argument while additionally ensuring that it will retain and execute under this Subject's identity.voidcheckPermission(String permission)Ensures this Subject implies the specified permission String.voidcheckPermission(Permission permission)Ensures this Subjectimpliesthe specifiedPermission.voidcheckPermissions(String... permissions)Ensures this Subjectimpliesall of the specified permission strings.voidcheckPermissions(Collection<Permission> permissions)Ensures this Subjectimpliesall of the specified permission strings.voidcheckRole(String roleIdentifier)Asserts this Subject has the specified role by returning quietly if they do or throwing anAuthorizationExceptionif they do not.voidcheckRoles(String... roleIdentifiers)Same ascheckRoles(Collectionbut doesn't require a collection as a an argument.roleIdentifiers) voidcheckRoles(Collection<String> roleIdentifiers)Asserts this Subject has all of the specified roles by returning quietly if they do or throwing anAuthorizationExceptionif they do not.voidexecute(Runnable runnable)Associates the specifiedRunnablewith thisSubjectinstance and then executes it on the currently running thread.<V> Vexecute(Callable<V> callable)Associates the specifiedCallablewith thisSubjectinstance and then executes it on the currently running thread.PrincipalCollectiongetPreviousPrincipals()Returns the previous 'pre run as' identity of thisSubjectbefore assuming the currentrunAsidentity, ornullif thisSubjectis not operating under an assumed identity (normal state).ObjectgetPrincipal()Returns this Subject's application-wide uniquely identifying principal, ornullif this Subject is anonymous because it doesn't yet have any associated account data (for example, if they haven't logged in).PrincipalCollectiongetPrincipals()Returns this Subject's principals (identifying attributes) in the form of aPrincipalCollectionornullif this Subject is anonymous because it doesn't yet have any associated account data (for example, if they haven't logged in).SessiongetSession()Returns the applicationSessionassociated with this Subject.SessiongetSession(boolean create)Returns the applicationSessionassociated with this Subject.booleanhasAllRoles(Collection<String> roleIdentifiers)Returnstrueif this Subject has all of the specified roles,falseotherwise.booleanhasRole(String roleIdentifier)Returnstrueif this Subject has the specified role,falseotherwise.boolean[]hasRoles(List<String> roleIdentifiers)Checks if this Subject has the specified roles, returning a boolean array indicating which roles are associated.booleanisAuthenticated()Returnstrueif this Subject/user proved their identity during their current session by providing valid credentials matching those known to the system,falseotherwise.booleanisPermitted(String permission)Returnstrueif this Subject is permitted to perform an action or access a resource summarized by the specified permission string.boolean[]isPermitted(String... permissions)Checks if this Subject implies the given permission strings and returns a boolean array indicating which permissions are implied.boolean[]isPermitted(List<Permission> permissions)Checks if this Subject implies the given Permissions and returns a boolean array indicating which permissions are implied.booleanisPermitted(Permission permission)Returnstrueif this Subject is permitted to perform an action or access a resource summarized by the specified permission.booleanisPermittedAll(String... permissions)Returnstrueif this Subject implies all of the specified permission strings,falseotherwise.booleanisPermittedAll(Collection<Permission> permissions)Returnstrueif this Subject implies all of the specified permissions,falseotherwise.booleanisRemembered()Returnstrueif thisSubjecthas an identity (it is not anonymous) and the identity (akaprincipals) is remembered from a successful authentication during a previous session.booleanisRunAs()Returnstrueif thisSubjectis 'running as' another identity other than its original one orfalseotherwise (normalSubjectstate).voidlogin(AuthenticationToken token)Performs a login attempt for this Subject/user.voidlogout()Logs out this Subject and invalidates and/or removes any associated entities, such as aSessionand authorization data.PrincipalCollectionreleaseRunAs()Releases the current 'run as' (assumed) identity and reverts back to the previous 'pre run as' identity that existed before#runAs runAswas called.voidrunAs(PrincipalCollection principals)Allows this subject to 'run as' or 'assume' another identity indefinitely.
-
-
-
Method Detail
-
getPrincipal
Object getPrincipal()
Returns this Subject's application-wide uniquely identifying principal, ornullif this Subject is anonymous because it doesn't yet have any associated account data (for example, if they haven't logged in). The term principal is just a fancy security term for any identifying attribute(s) of an application user, such as a username, or user id, or public key, or anything else you might use in your application to identify a user.Uniqueness
Although given names and family names (first/last) are technically considered principals as well, Shiro expects the object returned from this method to be an identifying attribute unique across your entire application. This implies that things like given names and family names are usually poor candidates as return values since they are rarely guaranteed to be unique; Things often used for this value:- A
longRDBMS surrogate primary key - An application-unique username
- A
UUID - An LDAP Unique ID
getPrincipals().getPrimaryPrincipal()- Returns:
- this Subject's application-specific unique identity.
- See Also:
PrincipalCollection.getPrimaryPrincipal()
- A
-
getPrincipals
PrincipalCollection getPrincipals()
Returns this Subject's principals (identifying attributes) in the form of aPrincipalCollectionornullif this Subject is anonymous because it doesn't yet have any associated account data (for example, if they haven't logged in). The word "principals" is nothing more than a fancy security term for identifying attributes associated with a Subject, aka, application user. For example, user id, a surname (family/last name), given (first) name, social security number, nickname, username, etc, are all examples of a principal.- Returns:
- all of this Subject's principals (identifying attributes).
- See Also:
getPrincipal(),PrincipalCollection.getPrimaryPrincipal()
-
isPermitted
boolean isPermitted(String permission)
Returnstrueif this Subject is permitted to perform an action or access a resource summarized by the specified permission string. This is an overloaded method for the corresponding type-safePermissionvariant. Please see the class-level JavaDoc for more information on these String-based permission methods.- Parameters:
permission- the String representation of a Permission that is being checked.- Returns:
- true if this Subject is permitted, false otherwise.
- Since:
- 0.9
- See Also:
isPermitted(Permission permission)
-
isPermitted
boolean isPermitted(Permission permission)
Returnstrueif this Subject is permitted to perform an action or access a resource summarized by the specified permission. More specifically, this method determines if anyPermissions associated with the subjectimplythe specified permission.- Parameters:
permission- the permission that is being checked.- Returns:
- true if this Subject is permitted, false otherwise.
-
isPermitted
boolean[] isPermitted(String... permissions)
Checks if this Subject implies the given permission strings and returns a boolean array indicating which permissions are implied. This is an overloaded method for the corresponding type-safePermissionvariant. Please see the class-level JavaDoc for more information on these String-based permission methods.- Parameters:
permissions- the String representations of the Permissions that are being checked.- Returns:
- a boolean array where indices correspond to the index of the
permissions in the given list. A true value at an index indicates this Subject is permitted for
for the associated
Permissionstring in the list. A false value at an index indicates otherwise. - Since:
- 0.9
-
isPermitted
boolean[] isPermitted(List<Permission> permissions)
Checks if this Subject implies the given Permissions and returns a boolean array indicating which permissions are implied. More specifically, this method should determine if eachPermissionin the array isimpliedby permissions already associated with the subject. This is primarily a performance-enhancing method to help reduce the number ofisPermitted(java.lang.String)invocations over the wire in client/server systems.- Parameters:
permissions- the permissions that are being checked.- Returns:
- a boolean array where indices correspond to the index of the
permissions in the given list. A true value at an index indicates this Subject is permitted for
for the associated
Permissionobject in the list. A false value at an index indicates otherwise.
-
isPermittedAll
boolean isPermittedAll(String... permissions)
Returnstrueif this Subject implies all of the specified permission strings,falseotherwise. This is an overloaded method for the corresponding type-safePermissionvariant. Please see the class-level JavaDoc for more information on these String-based permission methods.- Parameters:
permissions- the String representations of the Permissions that are being checked.- Returns:
- true if this Subject has all of the specified permissions, false otherwise.
- Since:
- 0.9
- See Also:
isPermittedAll(Collection)
-
isPermittedAll
boolean isPermittedAll(Collection<Permission> permissions)
Returnstrueif this Subject implies all of the specified permissions,falseotherwise. More specifically, this method determines if all of the givenPermissions areimplied bypermissions already associated with this Subject.- Parameters:
permissions- the permissions to check.- Returns:
- true if this Subject has all of the specified permissions, false otherwise.
-
checkPermission
void checkPermission(String permission) throws AuthorizationException
Ensures this Subject implies the specified permission String. If this subject's existing associated permissions do notPermission.implies(Permission)imply} the given permission, anAuthorizationExceptionwill be thrown. This is an overloaded method for the corresponding type-safePermissionvariant. Please see the class-level JavaDoc for more information on these String-based permission methods.- Parameters:
permission- the String representation of the Permission to check.- Throws:
AuthorizationException- if the user does not have the permission.- Since:
- 0.9
-
checkPermission
void checkPermission(Permission permission) throws AuthorizationException
Ensures this Subjectimpliesthe specifiedPermission. If this subject's existing associated permissions do notimplythe given permission, anAuthorizationExceptionwill be thrown.- Parameters:
permission- the Permission to check.- Throws:
AuthorizationException- if this Subject does not have the permission.
-
checkPermissions
void checkPermissions(String... permissions) throws AuthorizationException
Ensures this Subjectimpliesall of the specified permission strings. If this subject's existing associated permissions do notimplyall of the given permissions, anAuthorizationExceptionwill be thrown. This is an overloaded method for the corresponding type-safePermissionvariant. Please see the class-level JavaDoc for more information on these String-based permission methods.- Parameters:
permissions- the string representations of Permissions to check.- Throws:
AuthorizationException- if this Subject does not have all of the given permissions.- Since:
- 0.9
-
checkPermissions
void checkPermissions(Collection<Permission> permissions) throws AuthorizationException
Ensures this Subjectimpliesall of the specified permission strings. If this subject's existing associated permissions do notimplyall of the given permissions, anAuthorizationExceptionwill be thrown.- Parameters:
permissions- the Permissions to check.- Throws:
AuthorizationException- if this Subject does not have all of the given permissions.
-
hasRole
boolean hasRole(String roleIdentifier)
Returnstrueif this Subject has the specified role,falseotherwise.- Parameters:
roleIdentifier- the application-specific role identifier (usually a role id or role name).- Returns:
trueif this Subject has the specified role,falseotherwise.
-
hasRoles
boolean[] hasRoles(List<String> roleIdentifiers)
Checks if this Subject has the specified roles, returning a boolean array indicating which roles are associated. This is primarily a performance-enhancing method to help reduce the number ofhasRole(java.lang.String)invocations over the wire in client/server systems.- Parameters:
roleIdentifiers- the application-specific role identifiers to check (usually role ids or role names).- Returns:
- a boolean array where indices correspond to the index of the roles in the given identifiers. A true value indicates this Subject has the role at that index. False indicates this Subject does not have the role at that index.
-
hasAllRoles
boolean hasAllRoles(Collection<String> roleIdentifiers)
Returnstrueif this Subject has all of the specified roles,falseotherwise.- Parameters:
roleIdentifiers- the application-specific role identifiers to check (usually role ids or role names).- Returns:
- true if this Subject has all the roles, false otherwise.
-
checkRole
void checkRole(String roleIdentifier) throws AuthorizationException
Asserts this Subject has the specified role by returning quietly if they do or throwing anAuthorizationExceptionif they do not.- Parameters:
roleIdentifier- the application-specific role identifier (usually a role id or role name ).- Throws:
AuthorizationException- if this Subject does not have the role.
-
checkRoles
void checkRoles(Collection<String> roleIdentifiers) throws AuthorizationException
Asserts this Subject has all of the specified roles by returning quietly if they do or throwing anAuthorizationExceptionif they do not.- Parameters:
roleIdentifiers- the application-specific role identifiers to check (usually role ids or role names).- Throws:
AuthorizationException- if this Subject does not have all of the specified roles.
-
checkRoles
void checkRoles(String... roleIdentifiers) throws AuthorizationException
Same ascheckRoles(Collectionbut doesn't require a collection as a an argument. Asserts this Subject has all of the specified roles by returning quietly if they do or throwing anroleIdentifiers) AuthorizationExceptionif they do not.- Parameters:
roleIdentifiers- roleIdentifiers the application-specific role identifiers to check (usually role ids or role names).- Throws:
AuthorizationException- org.apache.shiro.authz.AuthorizationException if this Subject does not have all of the specified roles.- Since:
- 1.1.0
-
login
void login(AuthenticationToken token) throws AuthenticationException
Performs a login attempt for this Subject/user. If unsuccessful, anAuthenticationExceptionis thrown, the subclass of which identifies why the attempt failed. If successful, the account data associated with the submitted principals/credentials will be associated with thisSubjectand the method will return quietly. Upon returning quietly, thisSubjectinstance can be considered authenticated andgetPrincipal()will be non-null andisAuthenticated()will betrue.- Parameters:
token- the token encapsulating the subject's principals and credentials to be passed to the Authentication subsystem for verification.- Throws:
AuthenticationException- if the authentication attempt fails.- Since:
- 0.9
-
isAuthenticated
boolean isAuthenticated()
Returnstrueif this Subject/user proved their identity during their current session by providing valid credentials matching those known to the system,falseotherwise. Note that even if this Subject's identity has been remembered via 'remember me' services, this method will still returnfalseunless the user has actually logged in with proper credentials during their current session. See theisRemembered()method JavaDoc for more.- Returns:
trueif this Subject proved their identity during their current session by providing valid credentials matching those known to the system,falseotherwise.- Since:
- 0.9
-
isRemembered
boolean isRemembered()
Returnstrueif thisSubjecthas an identity (it is not anonymous) and the identity (akaprincipals) is remembered from a successful authentication during a previous session. Although the underlying implementation determines exactly how this method functions, most implementations have this method act as the logical equivalent to this code:
Note as indicated by the above code example, if agetPrincipal()!= null && !isAuthenticated()Subjectis remembered, they are NOT considered authenticated. A check againstisAuthenticated()is a more strict check than that reflected by this method. For example, a check to see if a subject can access financial information should almost always depend onisAuthenticated()to guarantee a verified identity, and not this method. Once the subject is authenticated, they are no longer considered only remembered because their identity would have been verified during the current session.Remembered vs Authenticated
Authentication is the process of proving you are who you say you are. When a user is only remembered, the remembered identity gives the system an idea who that user probably is, but in reality, has no way of absolutely guaranteeing if the rememberedSubjectrepresents the user currently using the application. So although many parts of the application can still perform user-specific logic based on the rememberedprincipals, such as customized views, it should never perform highly-sensitive operations until the user has legitimately verified their identity by executing a successful authentication attempt. We see this paradigm all over the web, and we will use Amazon.com as an example: When you visit Amazon.com and perform a login and ask it to 'remember me', it will set a cookie with your identity. If you don't log out and your session expires, and you come back, say the next day, Amazon still knows who you probably are: you still see all of your book and movie recommendations and similar user-specific features since these are based on your (remembered) user id. BUT, if you try to do something sensitive, such as access your account's billing data, Amazon forces you to do an actual log-in, requiring your username and password. This is because although amazon.com assumed your identity from 'remember me', it recognized that you were not actually authenticated. The only way to really guarantee you are who you say you are, and therefore allow you access to sensitive account data, is to force you to perform an actual successful authentication. You can check this guarantee via theisAuthenticated()method and not via this method.- Returns:
trueif thisSubject's identity (akaprincipals) is remembered from a successful authentication during a previous session,falseotherwise.- Since:
- 1.0
-
getSession
Session getSession()
Returns the applicationSessionassociated with this Subject. If no session exists when this method is called, a new session will be created, associated with this Subject, and then returned.- Returns:
- the application
Sessionassociated with this Subject. - Since:
- 0.2
- See Also:
getSession(boolean)
-
getSession
Session getSession(boolean create)
Returns the applicationSessionassociated with this Subject. Based on the boolean argument, this method functions as follows:- If there is already an existing session associated with this
Subject, it is returned and thecreateargument is ignored. - If no session exists and
createistrue, a new session will be created, associated with thisSubjectand then returned. - If no session exists and
createisfalse,nullis returned.
- Parameters:
create- boolean argument determining if a new session should be created or not if there is no existing session.- Returns:
- the application
Sessionassociated with thisSubjectornullbased on the above described logic. - Since:
- 0.2
- If there is already an existing session associated with this
-
logout
void logout()
Logs out this Subject and invalidates and/or removes any associated entities, such as aSessionand authorization data. After this method is called, the Subject is considered 'anonymous' and may continue to be used for another log-in if desired.Web Environment Warning
Calling this method in web environments will usually remove any associated session cookie as part of session invalidation. Because cookies are part of the HTTP header, and headers can only be set before the response body (html, image, etc) is sent, this method in web environments must be called before any content has been rendered. The typical approach most applications use in this scenario is to redirect the user to a different location (e.g. home page) immediately after calling this method. This is an effect of the HTTP protocol itself and not a reflection of Shiro's implementation. Non-HTTP environments may of course use a logged-out subject for login again if desired.
-
execute
<V> V execute(Callable<V> callable) throws ExecutionException
Associates the specifiedCallablewith thisSubjectinstance and then executes it on the currently running thread. If you want to execute theCallableon a different thread, it is better to use theassociateWith(Callable)method instead.- Type Parameters:
V- the type of return value theCallablewill return- Parameters:
callable- the Callable to associate with this subject and then execute.- Returns:
- the resulting object returned by the
Callable's execution. - Throws:
ExecutionException- if theCallable'scallmethod throws an exception.- Since:
- 1.0
-
execute
void execute(Runnable runnable)
Associates the specifiedRunnablewith thisSubjectinstance and then executes it on the currently running thread. If you want to execute theRunnableon a different thread, it is better to use theassociateWith(Runnable)method instead. Note: This method is primarily provided to execute existing/legacy Runnable implementations. It is better for new code to useexecute(Callable)since that supports the ability to return values and catch exceptions.- Parameters:
runnable- theRunnableto associate with thisSubjectand then execute.- Since:
- 1.0
-
associateWith
<V> Callable<V> associateWith(Callable<V> callable)
Returns aCallableinstance matching the given argument while additionally ensuring that it will retain and execute under this Subject's identity. The returned object can be used with anExecutorServiceto execute as this Subject. This will effectively ensure that any calls toSecurityUtils.getSubject()and related functionality will continue to function properly on any thread that executes the returnedCallableinstance.- Type Parameters:
V- theCallables return value type- Parameters:
callable- the callable to execute as thisSubject- Returns:
- a
Callablethat can be run as thisSubject. - Since:
- 1.0
-
associateWith
Runnable associateWith(Runnable runnable)
Returns aRunnableinstance matching the given argument while additionally ensuring that it will retain and execute under this Subject's identity. The returned object can be used with anExecutoror another thread to execute as this Subject. This will effectively ensure that any calls toSecurityUtils.getSubject()and related functionality will continue to function properly on any thread that executes the returnedRunnableinstance. *Note that if you need a return value to be returned as a result of the runnable's execution or if you need to react to any Exceptions, it is highly recommended to use thecreateCallablemethod instead of this one.- Parameters:
runnable- the runnable to execute as thisSubject- Returns:
- a
Runnablethat can be run as thisSubjecton another thread. - Since:
- 1.0
- See Also:
(java.util.concurrent.Callable)
-
runAs
void runAs(PrincipalCollection principals) throws NullPointerException, IllegalStateException
Allows this subject to 'run as' or 'assume' another identity indefinitely. This can only be called when theSubjectinstance already has an identity (i.e. they are remembered from a previous log-in or they have authenticated during their current session). Some notes aboutrunAs:- You can tell if a
Subjectis 'running as' another identity by calling theisRunAs()method. - If running as another identity, you can determine what the previous 'pre run as' identity
was by calling the
getPreviousPrincipals()method. - When you want a
Subjectto stop running as another identity, you can return to its previous 'pre run as' identity by calling thereleaseRunAs()method.
- Parameters:
principals- the identity to 'run as', aka the identity to assume indefinitely.- Throws:
NullPointerException- if the specified principals collection isnullor empty.IllegalStateException- if thisSubjectdoes not yet have an identity of its own.- Since:
- 1.0
- You can tell if a
-
isRunAs
boolean isRunAs()
Returnstrueif thisSubjectis 'running as' another identity other than its original one orfalseotherwise (normalSubjectstate). See therunAsmethod for more information.- Returns:
trueif thisSubjectis 'running as' another identity other than its original one orfalseotherwise (normalSubjectstate).- Since:
- 1.0
- See Also:
runAs(org.apache.shiro.subject.PrincipalCollection)
-
getPreviousPrincipals
PrincipalCollection getPreviousPrincipals()
Returns the previous 'pre run as' identity of thisSubjectbefore assuming the currentrunAsidentity, ornullif thisSubjectis not operating under an assumed identity (normal state). See therunAsmethod for more information.- Returns:
- the previous 'pre run as' identity of this
Subjectbefore assuming the currentrunAsidentity, ornullif thisSubjectis not operating under an assumed identity (normal state). - Since:
- 1.0
- See Also:
runAs(org.apache.shiro.subject.PrincipalCollection)
-
releaseRunAs
PrincipalCollection releaseRunAs()
Releases the current 'run as' (assumed) identity and reverts back to the previous 'pre run as' identity that existed before#runAs runAswas called. This method returns 'run as' (assumed) identity being released ornullif thisSubjectis not operating under an assumed identity.- Returns:
- the 'run as' (assumed) identity being released or
nullif thisSubjectis not operating under an assumed identity. - Since:
- 1.0
- See Also:
runAs(org.apache.shiro.subject.PrincipalCollection)
-
-