一.步骤总结
1.添加依赖
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.2</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
2.在resources中新建配置文件shiro.ini,文件名称任意,扩展名必须是ini
[users]
admin=1234
root=1234
3.新建测试类
实现步骤:
1)获取工厂,创建工厂时要传入shiro.ini,通过工厂获取securitryManager
IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
2.将获取到的securityManager对象放到工具类中
SecurityUtils.setSecurityManager(securityManager);
3.通过工具类获取subject
Subject subject = SecurityUtils.getSubject();
4.创建令牌Token,其中admin 和123就是客户端传入过来的
UsernamePasswordToken token = new UsernamePasswordToken("admin", "123");
5.调用subject的login方法,并将token传入进行认证
/* 这边进行认证,如果成功,则会走下一行,如若失败,会抛出异常
账号错误则抛UnknownAccountException异常
密码错误则抛IncorrectCredentialsException异常
反正是不会走下一行
*/
try {
subject.login(token);
System.out.println("认证成功");
} catch (UnknownAccountException u) {
System.out.println("未知账号异常");
} catch (IncorrectCredentialsException i) {
System.out.println("密码错误异常");
} catch (Exception e) {
e.printStackTrace();
System.out.println("系统发生未知错误");
}
测试类的完整代码
package com.yrp.test;
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;
/**
* @program: springboot
* @author: Mrs.ye
* @create: 2020-09-11 10:20
* @description: 账号认证和授权的入口
**/
public class ShiroTest {
public static void main(String[] args) {
IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("admin", "123");
try {
/* 这边进行认证,如果成功,则会走下一行,如若失败,会抛出异常
账号错误则抛UnknownAccountException异常
密码错误则抛IncorrectCredentialsException异常
反正是不会走下一行
*/
subject.login(token);
System.out.println("认证成功");
} catch (UnknownAccountException u) {
System.out.println("未知账号异常");
} catch (IncorrectCredentialsException i) {
System.out.println("密码错误异常");
} catch (Exception e) {
e.printStackTrace();
System.out.println("系统发生未知错误");
}
}
}