Without question, the most important concept in Apache Shiro is the Subject
. ‘Subject’ is just a security term that means a security-specific ‘view’ of an application user. A Shiro Subject
instance represents both security state and operations for a single application user.
These operations include:
We originally wanted to call it ‘User’ since that “just makes sense”, but we decided against it: too many applications have existing APIs that already have their own User classes/frameworks, and we didn’t want to conflict with those. Also, in the security world, the term ‘Subject’ is actually the recognized nomenclature.
Shiro’s API encourages a Subject
-centric programming paradigm for applications. When coding application logic, most application developers want to know who the currently executing user is. While the application can usually look up any user via their own mechanisms (UserService, etc), when it comes to security, the most important question is “Who is the current user?”
While any Subject can be acquired by using the SecurityManager
, application code based on only the current user/Subject
is much more natural and intuitive.
In almost all environments, you can obtain the currently executing Subject
by using org.apache.shiro.SecurityUtils
:
Subject currentUser = SecurityUtils.getSubject();
The getSubject()
call in a standalone application might return a Subject
based on user data in an application-specific location, and in a server environment (e.g. web app), it acquires the Subject based on user data associated with current thread or incoming request.
After you acquire the current Subject
, what can you do with it?
If you want to make things available to the user during their current session with the application, you can get their session:
Session session = currentUser.getSession();
session.setAttribute( "someKey", "aValue" );
The Session
is a Shiro-specific instance that provides most of what you’re used to with regular HttpSessions but with some extra goodies and one big difference: it does not require an HTTP environment!
If deploying inside a web application, by default the Session
will be HttpSession
based. But, in a non-web environment, like this simple Quickstart, Shiro will automatically use its Enterprise Session Management by default. This means you get to use the same API in your applications, in any tier, regardless of deployment environment. This opens a whole new world of applications since any application requiring sessions does not need to be forced to use the HttpSession
or EJB Stateful Session Beans. And, any client technology can now share session data.
So now you can acquire a Subject
and their Session
. What about the really useful stuff like checking if they are allowed to do things, like checking against roles and permissions?
Well, we can only do those checks for a known user. Our Subject
instance above represents the current user, but who is actually the current user? Well, they’re anonymous - that is, until they log in at least once. So, let’s do that:
if ( !currentUser.isAuthenticated() ) {
//collect user principals and credentials in a gui specific manner
//such as username/password html form, X509 certificate, OpenID, etc.
//We'll use the username/password example here since it is the most common.
//(do you know what movie this is from? ;)
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
//this is all you have to do to support 'remember me' (no config - built in!):
token.setRememberMe(true);
currentUser.login(token);
}
That’s it! It couldn’t be easier.
But what if their login attempt fails? You can catch all sorts of specific exceptions that tell you exactly what happened:
try {
currentUser.login( token );
//if no exception, that's it, we're done!
} catch ( UnknownAccountException uae ) {
//username wasn't in the system, show them an error message?
} catch ( IncorrectCredentialsException ice ) {
//password didn't match, try again?
} catch ( LockedAccountException lae ) {
//account for that username is locked - can't login. Show them a message?
}
... more types exceptions to check if you want ...
} catch ( AuthenticationException ae ) {
//unexpected condition - error?
}
You, as the application/GUI developer can choose to show the end-user messages based on exceptions or not (for example, "There is no account in the system with that username."
). There are many different types of exceptions you can check, or throw your own for custom conditions Shiro might not account for. See the AuthenticationException JavaDoc for more.
Ok, so by now, we have a logged in user. What else can we do?
Let’s say who they are:
//print their identifying principal (in this case, a username):
log.info( "User [" + currentUser.getPrincipal() + "] logged in successfully." );
We can also test to see if they have specific role or not:
if ( currentUser.hasRole( "schwartz" ) ) {
log.info("May the Schwartz be with you!" );
} else {
log.info( "Hello, mere mortal." );
}
We can also see if they have a permission to act on a certain type of entity:
if ( currentUser.isPermitted( "lightsaber:weild" ) ) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
Also, we can perform an extremely powerful instance-level permission check - the ability to see if the user has the ability to access a specific instance of a type:
if ( currentUser.isPermitted( "winnebago:drive:eagle5" ) ) {
log.info("You are permitted to 'drive' the 'winnebago' with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}
Piece of cake, right?
Finally, when the user is done using the application, they can log out:
currentUser.logout(); //removes all identifying information and invalidates their session too.
This simple API constitutes 90% of what Shiro end-users will ever have to deal with when using Shiro.
A new feature added in Shiro 1.0 is the ability to construct custom/ad-hoc subject instances for use in special situations.
You should almost always acquire the currently executing Subject by calling SecurityUtils.getSubject();
Creating custom Subject
instances should only be done in special cases.
Some ‘special cases’ when this can be useful:
System startup/bootstrap - when there are no users interacting with the system, but code should execute as a ‘system’ or daemon user. It is desirable to create Subject instances representing a particular user so bootstrap code executes as that user (e.g. as the admin
user).
This practice is encouraged because it ensures that utility/system code executes in the same way as a normal user, ensuring code is consistent. This makes code easier to maintain since you don’t have to worry about custom code blocks just for system/daemon scenarios.
Integration Testing - you might want to create Subject
instances as necessary to be used in integration tests. See the testing documentation for more.
Daemon/background process work - when a daemon or background process executes, it might need to execute as a particular user.
If you already have access to a Subject
instance and want it to be available to other threads, you should use the Subject.associateWith
* methods instead of creating a new Subject instance.
Ok, so assuming you still need to create custom subject instances, let’s see how to do it:
The Subject.Builder
class is provided to build Subject
instances easily without needing to know construction details.
The simplest usage of the Builder is to construct an anonymous, session-less Subject
instance:
Subject subject = new Subject.Builder().buildSubject()
The default, no-arg Subject.Builder()
constructor shown above will use the application’s currently accessible SecurityManager
via the SecurityUtils.getSecurityManager()
method. You may also specify the SecurityManager
instance to be used by the additional constructor if desired:
SecurityManager securityManager = //acquired from somewhere
Subject subject = new Subject.Builder(securityManager).buildSubject();
All other Subject.Builder
methods may be called before the buildSubject()
method to provide context on how to construct the Subject
instance. For example, if you have a session ID and want to acquire the Subject
that ‘owns’ that session (assuming the session exists and is not expired):
Serializable sessionId = //acquired from somewhere
Subject subject = new Subject.Builder().sessionId(sessionId).buildSubject();
Similarly, if you want to create a Subject
instance that reflects a certain identity:
Object userIdentity = //a long ID or String username, or whatever the "myRealm" requires
String realmName = "myRealm";
PrincipalCollection principals = new SimplePrincipalCollection(userIdentity, realmName);
Subject subject = new Subject.Builder().principals(principals).buildSubject();
You can then use the built Subject
instance and make calls on it as expected. But note:
The built Subject
instance is not automatically bound to the application (thread) for further use. If you want it to be available to any code that calls SecurityUtils.getSubject()
, you must ensure a Thread is associated with the constructed Subject
.
As stated above, just building a Subject
instance does not associate it with a thread - a usual requirement if any calls to SecurityUtils.getSubject()
during thread execution are to work properly. There are three ways of ensuring a thread is associated with a Subject
:
Automatic Association - A Callable
or Runnable
executed via the Subject.execute
* methods will automatically bind and unbind the Subject to the thread before and after Callable
/Runnable
execution.
Manual Association - You manually bind and unbind the Subject
instance to the currently executing thread. This is usually useful for framework developers.
Different Thread - A Callable
or Runnable
is associated with a Subject
by calling the Subject.associateWith
* methods and then the returned Callable
/Runnable
is executed by another thread. This is the preferred approach if you need to execute work on another thread as the Subject
.
The important thing to know about thread association is that 2 things must always occur:
ThreadState
mechanism which is an abstraction on top of a ThreadLocal
.Subject
state in a pooled/reusable thread environment.These principles are guaranteed to occur in the 3 mechanisms listed above. Their usage is elaborated next.
If you only need a Subject
to be temporarily associated with the current thread, and you want the thread binding and cleanup to occur automatically, a Subject
’s direct execution of a Callable
or Runnable
is the way to go. After the Subject.execute
call returns, the current thread is guaranteed to be in the same state as it was before the execution. This mechanism is the most widely used of the three.
For example, let’s say that you had some logic to perform when the system starts up. You want to execute a chunk of code as a particular user, but once the logic is finished, you want to ensure the thread/environment goes back to normal automatically. You would do that by calling the Subject.execute
* methods:
Subject subject = //build or acquire subject
subject.execute( new Runnable() {
public void run() {
//subject is 'bound' to the current thread now
//any SecurityUtils.getSubject() calls in any
//code called from here will work
}
});
//At this point, the Subject is no longer associated
//with the current thread and everything is as it was before
Of course Callable
instances are supported as well so you can have return values and catch exceptions:
Subject subject = //build or acquire subject
MyResult result = subject.execute( new Callable<MyResult>() {
public MyResult call() throws Exception {
//subject is 'bound' to the current thread now
//any SecurityUtils.getSubject() calls in any
//code called from here will work
...
//finish logic as this Subject
...
return myResult;
}
});
//At this point, the Subject is no longer associated
//with the current thread and everything is as it was before
This approach is also useful in framework development. For example, Shiro’s support for secure Spring remoting ensures the remote invocation is executed as a particular subject:
Subject.Builder builder = new Subject.Builder();
//populate the builder's attributes based on the incoming RemoteInvocation ...
Subject subject = builder.buildSubject();
return subject.execute(new Callable() {
public Object call() throws Exception {
return invoke(invocation, targetObject);
}
});
While the Subject.execute
* methods automatically clean up the thread state after they return, there might be some scenarios where you want to manage the ThreadState
yourself. This is almost always done in framework-level development when integrating w/ Shiro and is rarely used even in bootstrap/daemon scenarios (where the Subject.execute(callable)
example above is more frequent).
The most important thing about this mechanism is that you must always guarantee the current thread is cleaned up after logic is executed to ensure there is no thread state corruption in a reusable or pooled thread environment.
Guaranteeing cleanup is best done in a try/finally
block:
Subject subject = new Subject.Builder()...
ThreadState threadState = new SubjectThreadState(subject);
threadState.bind();
try {
//execute work as the built Subject
} finally {
//ensure any state is cleaned so the thread won't be
//corrupt in a reusable or pooled thread environment
threadState.clear();
}
Interestingly enough, this is exactly what the Subject.execute
* methods do - they just perform this logic automatically before and after Callable
or Runnable
execution. It is also nearly identical logic performed by Shiro’s ShiroFilter
for web applications (ShiroFilter
uses web-specific ThreadState
implementations outside the scope of this section).
Don't use the above ThreadState
code example in a thread that is processing a web request. Web-specific ThreadState implementations are used during web requests instead. Instead, ensure the ShiroFilter
intercepts web requests to ensure Subject building/binding/cleanup is done properly.
If you have a Callable
or Runnable
instance that should execute as a Subject
and you will execute the Callable
or Runnable
yourself (or hand it off to a thread pool or Executor
or ExecutorService
for example), you should use the Subject.associateWith
* methods. These methods ensure that the Subject is retained and accessible on the thread that eventually executes.
Callable example:
Subject subject = new Subject.Builder()...
Callable work = //build/acquire a Callable instance.
//associate the work with the built subject so SecurityUtils.getSubject() calls works properly:
work = subject.associateWith(work);
ExecutorService executor = java.util.concurrent.Executors.newCachedThreadPool();
//execute the work on a different thread as the built Subject:
executor.execute(work);
Runnable example:
Subject subject = new Subject.Builder()...
Runnable work = //build/acquire a Runnable instance.
//associate the work with the built subject so SecurityUtils.getSubject() calls works properly:
work = subject.associateWith(work);
ExecutorService executor = java.util.concurrent.Executors.newCachedThreadPool();
//execute the work on a different thread as the built Subject:
executor.execute(work);
The associateWith
* methods perform necessary thread cleanup automatically to ensure threads remain clean in a pooled environment.
While we hope this documentation helps you with the work you're doing with Apache Shiro, the community is improving and expanding the documentation all the time. If you'd like to help the Shiro project, please consider correcting, expanding, or adding documentation where you see a need. Every little bit of help you provide expands the community and in turn improves Shiro.
The easiest way to contribute your documentation is to submit a pull-request by clicking on the Edit
link below, send it to the User Forum or the User Mailing List.