shiro第一个实例
原创
©著作权归作者所有:来自51CTO博客作者it999977的原创作品,请联系作者获取转载授权,否则将追究法律责任
maven
<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.12</version>
</dependency>
shiro.ini
[users]
lzh=123
java
package shiro
import org.apache.shiro.SecurityUtils
import org.apache.shiro.authc.AuthenticationException
import org.apache.shiro.authc.UsernamePasswordToken
import org.apache.shiro.config.Ini
import org.apache.shiro.config.IniSecurityManagerFactory
import org.apache.shiro.mgt.SecurityManager
import org.apache.shiro.subject.Subject
import org.apache.shiro.util.Factory
public class ShiroDemo {
public static void main(String[] args) {
// 初始化SecurityFactory工厂
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini")
// 获取SessionFactory实例
SecurityManager securityManager = factory.getInstance()
// 把SecurityManager实例绑定到SecurityUtils
SecurityUtils.setSecurityManager(securityManager)
// 获得当前执行的用户
Subject currentUser = SecurityUtils.getSubject()
// 创建token令牌,用户名/密码
UsernamePasswordToken token = new UsernamePasswordToken("lzh",
"123")
try {
//身份认证
currentUser.login(token)
System.out.println("身份认证成功!")
} catch (AuthenticationException e) {
e.printStackTrace()
System.out.println("身份认证失败!")
}
}
}