0. Write first

In a recent project, we implemented authentication and authorization of our system based on Shiro. Take this opportunity to write several blogs, summarize the problems encountered in this practice, and learn Shiro’s knowledge points comprehensively.

1. Rights management

Permission management Controls users’ access to the system. Users can access only authorized resources based on security rules or policies.

Permission management is divided into two parts: authentication and authorization.

2. Implementation scheme and model

At present, the mainstream solution is Spring Security +JWT or Shiro+JWT. There are also teams (companies) that write their own filters for access control. This is not recommended unless you design a permission management scheme that can stand the test of a production environment.

If you need to learn more about Spring Security, you can read my Spring Security article.

There are mainly several rights management models:

  1. Discretionary Access Control (DAC). A typical example is permission management on Windows operating systems. The biggest drawback of DAC is that it is difficult to manage permissions decentralized, such as simply setting uniform permissions on a set of files and granting them to a specific set of users.

  2. Mandatory Access Control (MAC) model. MAC was born to complement DAC, which digitally marks users and resources with their permission levels. A user can access a resource only when its permission level is higher than or equal to that of the resource. Otherwise, the user is denied access. For example, there is a resource 404.MP4 with the resource level of 1024. There is user Ferrayman with the permission level of 256 and user boss with the permission level of 2048. Boss then has normal access to the resource 404.mp4, while Ferrayman does not.

  3. Role-based Access Control (RBAC) is a role-based Access Control (RBAC) model that assigns roles to users. Roles correspond to certain resources, and users have Access rights to the resources under their roles. RBAC is divided into RBAC0, RBAC1, RBAC2, and RBAC3.

    We mainly use the RBAC model.

3. What is Shiro?

Apache Shiro™ is a Powerful and Easy to Use Java Security Framework that performs authentication, authorization, Cryptography, and Session Management. With 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.Copy the code

Apache Shiro is a powerful and easy-to-use Java security framework that performs authentication, authorization, password, and session management. Using Shiro’s easy-to-understand apis, you can quickly and easily obtain any application, from the smallest mobile applications to the largest web and enterprise applications.

3.1 Shiro of

Shiro has three major components: Subject, SecurityManager, and Realms.

3.1.1 the Subject:

The current subject. In Shiro, the concept of Subject does not just refer to people, but can also be third-party processes, Daemon accounts, or similar things. It simply means “what is currently interacting with the software.” Subject represents the security actions of the current user, and SecurityManager manages the security actions of all users.

It mainly consists of identity information Principals and voucher Principals. Principal can be understood as the account of the Principal in the system and is unique. The Principals can be understood as passwords, certificates corresponding to the Principals’ current system accounts.

3.1.2 SecurityManager:

It is the core of Shiro’s framework, a typical Facade pattern, through which Shiro manages internal component instances and provides various services for security management.

3.1.3 Realm:

Realm acts as a “bridge” or “connector” between Shiro and application security data. That is, when authenticating a user (login) and authenticating a user (access control), Shiro looks up the user and their permission information from an application-configured Realm.

In this sense, a Realm is essentially a security-related DAO: It encapsulates the connection details of the data source and provides related data to Shiro when needed. When configuring Shiro, you must specify at least one Realm for authentication and/or authorization. It is possible to configure multiple Realms, but at least one is required.

Shiro has built-in Realms that can connect to a large number of secure data sources (aka directories), such as LDAP, relational databases (JDBC), ini-like text configuration resources, and properties files. If the default Realm does not meet your requirements, you can also insert your own Realm implementation that represents a custom data source.

4 Shiro’s advantages

Simple and flexible.

It is simpler to use than Spring Security. Support not only Web applications but also non-Web applications, seamless integration.

5 一个Demo

Create an empty Maven project and introduce the following dependencies

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.5.3</version>
</dependency>
<! Easy to test -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
     <scope>test</scope>
</dependency>
Copy the code

Import Shiro’s configuration file

Shiro’s configuration file is a file ending in “.ini “. Ini format is used because the file type supports complex data formats. It is used to store shiro’s permission data. This is mainly used to learn shiro. In normal projects, permission data is stored in the database.

Configure the identity information and credentials of the principal

[users]
xiangbei=123
xiangname=123
Copy the code

Creating an Authenticator

package pers.lbf.shirodemo.core;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;

/** Authenticator *@authorLaifeng [email protected] *@version 1.0
 * @date2020/9/21 0:50 * /
public class Authenticator {

    private DefaultSecurityManager securityManager;

    public Authenticator(a){
        1. Create a security manager
        this.securityManager = new DefaultSecurityManager();

        //2. Set the problem domain for the security manager
        // Because permission information is read from the INI file, it is IniRealm
        this.securityManager.setRealm(new IniRealm("classpath:shiro.ini"));

        //3. Inject the security manager and use the SecurityUtils global security tool class to complete authentication
        SecurityUtils.setSecurityManager(securityManager);



    }

    /**认证
     * @authorLaifeng [email protected] *@dateThe 2020-09-23 16:22:11 *@paramUsername username *@param"Password," password *@return void
     * @version1.0 * /
    public void authenticate(String username,String password){
        //4. Get the current topic
        Subject subject = SecurityUtils.getSubject();

        //5. Create a login token based on the identity certificate information of the login object
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        / / 6. Certification
        If the authentication passes, no exception is thrown; otherwise, the AuthenticationExceptixon exception subclass is thrown
        // It is recommended to throw a formal project directly to handle exceptions
        try {
            subject.login(token);
        }catch (IncorrectCredentialsException e) {
            e.printStackTrace();
        }catch (ConcurrentAccessException e){
            e.printStackTrace();
        }catch (UnknownAccountException e){
            e.printStackTrace();
        }catch (ExcessiveAttemptsException e){
            e.printStackTrace();
        }catch (ExpiredCredentialsException e){
            e.printStackTrace();
        }catch(LockedAccountException e){ e.printStackTrace(); }}}Copy the code

Testing, simulation certification

package shirodemo;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.junit.Before;
import org.junit.Test;
import pers.lbf.shirodemo.core.Authenticator;

/** Test authentication *@authorLaifeng [email protected] *@version 1.0
 * @date2020/9/21 0:49 * /

public class TestAuthenticator {
    private  Authenticator authenticator=null;

    @Before
    public void init(a) {
        authenticator = new Authenticator();
    }

    @Test
    public void testAuth(a){

        authenticator.authenticate("xiangbei"."123"); }}Copy the code

The six is at the end

Today, we are going to start learning about Shiro with a simple demo. However, this knowledge is not enough for us to apply it to our products. In the following series of Shiro Xiu Xian Gongfu (articles), the author will follow you to learn shiro’s application.