Shiro Quick Start

Source: Internet
Author: User
Tags arrays comparison hash ini md5 md5 encryption require throw exception
The first 2 days to write the web Rights Management, then the actual development is how to implement the Rights management. Let's take a look at it.

The traditional scheme: by setting up interceptors, managing based on URL, creating a user class for storing menus, storing the user in session to the front end for menu dynamic display, and the user class permissions collection for URL interception, have corresponding permission to release. This approach is easy to implement, but not easy to maintain.

New scenario: Using the Shiro Rights Management framework

what is Shiro.
Shiro is Apache's Open source Java security framework that provides authentication, authorization, encryption, session management, Web integration, caching, and so on, as well as a framework like spring security.

Shiro function Diagram


Subject: The main body, can be the user can also be a program, the main body to access the system, the system needs to authenticate the subject, authorization.
SecurityManager: Security Manager, the subject of authentication and authorization are carried out through the SecurityManager, is the core of Shiro.
Authenticator: The authenticator, the main body carries on the attestation finally through the authenticator carries on.
Authorizer: The authorization, the subject to authorize the final through the authorizer.
Sessionmanager:web application is generally used to manage the session with a Web container, Shiro also provides a set of session management methods.
Sessiondao: Using Sessiondao to manage session data, Sessiondao is required for personalized session data storage.
Cache Manager: Caching manager, which caches session and authorization data primarily, such as caching authorization data through CacheManager, and ehcache consolidation to manage cached data.
Realm: Domain, field, equivalent data source, through realm access authentication, authorization related data.

Shiro Frame composition


Subject: The main body, can be the user can also be a program, the main body to access the system, the system needs to authenticate the subject, authorization.

SecurityManager: Security Manager, the subject of authentication and authorization are carried out through the SecurityManager, is the core of Shiro.

Authenticator: The authenticator, the main body carries on the attestation finally through the authenticator carries on.

Authorizer: The authorization, the subject to authorize the final through the authorizer.

Sessionmanager:web application is generally used to manage the session with a Web container, Shiro also provides a set of session management methods.

Sessiondao: Using Sessiondao to manage session data, Sessiondao is required for personalized session data storage.

Cache Manager: Caching manager, which caches session and authorization data primarily, such as caching authorization data through CacheManager, and ehcache consolidation to manage cached data.

Realm: Domain, field, equivalent data source, through realm access authentication, authorization related data.

Example 1

Here is an example of getting started with authentication and authorization, requiring only a shiro-core jar package and the Slf4j-api.jar, commons-logging,

Commons-beanutils.jar, Hamcrest-core.jar, and JUnit, if you use Maven dependencies, just add Shiro-core, commons-logging, and JUnit.

I'm using the shiro1.3.2.

The following example uses the data in the Shiro-data-from-ini.ini file, simulating the database data, generally testing, the real project is definitely custom realm, and then to the database to obtain user information and permissions information, examples of the main steps are commented.

Shiro-data-from-ini.ini

#模拟用户数据源, account number = password, role, role ...
[Users]
pens=123,role1,role2
holien=123,role3

#设置角色, permissions, and resources (no longer works with realm)
# Format: Role = resource: Action: Instance, resource: Action equals resource: Action: *
[roles]
#角色role1对资源user拥有create, update permission
role1=user:create,user: Update
#角色role2对资源user拥有create, delete permissions
role2=user:delete
#角色role3对资源user拥有create权限
role3= User:create

#以上的数据在没有设置realm时才起作用

Test class: Authcandauthzbyinidata.class

Package Shiro_authenc;
Import Org.apache.shiro.SecurityUtils;
Import Org.apache.shiro.authc.UsernamePasswordToken;
Import Org.apache.shiro.config.IniSecurityManagerFactory;
Import Org.apache.shiro.mgt.SecurityManager;
Import Org.apache.shiro.subject.Subject;

Import Org.junit.Test;
Import Java.util.Arrays;

Import java.util.List; /** * Writer:holien * time:2017-08-19 20:30 * Intent: Use the test data in the INI file as the data source for authentication and authorization */public class Authcandauthzbyinid ATA {@Test public void Testauthcandauthozbyrealm () {/* identity authentication */INISECURITYM
        Anagerfactory factory = new Inisecuritymanagerfactory ("Classpath:shiro-data-from-ini.ini");
        SecurityManager SecurityManager = Factory.getinstance ();
        Associating the security Manager with security Tools Securityutils.setsecuritymanager (SecurityManager);
        Analog user form sent over the account password, the default name must be username and password, you can change the configuration file String username = "pens";
        String Password = "123"; Create a password (user entered the account password), account information and INI file account information matching can be certifiedSuccessful Usernamepasswordtoken token = new Usernamepasswordtoken (username, password);
        Gets the user principal Subject Subject = Securityutils.getsubject ();
        try {//Login, authentication (another thread executes this method), to INI file to compare user information Subject.login (token);
        } catch (Exception e) {e.printstacktrace ();
        } System.out.println ("Whether certified:" + subject.isauthenticated ());
Exit and then judge, regardless of authentication or authorization is false//subject.logout ();

        SYSTEM.OUT.PRINTLN ("Whether certified:" + subject.isauthenticated ()); /* Role-based authorization *//Verify that you have the specified role System.out.println ("Has role role1:" + subject.hasrole ("Role1
        "));
        Verify that you have one of these roles (I think it is intuitive to use multiple hasrole methods to make logical judgments) list<string> List = arrays.aslist ("Role1", "role2");
        Boolean[] B = subject.hasroles (list);
        System.out.println (B[0] + "" + b[1]); Verify that you have a set of roles that require multiple roles to have System.out.println together ("If you have both roles Role1 and role2:" + subject.hasallroles (arrays.aslist ("ROle1 "," Role2 ")));
        /* resource-based authorization */SYSTEM.OUT.PRINTLN ("Create permission for User:" + subject.ispermitted ("user:create")); SYSTEM.OUT.PRINTLN ("Whether you have Create, update, delete permissions for a user:" + subject.ispermittedall ("User:create", "User:update", "User
        :d elete "));
Unlike Ispermission, Checkpermisson will throw an exception if the corresponding permission is not detected subject.checkpermission ("User:create");  Subject.checkpermission ("User:batch");
 Throw Exception}}
Let's take a look at the basic use examples of the MD5 encryption that Shiro comes with.

Package Shiro_authenc;

Import Org.apache.shiro.crypto.hash.Md5Hash;
Import Org.junit.Test;

/**
 * Writer:holien
 * time:2017-08-20 20:38
 * Intent:shiro comes with MD5 encryption */public
class Md5test {
    @Test public
    void TestMD5 () {
        String password = "123";
        MD5 encryption Add salt
        String salt = "";
        Parameter 1: Password to encrypt parameter 2: Salt parameter 3:hash iteration number
        Md5hash Md5hash = new Md5hash (password, salt, 1);
        String Md5password = md5hash.tostring ();
        System.out.println (Md5password);  5319bf4ef8f5029ec32a4ad62a3f8eff
    }
}

Example 2
The following example uses realm, general custom classes inherit from Authorizingrealm, rewrite the abstract class of two methods, one for authentication, one for authorization, 2 methods need to go to the database or cache to obtain relevant information, here I also used the simulation data, After the integration of spring, then build a complete project. The difference between this example and the above example is mainly the difference between the data acquisition path, and the password is MD5 added salt encryption. Custom realm and encryption algorithms need to be configured in the INI file.

Shiro-realm.ini

[Main]
#定义凭证 (password) match
credentialsmatcher=org.apache.shiro.authc.credential.hashedcredentialsmatcher
#指定散列算法
credentialsmatcher.hashalgorithmname=md5
#散列次数
Credentialsmatcher.hashiterations=1

# Set up your custom realm
Customrealm=shiro_authenc. Customrealm
#将凭证匹配器设置到realm中
customrealm.credentialsmatcher= $credentialsMatcher
securitymanager.realms= $customRealm

This INI file defines the credential match, uses the MD5 algorithm, iterates 1 times, customizes the realm class reference to realm named Customrealm, and configures the previously defined credential match to Customrealm. Finally, the Customrealm is configured to SecurityManager. Custom Realm, inherited from Authorizingrealm's Customrealm.class


Package Shiro_authenc;
Import org.apache.shiro.authc.AuthenticationException;
Import Org.apache.shiro.authc.AuthenticationInfo;
Import Org.apache.shiro.authc.AuthenticationToken;
Import Org.apache.shiro.authc.SimpleAuthenticationInfo;
Import Org.apache.shiro.authz.AuthorizationInfo;
Import Org.apache.shiro.authz.SimpleAuthorizationInfo;
Import Org.apache.shiro.realm.AuthorizingRealm;
Import org.apache.shiro.subject.PrincipalCollection;

Import Org.apache.shiro.util.ByteSource;
Import java.util.ArrayList;

Import Java.util.Arrays; /** * Writer:holien * time:2017-08-20 14:47 * Intent: Custom realm, where the user information needs to be queried in the database, using the test data here, * configured realm will no longer read I User of NI file */public class Customrealm extends Authorizingrealm {//authorized @Override protected Authorizationinf o Dogetauthorizationinfo (principalcollection principalcollection) {//Authentication successful, user identity will be stored in principalcollection, we based on the primary user identity
     Go to the database to take the appropriate roles and permissions String username = (string) principalcollection.getprimaryprincipal ();   Simulate resource permissions taken from a database, format: resource: Action: instance arraylist<string> permissions = new arraylist<> ();
        Permissions.add ("User:create");
        Permissions.add ("User:update");
        Permissions.add ("User:delete");
        The role or permission to retrieve the database is stored in the Info object for the authorization check simpleauthorizationinfo info = new Simpleauthorizationinfo ();
        Info.addstringpermissions (permissions);
        Info.addroles (Arrays.aslist ("Role1", "Role2"));
        return info; Returns null}//Authentication @Override protected AuthenticationInfo dogetauthenticationinfo (authentic) if the corresponding role or permission is not queried
        Ationtoken Authenticationtoken) throws Authenticationexception {//from token to remove the user input account, according to the account to the database to take account, the following usercode to simulate
        String username = (string) authenticationtoken.getprincipal ();
        According to user input account number from the database to remove the account, we assume that the account taken out is called Usercode String usercode = "Pens";
        if (Usercode = = NULL | | usercode.equals ("")) {//If the account does not exist, return null return null;
            } else {Simulates a hashed password taken from the database based on the account number (MD5 hash once, salt 110), no return null is found, and the return info String password = "5319bf4ef8f5029ec32a4ad62a3f8eff" is obtained;
            Obtain salt from the database, assuming a String salt = "110";  Realm compares the password (database) contained in this object with the password in token (the password that the user entered is encrypted with salt), and the encryption algorithm specifies SIMPLEAUTHENTICATIONINFO info in the INI file.
            New Simpleauthenticationinfo (username, password, ByteSource.Util.bytes (salt), this.getname ());
        return info; }
    }
}
Test class: Testauthcandauthozbyrealm.class
Package Shiro_authenc;
Import Org.apache.shiro.SecurityUtils;
Import Org.apache.shiro.authc.UsernamePasswordToken;
Import Org.apache.shiro.config.IniSecurityManagerFactory;
Import Org.apache.shiro.mgt.SecurityManager;
Import Org.apache.shiro.subject.Subject;

Import Org.junit.Test;
Import Java.util.Arrays;

Import java.util.List;
    /** * Writer:holien * time:2017-08-19 20:30 * Intent: Use realm as a data source for authentication and authorization */public class Authcandauthzbyrealm { @Test public void Testauthcandauthozbyrealm () {/* identity authentication */Inisecuritymanagerf
        Actory factory = new Inisecuritymanagerfactory ("Classpath:shiro-realm.ini");
        SecurityManager SecurityManager = Factory.getinstance ();
        Associating the security Manager with security Tools Securityutils.setsecuritymanager (SecurityManager);
        Analog user form sent over the account password, the default name must be username and password, you can change the configuration file String username = "pens";
        String Password = "123";
      Create a password (user entered the account password), account information and realm go to the database to obtain the same account information can be certified successful  Usernamepasswordtoken token = new Usernamepasswordtoken (username, password);
        Gets the user principal Subject Subject = Securityutils.getsubject ();
        try {//Login, authentication (another thread executes this method), go to realm to compare user information Subject.login (token);
        } catch (Exception e) {e.printstacktrace ();
        } System.out.println ("Whether certified:" + subject.isauthenticated ());
Exit and then judge, regardless of authentication or authorization is false//subject.logout ();

        SYSTEM.OUT.PRINTLN ("Whether certified:" + subject.isauthenticated ()); /* Role-based authorization *//Verify that you have the specified role System.out.println ("Has role role1:" + subject.hasrole ("Role1
        "));
        Verify that you have one of these roles (I think it is intuitive to use multiple hasrole methods to make logical judgments) list<string> List = arrays.aslist ("Role1", "role2");
        Boolean[] B = subject.hasroles (list);
        System.out.println (B[0] + "" + b[1]); Verify that you have a set of roles that require multiple roles to have System.out.println together ("If you have both roles Role1 and role2:" + subject.hasallroles (arrays.aslist ("Role1", "ROle2 ")));
        /* resource-based authorization */SYSTEM.OUT.PRINTLN ("Create permission for User:" + subject.ispermitted ("user:create")); SYSTEM.OUT.PRINTLN ("Whether you have Create, update, delete permissions for a user:" + subject.ispermittedall ("User:create", "User:update", "User
        :d elete "));
Unlike Ispermission, Checkpermisson will throw an exception if the corresponding permission is not detected subject.checkpermission ("User:create");  Subject.checkpermission ("User:batch"); Throw Exception}}
Once the login method is called, it will go to the Dogetauthenticationinfo method in Customrealm to verify the user information, and the Hasrole method and ispermitted method are all called to Customrealm Dogetauthorizationinfo method to query, here a bit of resources, such as spring integration, using Ehcache to do the cache, do not have to customrealm each time to obtain, directly return the results of the cache.


Summarize the process

Certification Process :

1, subject (main) request authentication, call Subject.login (token)
2, SecurityManager (Security Manager) to perform the certification
3, SecurityManager through the Modularrealmauthenticator certification.
4. Modularrealmauthenticator token to Realm,realm user information (including identity and credentials) from the database based on token
5, realm If the user does not query to Modularrealmauthenticator return Null,modularrealmauthenticator throws an exception (the user does not exist)
6, realm if the query to the user to Modularrealmauthenticator return AuthenticationInfo (authentication information)
7, Modularrealmauthenticator take AuthenticationInfo (authentication information) to carry out the voucher (password) comparison. If it is consistent, the authentication passes if the inconsistency throws an exception (a credential error).

Authorization Process :

1, authorization to subject, call Method ispermitted ("permission string")
2, SecurityManager perform authorization, Modularrealmauthorizer execute authorization
3, Modularrealmauthorizer execute the Dogetauthorizationinfo method in realm (custom customrealm) query permission data from Database
4, realm query permission data from database, Return to Modularrealmauthorizer
5, Modularrealmauthorizer call Permissionresolver for permission string comparison
6, if alignment, ispermitted " Permission string "In the realm query to the permission data, the user access to the permission string has permissions, otherwise no permissions, throw an exception."
Next article is the integration of Shiro and spring, can no longer drag, refueling ...

Related Article

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.