Overview
What is Apache Shiro?
Apache Shiro is a powerful and easy to use Java security framework that offers developers an intuitive yet comprehensive solution to authentication, authorization, cryptography, and session management.
QuickStart
既然是quickStart, 本节用了最简洁,通用的方式实现了Shiro,
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();
这个subject是个User, 但User容易与其他名称混淆, 所以称为currentUser
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 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!
web下就是HttpSession, 非web下创造session 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 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 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?
}
- 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?
Let’s say who they are:
//print their identifying principal (in this case, a username):
log.info( "User [" + currentUser.getPrincipal() + "] logged in successfully." );
if ( currentUser.hasRole( "schwartz" ) ) {
log.info("May the Schwartz be with you!" );
} else {
log.info( "Hello, mere mortal." );
}
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.");
}