Shiro from hearing to mastering series-2. Shiro realizes the login function (identity authentication practice)

Preface

The previous article introduced Shiro's architecture. We can find that there are not many things at the core of Shiro. We can remember Shiro's organization in a few minutes. Among them, Security Manager is the core of Shiro. It includes the authenticator, Authorizer, Session Manager, Session Manager, Cache Manager. In this article, we will introduce the process of Shiro's identity authentication, which is what we call user login.

Use Shiro for identity authentication

1. About identity authentication

1. What is identity authentication?

Identity authentication is to compare the user information stored in the database according to the user name and password entered by the user. If they are consistent, the authentication is successful, otherwise it fails. Shiro's configuration file is a file ending in .ini to store user information, authority information, etc., pay attention This file is only used for test scenarios. It will not be used in real development. In the actual project, this information is stored in the database, and the configuration file will not be written to death.

2. What must be known for identity authentication

We already know that identity authentication depends on Subject, which carries the user's information and password. So we also need to understand these two parts.

  1. Principal /ˈprɪnsəpl/: The main factor, here refers to the logged-in user information, that is, the user name. A principal can have multiple principals, such as user name, mobile phone number, email, etc., but one must be Primary Principal.
  2. credential /krəˈdenʃl/: Certificate, here refers to the password, which is the password for logging in.

3. Certification process

Insert picture description here
As shown in the above figure, Subject gets the user information and password, packs the information into a token Token, and then passes the token information to the Authenticator in the Security Manager, authenticates it, and then enters the system.

2. Use Shiro to realize the login function

1. The jar package that Shiro relies on

We only need to import its core package here, add the following dependencies in the pom file, choose the version by yourself, the version gap of the 1 series is not very big, here is the demonstration using version 1.5.3.

<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-core</artifactId>
  <version>1.5.3</version>
 </dependency>

2. Create a maven project

The first step is to create the project. We use the quick start option to create the project, as follows: The
Insert picture description here
second step is to create a resources file in the root directory of the project to store the .ini file, and at the same time create the Shiro configuration file of shiro.ini. Note that the file name does not matter, there is no mandatory naming rule.
Insert picture description here
Step 3: Write the configuration file and add the following information to the configuration file. The first line means that the key-value pair of user and password is configured below.

[users]
zhaoyun=daye
huangzhong=sheshou

Step 4: Add the above dependencies to the pom.xml file, as shown in the figure below.
Insert picture description here
So far, all the configurations we need are complete, and you can write the code below.
Step 5: Write the code, the code is shown as follows:

public class TestAuthenticator {
    
    
    public static void main(String[] args) {
    
    
        //第一步,获取Security Manager
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        //第二步,使用Security Manager加载配置文件,注意前面已经说过Realm是身份认证与权限的数据获取的地方,所以调用setRealm
        defaultSecurityManager.setRealm(new IniRealm("classpath:shiro.ini"));
        //第三步,使用SecurityUtils获取Subject
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();
        //第四步,获取用户登录Token
        UsernamePasswordToken authenticationToken = new UsernamePasswordToken("zhaoyun","daye");
        try {
    
    
            System.out.println(subject.isAuthenticated());
            //第五步,登录
            subject.login(authenticationToken);
            System.out.println(subject.isAuthenticated());
        } catch (UnknownAccountException e) {
    
    
            e.printStackTrace();
        }catch(IncorrectCredentialsException e){
    
    
            e.printStackTrace();
        }catch(Exception e){
    
    
            e.printStackTrace();
        }

    }
}

The output of the code above is as follows:

false
true

Process finished with exit code 0

3. Interpretation of code implementation

Each step has been divided in the code. It is worth mentioning that in the first step we used DefaultSecurityManager instead of SecurityManager. DefaultSecurityManager is his implementation class, so DefaultSecurityManager is used here.
The fifth step is to log in. This method has no return value. There are two methods to determine whether the login is successful or not. The first is to determine whether the program is abnormal. When the user name is abnormal, the program will report: UnknownAccountException, when the user enters the password When there is an error, it will report: IncorrectCredentialsException. In the second way, we can call the isAuthenticated method, which returns a boolean value. True means that the authentication is passed. We can see that it returns false before logging in and true after logging in, which means that the login is successful.

Three. Summary

At this point we have implemented a simple login function. However, this is just a demo that only includes login. In actual projects, there will be more complicated operations than this. This article introduces identity verification, and the next article will continue to discuss how to implement user login function by customizing Realm.

Guess you like

Origin blog.csdn.net/m0_46897923/article/details/114758852