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:
- authentication (login)
- authorization (access control)
- session access
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:
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:
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:
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:
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:
We can also test to see if they have specific role or not:
We can also see if they have a permission to act on a certain type of entity:
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:
Piece of cake, right?
Finally, when the user is done using the application, they can log out:
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.
Special Use Only!
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:
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:
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):
Similarly, if you want to create a Subject instance that reflects a certain identity:
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:
- The Subject is bound to the thread so it is available at all points of the thread's execution. Shiro does this via its ThreadState mechanism which is an abstraction on top of a ThreadLocal.
- The Subject is unbound at some point later, even if the thread execution results in an error. This ensures the thread remains clean and clear of any previous 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:
Of course Callable instances are supported as well so you can have return values and catch exceptions:
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:
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:
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.
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 corrected, expanding, or adding documentation where you see a need. Every little bit of help you provide expands the community and in turn improves Shiro.