授权过程

代码实现

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
47
48
49
50
package com.ledao;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
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();
//添加一个用户,该用户的角色有admin和teacher
simpleAccountRealm.addAccount("ledao", "123456", "admin", "teacher");
//构建securityManager环境
DefaultSecurityManager securityManager = new DefaultSecurityManager();
//将上面的用户交给securityManager管理
securityManager.setRealm(simpleAccountRealm);
//提交认证请求
SecurityUtils.setSecurityManager(securityManager);
//获取当前securityManager环境的subject主体
Subject subject = SecurityUtils.getSubject();
subject.checkRoles("admin", "teacher1");
//设置登录用户的token
UsernamePasswordToken token = new UsernamePasswordToken("ledao", "123456");
try {
//登录
subject.login(token);
//查看是否登录成功
System.out.println(subject.isAuthenticated() ? "登录成功" : "登录失败");
try {
//检查成功登录的用户是否有admin和teacher1两个角色
subject.checkRoles("admin", "teacher1");
} catch (AuthorizationException e) {
e.printStackTrace();
System.out.println("登录的用户与检查的角色不相符!!");
}
} catch (AuthenticationException e) {
e.printStackTrace();
System.out.println("用户名或密码错误!!");
}
}
}

测试

如果subject.checkRoles(“admin”, “teacher1”),那么程序会报错,提示没有teacher1这个角色;如果subject.checkRoles(“admin”, “teacher”),那么程序不会报错