Shiro的认证
接下来是在IDEA进行Shiro的学习,新建一个Springboot工程,除了一些默认的依赖,这里需要引入apache.shiro安全框架依赖,以及做单元测试的依赖。
1<dependencies>
2 <dependency>
3 <groupId>org.springframework.boot</groupId>
4 <artifactId>spring-boot-starter</artifactId>
5 </dependency>
6
7 <dependency>
8 <groupId>org.springframework.boot</groupId>
9 <artifactId>spring-boot-starter-test</artifactId>
10 <scope>test</scope>
11 </dependency>
12 <!--apache.shiro安全框架-->
13 <dependency>
14 <groupId>org.apache.shiro</groupId>
15 <artifactId>shiro-core</artifactId>
16 <version>1.4.0</version>
17 </dependency>
18 <!--单元测试-->
19 <dependency>
20 <groupId>junit</groupId>
21 <artifactId>junit</artifactId>
22 </dependency>
23 <dependencies>
创建一个新的测试类
1public class AuthenticationTest {
2 //演示例子使用SimpleAccountRealm
3 SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();
4 //认证之前在Realm中添加一个用户
5 @Before
6 public void addUser(){
7 simpleAccountRealm.addAccount("jiuyue","12345");
8 }
9 @Test
10 public void testAuthentication(){
11 //1. 构建securityManager环境
12 DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
13 defaultSecurityManager.setRealm(simpleAccountRealm);//将simpleAccountRealm设置到环境中
14 SecurityUtils.setSecurityManager(defaultSecurityManager);//SecurityUtils设置securityManager环境
15 //2. 设置主体要比较的认证、
16
17 Subject subject= SecurityUtils.getSubject();
18 //3. 对提交的主体进行认证
19 UsernamePasswordToken token = new UsernamePasswordToken("jiuyue","12345");
20 subject.login(token);
21 System.out.println("isAuthenticated: "+subject.isAuthenticated());
22 subject.logout();
23 System.out.println("isAuthenticated: "+subject.isAuthenticated());
24 }
25}
代码实现思路:
代码分析:
首先通过new DefaultSecurityManager()构建SecurityManager环境,将SimpleAccountRealm设置到环境中。
接着获取 SecurityManager 并绑定到 SecurityUtils,这是一个全局设置,设置一次即可。
通过 SecurityUtils 得到 Subject,其会自动绑定到当前线程;如果在 web 环境在请求结束时需要解除绑定。然后获取身份验证的 Token,如用户名,密码。
调用 subject.login 方法进行登录,其会自动委托给 SecurityManager.login 方法进行登录。
Shiro授权
Shiro的授权与Shiro的认知处理其实是一样的思路。
1public class AuthenticationTest2 {
2 SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();
3 @Before
4 public void addUser(){
5 //simpleAccountRealm.addAccount("jiuyue","12345","admin");
6 simpleAccountRealm.addAccount("jiuyue","12345","admin","user");
7 }
8 @Test
9 public void testAuthentication(){
10 //1.构建SecurityManager环境
11 DefaultSecurityManager defaultSecurityManager= new DefaultSecurityManager();
12 defaultSecurityManager.setRealm(simpleAccountRealm);
13 SecurityUtils.setSecurityManager(defaultSecurityManager);
14 Subject subject = SecurityUtils.getSubject();
15 //2.主体提交授权认证
16 UsernamePasswordToken token = new UsernamePasswordToken("jiuyue","12345");
17 subject.login(token);
18 //checkRole检查主体是否具有啥权限
19 //subject.checkRole("admin");
20 subject.checkRoles("admin","user");
21
22 }
23}
专题链接:
Shiro安全框架第一篇| 什么是Apache Shiro?
“扫码关注“