认证过程

代码实现

引入Shiro依赖

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>

Java代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.ledao;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;

/**
* @author LeDao
* @company
* @create 2021-09-14 11:10
*/
public class Test {

public static void main(String[] args) {
SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();
//添加一个用户,参数为正确的用户名和密码
simpleAccountRealm.addAccount("ledao", "123456");
//构建SecurityManager环境
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
//将用户信息放入SecurityManager环境
defaultSecurityManager.setRealm(simpleAccountRealm);
//主体提交认证请求
SecurityUtils.setSecurityManager(defaultSecurityManager);
//获取构建SecurityManager环境的当前用户
Subject subject = SecurityUtils.getSubject();
//设置一个token用于登录,参数分别为用户登录的用户名和密码
UsernamePasswordToken token = new UsernamePasswordToken("ledao", "123456");
//当前状态为未登录,所以输出false
System.out.println("当前登录状态为:" + subject.isAuthenticated());
try {
//登录
subject.login(token);
//当前状态为登录成功,所以输出true
System.out.println("当前登录状态为:" + subject.isAuthenticated());
//注销登录
subject.logout();
System.out.println("当前登录状态为:" + subject.isAuthenticated());
} catch (AuthenticationException e) {
e.printStackTrace();
System.out.println("用户名或密码错误");
}
}
}

测试

  1. 当token的两个参数和正确的用户名密码一致时,登录成功

  2. 不一致时,登录失败