shiro 文档(中文译)提取码:us92
说在前面的话
在读本博客建议读读 这篇博客,以便更好地接受(学习)。
建议读一读上方的 shiro 文档。
博客的主要内容为 Tutorial.java 。关键代码部分已经给出注释,建议自己一步一步地进行编写。
项目结构
文件
Tutorial.java
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Tutorial {
private static final transient Logger log = LoggerFactory.getLogger(Tutorial.class);
public static void main(String[] args) {
System.out.println("My First Apache Shiro Application");
//注册并获取 SecurityManager 实例
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
//获取当前正在执行操作的用户
Subject currentUser = SecurityUtils.getSubject();
//用 session 做一些事(不需要一个 web 或 EJB 容器)
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String)session.getAttribute("someKey");
if(value.equals("aValue")){
System.out.println("Retrieved the correct value [" + value + "]");
}
//让当前用户登录,并检查他的角色和权限
if(!currentUser.isAuthenticated()){
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
//开启 shiro 的 Remember me 服务
//(不必细究)
token.setRememberMe(true);
try{
currentUser.login(token);
//当前账户不存在
} catch(UnknownAccountException unknownAccountExecption){
System.out.println("There is no user with username of " + token.getPrincipal());
//提供的证书(密码)错误
} catch(IncorrectCredentialsException incorrectCredentialsException){
System.out.println("Password for the account " + token.getPrincipal() + " was incorrcted!");
} catch(LockedAccountException lockedAccountException){
System.out.println("The account for username " + token.getPrincipal() + " is locked."
+ "Please contact your administrator to unlock it.");
}
// ........
//捕获其他可能出现的错误,当然异常类可以是自己实现的
}
//知道他是谁:记录下当前用户的用户名(或昵称)
System.out.println("User [" + currentUser.getPrincipal() + "] logged in successfull.");
//测试角色
if(currentUser.hasRole("schwartz")){
System.out.println("May the Schwartz be with you!");
} else {
System.out.println("Hello, mere mortal");
}
//测试权限一:非实例
if(currentUser.isPermitted("lightsaber:weild")){
System.out.println("You may use a lightsaber ring. Use it wisely");
} else {
System.out.println("Sorry, lightsaber rings are for schwartz master only.");
}
//测试权限二:实例
if(currentUser.isPermitted("winnerbago:drive:eagle5")){
System.out.println("You are permitted to \"drive\" the winnerbago with license plate(id) \"eagle5\"."
+ "Here are the keys ----- Have fun!");
} else {
System.out.println("Sorry, you aren't allowed to drive the \"eagle5\" winnerbago!");
}
//登出
currentUser.logout();
System.exit(0);
}
}
Subject 类的 RememberMe 与 Authenticated 的区别
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>shiroTestTwo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.2</version>
</dependency>
</dependencies>
</project>
shiro.ini
#[users]
#root = secret, admin
#guest = guest, guest
#presidentskroob = 123456, persident
#darkhelmet = ludicrousspeed, darklord, schwartz
#lonestart = vespa, goodguy, schwartz
#[roles]
#admin = *
#schwartz = lightsaber:*
#goodguy = winnerbago:drive:eagle5
# =============================================================================
# Tutorial INI configuration
# Usernames/passwords are based on the classic Mel Brooks' film" Spaceballs" :)
# =============================================================================
# Users and their (optional) assigned roles
# username = password, role1, role2, ..., roleN
[users]
root = secret, admin
guest = guest, guest
presidentskroob = 12345, president
darkhelmet = ludicrousspeed, darklord, schwartz
lonestarr = vespa, goodguy, schwartz
# Roles with assigned permissions
# roleName = perm1, perm2, ...., permN
[roles]
admin = *
schwartz = lightsaber:*
goodguy = winnebago:drive:eagle5