Welcome to JSecurity's quickstart! This serves as our "10 minute test".
If you don't fully understand how to use a JSecurity-enabled application in under 10 minutes, we've done something wrong. JSecurity is so easy to understand, it should take 5 minutes ;)
What is JSecurity?
From our slogan, JSecurity is a "powerful and flexible open-source Java security framework that cleanly handles authentication, authorization, enterprise session management, and cryptography services"
In practical terms, it achieves to manage all facets of your application's security, while keeping out of the way as much as possible. It is built on sound interface-driven design and OO principles, enabling custom behavior wherever you can imagine it. But with sensible defaults for everything, it is as "hands off" as application security can be. At least that's what we strive for.
A lot :). But we don't want to bloat the QuickStart. Please check out our features page if you'd like to see what it can do for you. Also, if you're curious on how we got started and why we exist, please see the about page.
Ok. Now let's actually do something!
Note: Although JSecurity can be run in any environmenment, from the simplest command line application to the biggest enterprise web and clustered applications, we'll use the simplest possible example in a simple main method for this QuickStart so you can get a feel for the API.
jsecurity-version.zip. Unzip that file anywhere you want. It will unzip a directory named jsecurity-version/.jsecurity.jar file. Place that file in your application's classpath to start developing with JSecurity today.ant samples.quickstart.runAnd that will run the the code that this Quickstart references.
*This step requires only ant to be installed, but it will use Ivy to download the necessary libraries from Maven repositories to build the product. Please ensure you can access maven repositories (check firewall settings, etc).
jsecurity-version/samples/quickstart/src/Quickstart.java to follow along. Feel free to run the ant samples.quickstart.run command if you want to change the file and play around with the API a bit.
The Quickstart.java file referenced above contains all the code that will get you familiar with the API. Now lets break it down in chunks here so you can easily understand what is going on.
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. A Subject is just a security-specific "view" of an application User. We actually 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. Ok, moving on...
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 JSecurity-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, JSecurity 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.
//(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 failed? 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 JSecurity 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.
Well, that's the core to using JSecurity at the application-developer level. And although there is some pretty sophisticated stuff going on under the hood to make this work so elegantly, that's really all there is to it.
But you might ask yourself, "But who is responsible for getting the user data during a login (usernames and passwords, role and permissions, etc), and who actually performs those security checks during runtime? Well, you do, by implementing what JSecurity calls a Realm and plugging that Realm into JSecurity's configuration.
However, how you configure a Realm is largely dependent upon your runtime environment. For example, if you run a standalone application, or if you have a web based application, or a Spring or JEE container-based application, or combination thereof. That type of configuration is outside the scope of this quickstart, since its aim is to get you comfortable with the API and JSecurity's concepts.
Next, we'll provide additional 'recipe' web pages soon that describe how to configure realms in each of these environments. But don't worry! It is not difficult! Until they are up, please feel free to join in our Mailing Lists and ask questions. You'll find that we're happy to help whenever we can.
Thanks for following along. We hope you enjoy using JSecurity!