1、Shiro 基于 ini 配置实例
2019-08-19 本文已影响0人
Negen
Shiro 基于 ini 配置实例
基础环境
- JDK 1.8
- Maven 3
项目结构
目录结构.png1、创建Maven项目并引入以下相关依赖
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.24</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
2、Resource目录下创建配置文件 shiro.ini 并写入如下内容
[users]
test=123456
3、test目录下创建测试类 ShiroTest.java
public class ShiroTest {
@Test
public void shiroTest() {
//1、加载配置文件shiro.ini
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
//2、创建 SecurityManager 对象
SecurityManager securityManager = factory.getInstance();
//3、设置运行环境
SecurityUtils.setSecurityManager(securityManager);
//4、获取主体subject
Subject subject = SecurityUtils.getSubject();
//5、绑定主体登录账号及密码
// UsernamePasswordToken token = new UsernamePasswordToken("test", "12356"); //账号不存在
// UsernamePasswordToken token = new UsernamePasswordToken("admin", "123456"); //密码错误
UsernamePasswordToken token = new UsernamePasswordToken("test", "123456"); //正确的账号及密码
try {
//6、登录
subject.login(token);
System.out.println("登录成功");
}catch (UnknownAccountException unknownAccountException) {
System.out.println("账号不存在");
}catch (IncorrectCredentialsException incorrectCredentialsException) {
System.out.println("密码错误");
}
//验证登录状态
System.out.println("登录状态:" + subject.isAuthenticated());
}
}