Shiro Learning-Authentication

Source: Internet
Author: User
Tags memcached prepare throw exception

Shiro Learning-Authentication


Author: Vashon

Time: 2018-03-15 Introduction

Apache Shiro is a security framework for Java. Currently, there are more and more people using Apache Shiro because it's fairly simple, compared to spring security, it may not be as powerful as spring security does, but it might not need to be that complicated in actual work, so use a small, simple Shiro Is enough. For both of them which is good, this need not tangle, can be more simple to solve the project problem.

This tutorial only introduces the basic Shiro use, not too much analysis of the source code, etc., heavy in use.

Shiro can be very easy to develop a good enough application, not only can be used in javase environment, can also be used in Java EE environment. Shiro can help us accomplish: Authentication, authorization, encryption, session management, WEB integration, caching, and so on. This is not what we want, and the Shiro API is also very simple; its basic function points are shown in the following illustration:


Authentication: Identity authentication/Login, verify that the user has the corresponding identity;

Authorization: Authorization, that is, permission validation, to verify that an authenticated user has a permission, that is, to determine whether a user can do something, such as verifying that a user has a role. or fine-grained to verify that a user has a permission on a resource;

Session Manager: Conversation Management, that is, after a user logs on is a session, before exiting, all of its information is in the session, the session can be a common javase environment, can also be like the WEB environment;

Cryptography: Encryption, protection of data security, such as password encryption stored in the database, rather than plaintext storage;

Web Support: Web support that can be easily integrated into a web environment;

Caching: caching, such as user login, the user information, the role/permissions do not have to check every time, this can improve efficiency;

concurrency: Shiro supports concurrent authentication for multi-threaded applications, such as opening another thread in one thread, enabling automatic transmission of the past;

testing: Provide test support;

Runas: Allows one user to pretend to be visited by another user (if they allow);

RememberMe: Remember me, this is a very common function, that is, once logged in, the next time you do not have to log in.

keep in mind that Shiro does not maintain user and maintenance privileges; it needs to be designed/delivered by ourselves, and then injected to Shiro via the corresponding interface.

Next, we look at the Shiro architecture from the outside and from the inside, for a good framework, there should be a very simple and Easy-to-use API from the outside, and the API contract is clear; internally, it should have an extensible architecture, which is very easy to insert user-defined implementations, Because no framework can meet all the requirements.

First, let's look at Shiro from the outside, from an application perspective to see how to use Shiro to do the work. The following figure:


You can see: the object of direct interaction of the application code is Subject, that is to say, Shiro's external API core is Subject; the meaning of each API:

Subject: The main body, represents the current "user", this user is not necessarily a specific person, and the current application of the interaction of anything is Subject, such as web crawler, robot, etc., that is, an abstract concept; all Subject are bound to SecurityManager, all interactions with Subject will be delegated to SecurityManager, which can be regarded as a façade; SecurityManager is the actual performer;

SecurityManager: Security Manager, that is, all security-related operations will interact with SecurityManager, and it manages all Subject; you can see that it is the core of Shiro, and it is responsible for interacting with the other components described in the following , if you have studied Springmvc, you can think of it as Dispatcherservlet Front Controller;

Realm: Domain, Shiro from Realm to obtain security data (such as users, roles, permissions), that is, SecurityManager to authenticate user identity, then it needs to obtain the corresponding user from Realm to compare to determine whether the user's identity is legitimate , it also needs to obtain the user's corresponding role/authority from Realm to verify whether the user can perform the operation; Realm can be regarded as DataSource, that is, the safe data source.

That is to say for us, the simplest one Shiro application:

The application code is authenticated and authorized through Subject, and Subject is entrusted to SecurityManager; we need to inject SecurityManager into Shiro's Realm so that SecurityManager can be legally used. Households and their rights to judge.

As you can see from the above, Shiro does not provide the maintenance of user/rights, but rather through Realm let developers inject themselves.

Next, let's look at the architecture of the Shiro from within the Shiro, as shown in the following illustration:


Subject: Subject, you can see that the subject can be any "user" that can interact with the application;

SecurityManager: equivalent to Filterdispatcher in the Dispatcherservlet or Struts2 of SPRINGMVC; the heart of Shiro; All concrete interactions are through SecurityManager Control, it manages all Subject, and is responsible for authentication and authorization, and session, cache management.

Authenticator: Authenticator, responsible for the subject certification, this is an extension point, if the user feel Shiro default is not good, you can customize the implementation; It needs authentication strategy (authentication strategy), That is, under what circumstances the user authentication passed;

Authrizer: Authorization, or access controller, to determine whether the subject has the right to do the appropriate operation, that is, control the user can access the functions of the application;

Realm: can have 1 or more Realm, can be considered as a secure Entity data source, which is used to obtain security entities, can be JDBC implementations, LDAP implementations, memory implementations, and so on; Shiro doesn't know where your user/permissions are stored and in what format. , so we usually need to realize our own Realm in the application.

SessionManager: If you write a Servlet, you should know the concept of the session, the session needs someone to manage its lifecycle, this component is SessionManager, and Shiro is not only available in Web environment, can also be used in such as the common Javase environment, EJB and other environments; all, Shiro a session to manage the interaction between the subject and application data; In this case, for example, we are in the Web environment, the beginning is a Web server; then we went to the station EJ B server; When you want to put the session data of the two servers in one place, you can implement your own distributed session (such as putting the data on the Memcached server);

Sessiondao: DAO Everyone has used, data access objects, for session CRUD, such as we want to save sessions to the database, then we can implement their own sessiondao, such as JDBC write to the database; Put in the Memcached, you can realize your own Memcached Sessiondao, in addition, the cache can be used for caching in Sessiondao to improve performance;

CacheManager: Caching controllers to manage caching of users, roles, permissions, and so on, because these data are rarely changed, and can be improved by the performance of the access in the cache

Cryptography: Cipher module, Shiro improves some of the common cryptographic components used for password encryption/decryption.

To this Shiro architecture and its components are known, next to learn the Shiro components.


Authentication

Authentication, that is, in the application who can prove that he is himself. Generally provide some identification information such as their identity ID to indicate that he is himself, such as providing ID card, username/password to prove.

In Shiro, users need to provide principals (identity) and credentials (certification) to Shiro, so that applications can authenticate users:

Principals: Identity, that is, the identity of the main attribute, can be anything, such as user name, mailbox, and so on, the only thing. A subject can have multiple principals, but only one Primary principals, typically username/password/cell phone number.

credentials: proof/Voucher, that is, only the subject knows the security value, such as password/digital certificate.

The most common principals and credentials combinations are username/password. Next, start with a basic identity authentication.

The other two related concepts are the Subject and Realm mentioned earlier, respectively, as the data source of the subject and the authentication principal. Environmental Preparedness

This article is built using MAVEN, so a little maven knowledge is needed. First prepare for environment dependency:

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId> junit</artifactid>
        <version>4.9</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.1.3</version>
    </dependency>
    <dependency>
        <groupId> org.apache.shiro</groupid>
        <artifactId>shiro-core</artifactId>
        <version> 1.2.2</version>
    </dependency>
</dependencies>

Add JUnit, common-logging, and Shiro-core dependencies. Login/Exit

1, first prepare some user identity/credentials (Shiro.ini)

[Users]
zhang=123
wang=123

The INI configuration file is used here and two principals are specified through [users]: zhang/123, wang/123.

2. Test Cases (Com.github.zhangkaitao.shiro.chapter2.LoginLogoutTest)

 @Test public void Testhelloworld () {//1, get the SecurityManager factory, where the INI profile is used to initialize the SecurityManager factory<
    Org.apache.shiro.mgt.securitymanager> factory = new Inisecuritymanagerfactory ("Classpath:shiro.ini"); 2, Get SecurityManager instance and bind to securityutils org.apache.shiro.mgt.SecurityManager SecurityManager =
    Factory.getinstance ();
    Securityutils.setsecuritymanager (SecurityManager);
    3, get Subject and create user name/password Authentication token (that is, user identity/voucher) Subject Subject = Securityutils.getsubject ();
    Usernamepasswordtoken token = new Usernamepasswordtoken ("Zhang", "123");
    try {//4, login, that is, authentication Subject.login (token); catch (Authenticationexception e) {//5, Authentication failed} assert.assertequals (True, subject.isauthenticated ());
Asserts that the user has logged on to//6, exiting Subject.logout (); }

First, create a SecurityManager factory by using the new inisecuritymanagerfactory and specifying an INI configuration file;

Then get SecurityManager and bind to Securityutils, this is a global setting, set once;

The Subject is automatically bound to the current thread by Securityutils, if the Web environment needs to be unbound at the end of the request, and then the Token of the authentication, such as username/password, is obtained;

Call the Subject.login method to log in, which is automatically delegated to the Securitymanager.login method for login;

If authentication fails, capture authenticationexception or its subclasses, as common as: disabledaccountexception (Disabled account), Lockedaccountexception (Locked account), Unknownaccountexception (wrong account number), Excessiveattemptsexception (too many logon failures), Incorrectcredentialsexception (bad credentials), Expiredcredentialsexception (expired vouchers), and so on, see its inheritance relationship, for the page error message display, it is best to use such as "username/password Error" instead of "User name error"/"Password error", to prevent some malicious users from illegally scanning account library; Finally, you can call Subject.logout exit, which is automatically delegated to the Securitymanager.logout method exit.

You can summarize the authentication steps from the above code:

Collect user ID/credentials, such as username/password;

Call Subject.login to log in, if the failure will get the corresponding authenticationexception exception, prompts the user error message according to the exception, otherwise the login succeeds, and the last call to Subject.logout for exit operation.

As a few of the questions on the test:

Username/password hard-coded in the INI configuration file, you need to change to the database storage, and passwords need to encrypt storage; user identity Token may be more than a username/password, or there may be other, such as login to allow username/mailbox/Mobile phone number at the same time. Identity Certification Process


The process is as follows: First call Subject.login (token) for login, which is automatically delegated to the security Manager, which must be set by Securityutils.setsecuritymanager () before calling; SecurityManager is responsible for the true authentication logic; it delegates to authenticator for authentication; Authenticator is the true authenticator, Shiro the core authentication entry point in the API, where you can customize the insert your own implementation Authenticator may be delegated to the appropriate authenticationstrategy for multiple Realm authentication, and the default modularrealmauthenticator will invoke Authenticationstrategy For multiple Realm authentication, authenticator will pass the corresponding token to Realm, obtain authentication information from Realm, and if no return/Throw exception indicates authentication failed. Multiple Realm can be configured here, and will be accessed in the appropriate order and policy. Realm

Realm: Domain, Shiro from Realm to obtain security data (such as users, roles, permissions), that is, SecurityManager to authenticate user identity, it needs to obtain the corresponding user from Realm to compare to determine whether the user's identity is legitimate, also need to from Realm To obtain the user's corresponding Role/permissions to verify whether the user can operate, Realm can be regarded as DataSource, that is, secure data source. Our previous INI configuration will use Org.apache.shiro.realm.text.IniRealm.

The Org.apache.shiro.realm.Realm interface is as follows:

String GetName (); Returns a unique realm name,
Boolean supports (Authenticationtoken token);//Determine if this realm supports this token
AuthenticationInfo Getauthenticationinfo (Authenticationtoken token)
 throws authenticationexception;  Obtain authentication information according to token

Single Realm configuration

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.