10 minutes to teach you Apache Shiro

Source: Internet
Author: User

Preface

Welcome to Apache Shiro for a 10-minute tour!

We hope that this simple and quick example will give you an in-depth understanding of shiro in your application. Well, you can fix it in 10 minutes.

Overview

What is Apache Shiro?

Apache Shiro is a powerful Java security framework that provides developers with an intuitive and comprehensive solution for authentication, authorization, encryption, and session management.

In fact, Shiro's main function is to manage all security-related applications and support multiple implementation methods as much as possible. Shiro is built on a sound interface-driven design and object-oriented principles, and supports various user-defined behaviors. Shiro provides the default implementation so that it can implement the same functions as other security frameworks. Isn't that what we have been trying to get!

So what can Apache Shiro do?

A lot, a lot, hey. But I will not introduce it in the Quick Guide. What should I do if you want to know? GoHereFind your answer. Of course, if you still want to know when and why we want to "CREATE" Shiro, go and have a look.Shrio's history and missionRight.

Okay. Now let's do something.

Note: Shiro can run in any environment, from the simplest command line application to the large enterprise application and cluster application. However, we are going to use the simplest main method in the Quick Guide to give you a sensory understanding of Shiro APIs.

Download

  1. Make sure that jdk1.5 + and maven2.2 + are installed.
  2. GoHereDownload the latest released source code. In this example, release version 1.1.0.
  3. Extract source code
  4. Go to the Quick Guide folder

    CD shiro-root-1.1.0/samples/Quickstart

  5. Quick Guide

    MVN compile Exec: Java

Logs are output during the process to tell you what is in progress and finally exit the execution. You can find the source code in "samples/Quickstart/src/main/Java/Quickstart. Java" or modify it. Remember to run "MVN compile Exec: Java" after modification.

Quickstart. Java

Quickstart. Java contains all the content (authentication, authorization, and so on) We just mentioned. This simple example allows you to easily familiarize yourself with Shiro APIs. So let's analyze the code in Quickstart. Java at, so that we can understand their functions easily. In almost all environments, you can obtain the current user in this way:

Subject currentuser = securityutils. getsubject ();

You can use securityutils. getsubject () to obtain the current subject. Subject is a microcosm of the user's specific security in the application. Although it feels more appropriate to directly use the user, it actually means much more than the user. And every application has its own users and framework. We don't want to confuse them. Besides, subject is a widely recognized term in the security field. OK. Let's continue.

In a single application system, calling getsubject () will return a subject, which is the user information located at a specific location in the application; when running on the server (such as a web application ), getsubject returns a user information in the current thread or request. Now that you have obtained the subject object, what can you do with it?

If you want to obtain other parameters of the user's current session in the application, you can obtain the session object as follows:

Session session = currentuser. getsession ();

Session. setattribute ("somekey", "avalue ");

This session object is a special object in Shiro. It is very similar to the httpsession we often use, but it also provides additional things, the biggest difference from httpsession is that the session in Shiro does not depend on the HTTP environment (in other words, it can be run in a non-HTTP container ).

If Shiro is deployed in a web application, the session is based on httpsession. However, as in the Quickstart example, Shiro uses enterprisesessionmanagment by default in non-web environments. That is to say, no matter which layer of the application uses the same API, you do not need to consider the deployment environment. This advantage opens a new world for the application, because the application no longer needs to rely on the session bean of httpsession or EJB to obtain the session object. In addition, any client technology can share session data.

Now you can get the current subject and its session object. So how can we verify the roles and permissions?

It is very simple. You can use the obtained user object for verification. The subject object represents the current user. But who is the current user? They are anonymous users. That is, you must log on to obtain the current user. No problem. You can do this:

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's too easy!

What should I do if I fail to log on? You can capture various types of exceptions and handle them differently based on different types of exceptions:

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?

}

It can capture various exceptions provided by Shiro, or throw custom class exceptions to handle events not considered by Shiro. For more information, seeAuthenticationexception javadoc.

Tip: The safest way is to inform the user of the logon failure message. You will never help the attacker intrude into your system!

OK. Now we have a login user. What else can we do?

For example, who are they:

// Print their identifying principal (in this case, a username ):

Log.info ("User [" + currentuser. getprincipal () + "] logged in successfully .");

You can also determine whether a user has a specific role:

If (currentuser. hasrole ("Schwartz ")){

Log.info ("may the Schwartz be with you! ");

} Else {

Log.info ("Hello, mere mortal .");

}

You can also determine whether a user has operation permissions on a specific object:

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 .");

}

Of course, you can also perform powerful instance-level permission verification. It can be used to determine whether a user has the permission to access a specific type of instance:

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! ");

}

A piece of cake, right.

Finally, you can exit the application after using it.

Currentuser. logout (); // removes all identifying information and invalidates their session too.

These are the core of using Apache Shiro to develop applications. Of course, Apache Shiro has encapsulated many complicated things inside, but now it is so simple.

Who is responsible for retrieving user information (username, password, role, permission, etc.) during user logon and who is responsible for security authentication during runtime? Of course you have decided. Configure a reaml that implements realm in Shiro to Shiro.

How to configure depends largely on your runtime environment, such as using shiro in a single application, web application, spring or Jee container-based application or combination mode, the configurations are different. Configuration is beyond the scope of the Quickstart example, because its main purpose is to help you familiarize yourself with Shiro APIs and concepts.

For more information about Shiro, seeAuthentication GuideAndAuthorization Guide. You can also view other documents (especiallyReference manual), Here you can solve your various questions.

 

From: http://www.turingbook.com/article/details/163

 

 

Read and download related articles:

 

Shiro1.1.0 development configuration document"

 

Apply Shiro to Web Application"

 

Apache Shiro User Manual"

 

10 minutes to teach you Apache Shiro"

 

MoreApache Shiro documentationAll in oneRoll-out benefit 360 http://www.docin.com/book_360

 

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.