Apache Shiro -- Java安全框架
执行身份验证, 授权, 密码学和会话管理
1, Authentication 认证 -- 用户登录;
2, Authorization 授权 -- 用户具有哪些权限;
3, Cryptography 安全数据加密;
4, Session Management 会话管理
Spring boot shiro
十分钟快速开始----流程
maven配置:
<!--版本号到maven仓库中查找-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifctId>shiro-core</artifctId>
<version>1.4.1</version>
</dependency>
<!-- configure loggin -->
<dependency>
<groupId>org.slf4j</groupId>
<artifctId>jcl-over-slf4j</artifctId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifctId>slf4j-log4j12</artifctId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifctId>log4j</artifctId>
<version>1.2.17</version>
</dependency>
**日志log4j, xml配置: **( 文件名称: log4j.properties )
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
# General Apache libraries
log4j.logger.org.apache=WARN
# Spring
log4j.logger.org.springframework=WARN
# Default Shiro logging
log4j.logger.org.apache.shiro=INFO
# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
shiro配置文件:
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz
# -----------------------------------------------------------------------------
# Roles with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5
java文件:
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.ini.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.lang.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Simple Quickstart application showing how to use Shiro's API.
*
* @since 0.9 RC2
*/
public class Quickstart {
// 使用log进行日志输出:
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
//创建Shiro SecurityManager的最简单方法
//领域、用户、角色和权限使用简单的INI配置。
//我们将通过使用一个可以接收.ini文件和
//返回SecurityManager实例:
//在类路径的根使用shiro.ini文件
// (file:和url:分别从文件和url加载前缀):
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
//对于这个简单的示例《快速入门》,创建SecurityManager
//可以作为JVM单例访问。大多数应用程序不会这样做
//而依赖于它们的容器配置或web.xml
//webapps。这超出了这个简单的快速入门的范围
//我们只做最基本的,这样你可以继续得到感觉
//对的事情。
SecurityUtils.setSecurityManager(securityManager);
// 现在已经设置了一个简单的Shiro环境,让我们看看您可以做些什么:
// 获取当前执行的用户:
// Subject: 三大对象之一
Subject currentUser = SecurityUtils.getSubject();
// 通过当前用户拿到session
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
// 让我们登录当前用户,这样我们可以检查角色和权限:( 判断当前用户,是否被认证 )
if (!currentUser.isAuthenticated()) {
// token: 令牌
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
token.setRememberMe(true); // 设置记住我
try {
currentUser.login(token); // 执行登陆操作
} catch (UnknownAccountException uae) { //
log.info("There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
log.info("Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) {
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
// ... catch more exceptions here (maybe custom ones specific to your application?
catch (AuthenticationException ae) {
//unexpected condition? error?
}
}
//say who they are:
//print their identifying principal (in this case, a username):
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//test a role:
if (currentUser.hasRole("schwartz")) {
log.info("May the Schwartz be with you!");
} else {
log.info("Hello, mere mortal.");
}
//test a typed permission (not instance-level)
if (currentUser.isPermitted("lightsaber:wield")) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
//a (very powerful) Instance Level permission:
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}
//all done - log out!
currentUser.logout();
System.exit(0);
}
}
Spring boot 中集成
核心的三大对象:
- Subject: 用户
- SecurityManager: 管理所有用户
- Realm: 连接数据
spring Boot 整合 shiro 的包
<dependency>
<groupId>org.apache.shiro</groupId>
<artifctId>shiro-spring</artifctId>
<version>1.3.2</version>
</dependency>
Shiro 三大对象:
- ShiroFilterFactoryBean
- DafaultWebSecurityManager
- 创建 realm 对象 需要自定义
注解
@RequiresAuthentiocation: 验证用户是否登录, 等同于方法subject.isAuthenticated() 结果为 true 时.
@RequiresUser:
验证用户是否被记忆, user 有两种含义:
一种是成功登录的( subject.isAuthenticated() 结果为 true);
另一种是被记忆的( subject.isRemembered() 结果为 true).
@RequiresGuest:
验证是否是一个gues的请求, 与@RequestUser 完全相反
换而言之, RequiresUser ==!RequiresGuest
此时 subject.getPrincipal() 结果为 null.
@RequiresRoles:
例如: @RequiresRoles("aRoleName");
void someMethod();
如果subject中有aRoleName角色才可以访问方法someMethod. 如果没有这个权限则会抛出异常AuthorizationException.
@RequiresPermissions
例如: @RequiresPermissions({"file:read",write:aFile.txt}) void someMethod();
要求subject 中必须同时含有file:read和write : aFile.txt 的权限才能执行方法 someMethod(). 否则抛出异常AuthorizationException.
网友评论