1_shiro introduction and Practice

1. Authentication and Authorization of Rights Management

Privilege management includes two parts: user identity authentication and authorization, referred to as authentication authorization. Users of resources requiring access control are first authenticated, after which they have access to the resource.

1.1 What is authentication

Identity authentication is the process of determining whether a user is a legitimate user. The most common simple authentication method is to check the user name and password entered by the user to see if they are consistent with the user name and password stored in the system to determine if the user's identity is correct. For adoption fingerprint Wait for system, then show fingerprint; For card brushing systems such as hardware Key, you need to brush the card.

1.2 What is authorization

Authorization, or access control, controls who can access which resources. The principal needs to assign permissions after authenticating to access the system's resources. Some resources are inaccessible without permissions

2. Shiro Permission Authentication

2.1 Introduction to Shiro

Shiro is a powerful and easy-to-use Java security framework that performs authentication, authorization, encryption, and session management. Using Shiro's easy-to-understand API, you can quickly and easily secure any application, from the smallest mobile applications to the largest web and enterprise applications. Shiro is an open source framework under apache. It extracts functions related to security authentication of software system, implements user identity authentication, authorization of rights, encryption, session management and other functions, and forms a universal security authentication framework.

2.2 shiro architecture

 

2.2.1 Subject

Subject is the principal, the external application interacts with the subject, which records the current operating user and interprets the user's concept as the principal of the current operation, either a user requested through a browser or a running program. Subject is an interface in shiro that defines a number of authentication grant-related methods. External programs are granted by subjects, while subjects are authorized by SecurityManager Security Manager

2.2.2 SecurityManager

SecurityManager, the security manager, is the core of shiro, which manages all subjects securely. subject authentication, authorization, etc. can be accomplished through SecurityManager. Essentially, SecurityManager is authenticated through Authenticator, authorized through Authorizer, session management through SessionManager, etc.

SecurityManager is an interface that inherits three interfaces: Authenticator, Authorizer, and SessionManager.

2.2.3 Authenticator

Authenticator is the authenticator, which authenticates the user's identity. Authenticator is an interface. shiro provides the ModularRealmAuthenticator implementation class, which can basically meet most requirements or customize the authenticator.

2.2.4 Authorizer

Authorizer is an authorizer. Users are authenticated by the authenticator. When accessing a function, you need to use the authorizer to determine whether the user has the operation rights of the function.

2.2.5 Realm

Realm is a realm, which is equivalent to datasource data source. Security Manager needs to obtain user privilege data through Realm for security authentication. For example, if user identity data is in the database, realm needs to obtain user identity information from the database.

Note: Don't think of realms as simply taking data from a data source. There is also code associated with the Authentication Check in realms.

2.2.6 SessionManager

Session Manager is session management. The shiro framework defines a set of session management that does not depend on web container sessions, so shiro can either use non-Web applications or focus distributed application sessions on one point management, which enables it to achieve single sign-on.

2.2.7 SessionDAO

SessionDAO, or session dao, is a set of interfaces for session session operation, such as storing sessions in a database through jdbc.

2.2.8 CacheManager

CacheManager is cache management, which stores user rights data in the cache to improve performance.

2.2.9 Cryptography

Cryptograph is password management, and shiro provides a set of encryption/decryption components for easy development. For example, it provides functions such as hashing, encryption/decryption.

3. Shiro's certification

Identity authentication is to determine whether a user is a user of this system. The simplest form of authentication is to check the username and password that a user enters, which is consistent with the username and password stored in the system to determine whether it is a normal user.

Key Authenticated Objects in 1.1 shiro

Subject: Body

Users who access the system, the principal can be users, programs, etc., and those who authenticate are called principals.

Principal: Identity information [typically user name]

It is the identity for the subject to authenticate. The identity must be unique, such as user name, mobile phone number, mailbox address, etc. A subject can have multiple identities, but it must have a principal identity.

Credential: credential information [typically password]

Is the security information, such as password, certificate, etc., that only the principal knows.

1.2 Dependency

<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-spring-boot-starter</artifactId>
  <version>1.5.3</version>
</dependency>

1.3 Custom realm authentication

public class CustomerRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    //To grant authorization
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    //Authentication
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //The username and password token enters for the front end
        String username = (String) token.getPrincipal();
        User exist = userService.getUserByUsername(User.builder().name(username).build());
        if (exist == null) return null;
        
        //Parameter 1: Correct user name in principal database//Parameter 2: Correct password stored by this user in the database//Parameter 3: Provide the name of the current realm [this.getName() uses the default Relm name provided at the bottom level]
        //SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username,"123456", this.getName());
        
        //Parameter 1:principal; Parameter 2: Password of the database; Parameter 3: Database salt; Parameter 4: Name of the custom reaml (default)
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, exist.getPassword(), ByteSource.Util.bytes(exist.getSalt()), this.getName());
        return simpleAuthenticationInfo;
    }
}

1.4 Use Security Manager authentication

public static void main(String[] args) {
    //1. Create a security manager object
    DefaultSecurityManager securityManager = new DefaultSecurityManager();
    //2. Set realm for Security Manager
    //This is to get realm from ini file
    //securityManager.setRealm(new IniRealm("classpath:shiro.ini"); // Incoming Relm read from configuration file
    
     CustomerRealm1 customerRealm1 = new CustomerRealm1(); //Incoming custom realm
     //Set md5 encryption [Compare the incoming password after md5 and salt, and then the md5 retrieved from the database]
    HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
    credentialsMatcher.setHashAlgorithmName("MD5");
    credentialsMatcher.setHashIterations(1024); //Set number of hashes
    customerRealm1.setCredentialsMatcher(credentialsMatcher); //Set credential (password) matcher for realm
    securityManager.setRealm(customerRealm1); //Setting up a custom realm for the Security Manager

    //3. Set up a security manager for the global security tool class SecurityUtils
    SecurityUtils.setSecurityManager(securityManager);
    //4. Get the subject body of the principal object currently logged in
    Subject subject = SecurityUtils.getSubject();
    //5. Accounts and passwords entered by front-end users form token tokens
    UsernamePasswordToken token = new UsernamePasswordToken("James","123456");

    try{
        System.err.println("Authentication status: "+ subject.isAuthenticated()); //This is false
        subject.login(token); //Perform user authentication
        System.err.println("Authentication status: "+ subject.isAuthenticated()); //This is true
    }catch (UnknownAccountException e){
        System.err.println("Authentication Failure: user name does not exist~");
    }catch (IncorrectCredentialsException e){
        System.err.println("Authentication Failure: Password error~");
    }

    //Authorize after certification is complete
    if (subject.isAuthenticated()){
        //Has the specified role
        boolean user = subject.hasRole("user");

        //Which of the roles listed are owned by
        boolean[] booleans = subject.hasRoles(Lists.newArrayList("admin", "user", "super"));

        //Has all the roles specified
        boolean b = subject.hasAllRoles(Lists.newArrayList("user", "admin"));

        //Which of the specified permissions are owned by this subject s
        boolean[] permitted = subject.isPermitted("Permission 1", "Permission 2", "Permission 3");

        //Is there a permission
        boolean permitted1 = subject.isPermitted("user:update:*");

        //Has all the permissions specified
        boolean permittedAll = subject.isPermittedAll("user:update:*", "product1:*:*");
    }
}

4. Shi shiro's Authorization

Authorization is access control, which controls which resources a user can access and which resources or interfaces cannot access. The principal needs to assign permissions to access the system's resources after completing authentication.

4.1 Authorization Process

Who, or Subject, requires access to resources in the system.

What, that is, resources, such as system menus, pages, buttons, class methods, system commodity information, etc. Resources include resource types and resource instances, such as commodity information is resource type, commodity of type t01 is resource instance, commodity information of number 001 is also resource instance.

How, Permission, defines the operating permission of the principal for the resource. It does not make sense for the principal to leave the resource with permission, such as user query permission, user add permission, calling permission of a class method, modifying permission of user number 001, etc. Permission can tell which resources the principal has operating permission for.

  4.2 Custom Authorization

    //To grant authorization
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        System.out.println("Identity Information:"+primaryPrincipal);

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole("admin"); //Set up roles for authorization
        simpleAuthorizationInfo.addRole("user");
        simpleAuthorizationInfo.addStringPermission("user:update:*"); //Set permissions for authorization
        simpleAuthorizationInfo.addStringPermission("product:*:*");

        return simpleAuthorizationInfo;
    }

4.3   View authorization using security manager

public static void main(String[] args) {
    //Create Security Manager
    DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
    CustomerRealm customerRealm = new CustomerRealm();
    //Set md5 encryption
    HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
    credentialsMatcher.setHashAlgorithmName("MD5");
    credentialsMatcher.setHashIterations(1024);//Set number of hashes
    customerRealm.setCredentialsMatcher(credentialsMatcher);
    defaultSecurityManager.setRealm(customerRealm);
    //The default security manager will be installed in the tool class
    SecurityUtils.setSecurityManager(defaultSecurityManager);
    //Get Principal Object
    Subject subject = SecurityUtils.getSubject();
    //Create token token
    UsernamePasswordToken token = new UsernamePasswordToken("xiaochen", "123");
    try {
        subject.login(token);//User Login
        System.out.println("Login Successful~~");
    } catch (UnknownAccountException e) {
        System.out.println("User name error!!");
    }catch (IncorrectCredentialsException e){
        System.out.println("Password error!!!");
    }
    
    //Certification Passed
    if(subject.isAuthenticated()){
        //Role-based privilege management
        boolean admin = subject.hasRole("admin");
        System.out.println(admin);

        boolean permitted = subject.isPermitted("product:create:001");
        System.out.println(permitted);
    }
}

Keywords: Java Spring Spring Boot Back-end security

Added by dirkdetken on Wed, 01 Dec 2021 01:06:28 +0200