首页 技术 正文
技术 2022年11月9日
0 收藏 959 点赞 2,992 浏览 1750 个字

Shiro的认证流程大体可以参考下面这幅图:

2、Shiro的认证

但是没有接触过shiro的同学看到上面的图片也不明白,下面我们来在代码中尝试体验Shiro的认证过程:

1.新建一个SpringBoot项目项目结构如下:

2、Shiro的认证

2、Shiro的认证

ShiroframeApplicationTests代码:

package com.shiro.shiroframe;import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;public class ShiroframeApplicationTests {//realm,暂时用来存储我们假造的用户信息
SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();
@BeforeEach//@BeforeEach注解的作用就是使她下面的方法在其他方法运行之前执行
public void addUser(){
//设置假造的用户信息,在Realm里面添加一个用户
simpleAccountRealm.addAccount("qqq", "aaa");
}
@Test
public void authenticator() {
//1.构建SecurityManager环境
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
//设置SecurityManager环境下的Realm
defaultSecurityManager.setRealm(simpleAccountRealm);
//SecurityUtils先获取SecurityManager环境
SecurityUtils.setSecurityManager(defaultSecurityManager);
//通过SecurityUtils获取Subject主体
Subject subject = SecurityUtils.getSubject();
//通过UsernamePasswordToken组织提交认证所要传递的参数
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("qqq", "aaa");
//提交登录认证
subject.login(usernamePasswordToken);
//打印是否认证通过:subject.isAuthenticated()
System.err.println("isAuthenticated:" + subject.isAuthenticated());//账号密码匹配的情况下打印结果:isAuthenticated:true;否则控制台报错:org.apache.shiro.authc.UnknownAccountException: Realm [org.apache.shiro.realm.SimpleAccountRealm@2cbb3d47] was unable to find account data for the submitted AuthenticationToken [org.apache.shiro.authc.UsernamePasswordToken - qq, rememberMe=false].
//登出
subject.logout();
//登出之后认证返回false
System.err.println("isAuthenticated:" + subject.isAuthenticated());//isAuthenticated:false
}}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,487
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,487
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,127
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,289