1.首先创建一个普通的Maven工程
2.导入POM文件依赖---依赖如下
也可进入shiro官网查看需要的依赖“Download Apache Shiro | Apache Shiro”
org.apache.shiro shiro-core1.3.2 org.apache.shiro shiro-web1.3.2 org.apache.shiro shiro-spring1.3.2 org.slf4j slf4j-api1.7.33 log4j log4j1.2.12 junit junit4.12
3.在resources下创建*.ini文件
4.创建一个测试类
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.junit.Test;
public class ShiroTest {
@Test
public void shiroTest(){
//1.读取配置文件,创建安全管理器:SecurityManger
IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.createInstance();
//2.将对象工场和当前线程绑定
SecurityUtils.setSecurityManager(securityManager);
//3.从当前线程获取主题对象:Subject
Subject subject = SecurityUtils.getSubject();
//创建令牌:封装身份(账号和密码)
//UsernamePasswordToken token = new UsernamePasswordToken("lucky","abc123");
boolean authenticated = subject.isAuthenticated();
System.out.println("认证前"+authenticated);
if (!authenticated){
//创建令牌:封装身份(账号和密码)
UsernamePasswordToken token = new UsernamePasswordToken("lucy","abc123");
try {
subject.login(token);
authenticated=subject.isAuthenticated();
System.out.println("认证后"+authenticated);
}catch (UnknownAccountException e){
System.out.println("用户名错误");
}catch (IncorrectCredentialsException e){
System.out.println("密码错误");
}
//获取用户身份
Object principal = subject.getPrincipal();
System.out.println("用户身份"+principal);
//退出登录
subject.logout();
authenticated=subject.isAuthenticated();
System.out.println("退出后认证"+authenticated);
}
}
}
5.测试结果
6.用户名错误 与密码错去运行截图如下:
7.小伙伴们可自行更改:里面的用户和密码进行测试
UsernamePasswordToken token = new UsernamePasswordToken("lucy","1abc123");



