【shiro】shiro学习笔记1 - 初识shiro
认证流程
st=>start: Start
e=>end: End
op1=>operation: 构造SecurityManager环境
op2=>operation: Subject.login()提交认证
op3=>operation: SecurityManager.login()执行认证
op4=>operation: Authenticator执行认证
op5=>operation: Realm根据身份获取认证信息
st->op1->op2->op3->op4->op5->e
环境
-
目录
-
包依赖
pom.xml
<dependencies>
<!-- shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.4</version>
</dependency>
<!--日志问题的解决-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.15</version>
</dependency>
<dependency> <groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies></pre>
代码
AuthenticationTest.java
//创建SecurityManager环境
//1.创建SecurityManager工厂
Factory<SecurityManager> factory =
new IniSecurityManagerFactory("classpath:shiro-config.ini");
//2.通过工厂获得实例
SecurityManager securityManager = factory.getInstance();
//将SecurityManager设置到运行环境中
SecurityUtils.setSecurityManager(securityManager);
//Subject.login()提交认证
//1.创建Subject对象
Subject subject = SecurityUtils.getSubject();
//2.封装口令对象
AuthenticationToken token = new UsernamePasswordToken("kiwi", "123456");
//3.提交认证
try {
subject.login(token);
} catch (AuthenticationException e) {
e.printStackTrace();
}
System.out.println("认证:" + subject.isAuthenticated());
shiro-config.ini
[users]
kiwi = 123456
log4j.properties
log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
总结
1.刚开始运行老是报日志的问题
解决:引入slf4j-log4j12的jar包,具体参考关于SLF4J: Failed to load class的问题及解决
2.为什么要用ini文件而不用properties
因为ini文件可以分片,比如[users]就是划一片范围用于users信息