shiro's basic knowledge reserve -- authorization process

Posted by reto on Tue, 04 Jan 2022 04:05:53 +0100

Authorization Basics

1. Concept

Authorization is access control, which controls who can access which resources. After identity authentication, the principal needs to allocate permissions to access system resources. Some resources cannot be accessed without permissions.

2. Key objects

Who performs How operation on what ":

  • Who: the subject
  • What: refers to resources, system menus, pages, buttons, class methods, etc. resources include resource types and resource instances. For example, commodity information is resource type, commodity of type t01 is resource instance, and commodity information of No. 001 also belongs to resource instance.
  • How: permission, permission, specifies the permission of an entity to operate resources. Permission is meaningless when it leaves resources, such as user query permission, user add permission, call permission of a class method, modification permission of user No. 001, etc. through permission, you can know what the entity does on which resources.

3. Authorization process

The premise of authorization is to pass the certification.

4. Authorization method

  • Role based access control: RBAC role-based access control is role-based access control.
   What resources do you operate on 
  • Resource based access control: resource centric access control
If(subject.isPermission ("user:*:create")){
Create permission for all users

5. Permission string

Expressions: resource identifiers: actions: resource instance identifiers
This means what to do with the instance of that resource
User:*:01: any user has permission for any operation of 01 instance.

User:update:01: represents a resource instance
User:update: *: represents the resource type

6. Authorization realization

(1) The doGetAuthorizationInfo() method in AuthorizingRealm is overridden in the custom realm class.

package com.example.shiro.realm;

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;

//Add MD5+salt+hash using custom reaml
public class customerMd5Realm extends AuthorizingRealm {

//    Custom authorization method
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        Get identity information
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        System.out.println("Identity information:"+primaryPrincipal);
//        Obtain the role information and permission information of the current user according to the identity information and user name
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//        Assign the role information queried in the database to the permission object
//        Assign the query permission information in the database to the permission object
        return simpleAuthorizationInfo;

//   Custom authentication method
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        Get identity information
        String principal = (String) authenticationToken.getPrincipal();
//        Query database by user name
        if ("xiaochen".equals(principal)) {
//            This is the password generated by the simple MD55 algorithm
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(principal, "202cb962ac59075b964b07152d234b70", this.getName());
 *  md5+salt The generated password verification method has one more parameter, which is the expression for salt to generate random suffix
 * Parameter 1: user name in database parameter 2: password after md5+salt in database parameter 3: random salt during registration parameter 4: name of realm
 * And shiro will automatically identify random salts
 * If you want to use MD5+salt+hash, you need to set the number of hashes in the place of the specified algorithm
            SimpleAuthenticationInfo simpleAuthenticationInfo1 = new SimpleAuthenticationInfo(principal, "8a83592a02263bfe6752b2b5b03a4799", ByteSource.Util.bytes("X0*7ps"), this.getName());
            return simpleAuthenticationInfo;

        return null;

Programming, annotation, label.

(2) Check the authorized permissions in the authenticated user in the test class

package com.example.shiro.demoshiro;

import com.example.shiro.realm.customerMd5Realm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TestCustomerMd5RealmAuthenicator {
    public static void main(String[] args) {
//        Create security manager
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
//        The hash credential matcher is used to set the realm. Our customized realm inherits the authorizing realm, and the credential matcher can be set in the authorizing realm, but we need to create an object of the matcher
        customerMd5Realm realm = new customerMd5Realm();
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();//Create object for matcher
//        Use algorithm
        hashedCredentialsMatcher.setHashAlgorithmName("md5");//Name this matcher
//        If md5+salt+hash is used, specify the number of hashes
        hashedCredentialsMatcher.setHashIterations(1024);//Set the number of hash es for this matcher
        realm.setCredentialsMatcher(hashedCredentialsMatcher);//Set the matcher for this realm
//        Inject realm
//        Inject security manager into security tools
//        Obtain the subject through the security tool class
        Subject subject = SecurityUtils.getSubject();
//        authentication
        UsernamePasswordToken token = new UsernamePasswordToken("xiaochen", "123");
        try {
            System.out.println("Login successful");
        } catch (UnknownAccountException e) {
            System.out.println("Authentication failed");

        catch (IncorrectCredentialsException e) {
            System.out.println("Password error");
        //        Authenticate users for authorization
//            1. Role based permission control
//            Multi role based permission control
            System.out.println(subject.hasAllRoles(Arrays.asList("admin", "user")));
//            Do you have one of these roles
            System.out.println(subject.hasRoles(Arrays.asList("admin", "super", "user")));
//            Access control resource identifier based on permission string: Action: resource type
//            What permissions do you have
            boolean[] permitted = subject.isPermitted("user:*:01", "order:*:10");//Returned a bool array
            for (boolean b : permitted){
//            What permissions do you have at the same time
            boolean permittedAll = subject.isPermittedAll("user:*:01", "product:*");

Topics: Java Shiro intellij-idea