2、Shiro的认证

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

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

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

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
    }

}
原文地址:https://www.cnblogs.com/luzhanshi/p/11023771.html