Now that our SecurityManager is set up and ready-to go, now we can start doing the things we really care about - performing security operations.
When securing our applications, probably the most relevant questions we ask ourselves are “Who is the current user?” or “Is the current user allowed to do X”? It is common to ask these questions as we’re writing code or designing user interfaces: applications are usually built based on user stories, and you want functionality represented (and secured) based on a per-user basis. So, the most natural way for us to think about security in our application is based on the current user. Shiro’s API fundamentally represents the notion of 'the current user' with its Subject
concept.
In almost all environments, you can obtain the currently executing user via the following call:
Subject currentUser = SecurityUtils.getSubject();
Using SecurityUtils
.getSubject(), we can obtain the currently executing Subject
. Subject is a security term that basically means "a security-specific view of the currently executing user". It is not called a 'User' because the word 'User' is usually associated with a human being. In the security world, the term 'Subject' can mean a human being, but also a 3rd party process, cron job, daemon account, or anything similar. It simply means 'the thing that is currently interacting with the software'. For most intents and purposes though, you can think of the Subject
as Shiro’s ‘User’ concept.
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.
Now that you have a 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 tutorial application, 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 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.
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 and allows you to handle and react accordingly:
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?
}
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.
|
Security best practice is to give generic login failure messages to users because you do not want to aid an attacker trying to break into your system.
|
Ok, so by now, we have a logged-in user.
What else can we do?
//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:wield" ) ) {
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!");
}
Finally, when the user is done using the application, they can log out:
//removes all identifying information and invalidates their session too.
currentUser.logout();