Apache Shiro Series three: 10 minutes to get started

Source: Internet
Author: User
Tags builtin html form

First, Introduction

Read this Ten minutes to get started, you'll know how to introduce and use it in your application Shiro . Later you can use Shiro in your own application , and you should be able to do it within ten minutes.

Second, Overview

about the Shiro not much to say, the details can be seen http://www.cnblogs.com/strinkbug/p/6117353.html

Apache Shiro what can be done? http://shiro.apache.org/features.html

The answer is a lot, but here we don't start to say, if you are interested in this, you can go to see Shiro of the features .

third, Download

!--[if !supportlists]-->1) !--[Endif]--> Ensure that the 1.6 jdk are installed 3.0.3 maven

!--[if !supportlists]-->2) !--[Endif]--> from download   page download latest version of "Source Code distribution" 1.3.2 version;

3) decompression;

4) into the QuickStart directory;

$ CD Shiro-root-1.3.2/samples/quickstart

5) Run QuickStart ;

$ mvn Compile exec : Java

in the process of reading this entry document, you can open the source file Samples/quickstart/src/main/java/quickstart.java, and feel free to modify it to test your ideas.

Four, Quickstart.java

Let's break down the instructions. Quickstart.java within the source code so that you can better understand.

In any environment you can get the currently logged-in user by using the following code.

Subject CurrentUser =securityutils.getsubject ();

so-called Subject The starting point is in other systems. User , it's just another way of saying that, because it's not just people who can log into the system, but other systems.

If you are calling in a standalone application Getsubject () , we will get an application to log in locally to the user information, if it is a Web application, you will get a current thread or the current Session the relevant user.

Anyway, now that you've got a user, what can you do next?

If you want to make certain data valid for the duration of the current user logon session, you can do this as follows:

Session session = currentuser.getsession (); Session.setattribute ("Somekey", "avalue");

this Session is a Shiro realization of a special class that he and HttpSession has a similar interface, so everyone will be familiar with it. But he has one additional benefit: the context is not dependent on HTTP . This allows you to use the Session in a non- Web application (such as a command-line program) .

if it is in aWebused in ApplicationsSession, The returnedSessionis based on aHttpSessionand if it is in a non-Webenvironment, the default is to use theEnterprise Session. In any case, this means that we ignore the application's deployment environment and always use the sameAPIto operateSession. This brings a new user experience, and now,Webapplications and non-Webapps can be sharedSessionthe data.

so far, we've got a Subject well he's Session now, how about we use them to do something really meaningful? For example, check if the user has permission to do something?

We can do these checks for a known user. The Subject in our previous section represents the current user, but for now, who is the current user? Before actually logging in,Subject represents an anonymous user. Let's take a look at how the login is done.

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 's the most common.//(Do you know the What movie is the from ?;)Usernamepasswordtoken token =newusernamepasswordtoken ("Lonestarr", "Vespa");//This are all of the remember Me ' config-built in!:Token.setrememberme (true); Currentuser.login (token);}

In this way, simple can not be simpler. But what if the login fails? You can catch an exception to get an accurate picture of what went wrong, and then do some targeted processing.
1 Try{2 Currentuser.login (token);3 //If no exception, that ' s it, we ' re done!4}Catch(unknownaccountexception UAE) {5 //username wasn ' t in the system, show them an error message?6}Catch(Incorrectcredentialsexception ice) {7 //password didn ' t match, try again?8}Catch(Lockedaccountexception Lae) {9 //Account for this username is locked-can ' t login. Show them a message?Ten } One... more types exceptions to checkifYou want ... A}Catch(Authenticationexception ae) { - //unexpected condition-error? -}

You can detect many different kinds of exceptions, or you can throw your own exceptions. OK Authenticationexception Javadoc to learn more. Tips: The best practice in the field of security is to give only a few common error hints when an error occurs. If the message is too detailed, you may accidentally leak some of the central information to attack our hackers. Well, so far, we've got a logged-in user, and what else can we do? For example, we can print some information to illustrate who we are:
// print their identifying principal (in the case, a username):log.info ("User [" + currentuser.getprincipal () + "] Lo Gged in successfully. ");

We can also test to see if the current user has a role.
if (Currentuser.hasrole ("Schwartz")) {Log.info ("May the Schwartz is with you!" );} Else {log.info ("Hello, mere mortal.") );}

Or maybe we can see if he has permission to perform some sort of operation on some kind of data.
if (Currentuser.ispermitted ("Lightsaber:weild")) {Log.info ("You may use a lightsaber ring. Use it wisely. " );} Else {log.info ("Sorry, lightsaber rings is for Schwartz Masters only.") );}

We can also do an instance-level permission check--to see if the user has permission to access a specific instance of a type of data.
if (Currentuser.ispermitted ("Winnebago:drive:eagle5")) {Log.info ("You're permitted to ' drive ' the ' Winnebago ' With license plate (ID) ' Eagle5 '. "+" Here is the Keys-have fun! " );} Else {log.info ("Sorry, you aren ' t allowed-drive the ' eagle5 ' winnebago!" );}

It's a piece of cake, isn't it? Finally, if the user has done everything, he can log out.
Currentuser.logout (); // removes all identifying information and invalidates their session too.

Well, if we're going to use Apache Shiro in our application, we know that these APIs are not all that bad. While some of the complex implementations are hidden beneath these elegant codes. But for the user, that's really enough. But you may ask yourself: "Who will be responsible for obtaining user-related data (such as usernames, passwords, roles, permissions, etc.) when the user logs in, and who will actually perform these security checks at runtime?" "I can only say that you are you are you, you want to implement a self-shiro in the realm of the interface, and inherit it into the Shiro configuration. However, how to configure realm is primarily related to your run-time environment. For example, you might be running a standalone application, or a Web application, or an application that relies on a spring or JEE container, or a combination of these types. For a 10-minute entry, these configurations are all too complex, and the main purpose of this section is to familiarize you with Shiro's APIs and related concepts. You may want to read the User Authentication Wizard (http://shiro.apache.org/java-authentication-guide.html) and the User Authorization Wizard (HTTP.//) Before you continue to understand the other details.  shiro.apache.org/java-authorization-guide.html), and then continue reading other documents, especially the reference Manual (http://shiro.apache.org/reference.html). English Original address: http://shiro.apache.org/10-minute-tutorial.html



Apache Shiro Series three: 10 minutes to get started

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.