一、Shiro简介
1.什么是Shiro?
Apache Shiro是一个功能强大且灵活的开源安全框架,可以干净地处理身份验证,授权,企业会话管理和加密。
- Apache Shiro是一个Java的安全(权限)框架。
- Shiro 可以非常容易的开发出足够好的应用,其不仅可以用在JavaSE环境,也可以用在JavaEE环境。
- Shiro可以完成,认证,授权,加密,会话管理。Web集成,缓存等。
- 下载地址: http://shiro.apache.org/
2.Apache Shiro功能
Shiro以Shiro开发团队所谓的“应用程序安全性的四个基石”为目标-身份验证,授权,会话管理和密码学:
-
Authentication(身份验证):有时称为“登录”,这是证明用户是他们所说的身份的行为。
-
Authorization(授权):访问控制的过程,即确定“谁”有权访问“什么”。
-
Session Management(会话管理):即使在非Web或EJB应用程序中,也可以管理特定于用户的会话。
-
Cryptography(密码学):使用密码算法保持数据安全,同时仍然易于使用。
在不同的应用程序环境中,还具有其他功能来支持和加强这些问题,尤其是:
- Web Support (Web支持):Shiro的Web支持API可帮助轻松保护Web应用程序。
- Caching(缓存):缓存是Apache Shiro API的第一层公民,可确保安全操作保持快速有效。
- Concurrency(并发性):Apache Shiro的并发功能支持多线程应用程序。
- Testing(测试):测试支持可帮助您编写单元测试和集成测试,并确保您的代码将按预期进行保护。
- “Run As”(“运行方式”):一种功能,允许用户采用其他用户的身份(如果允许),有时在管理方案中很有用。
- “Remember Me”(“记住我”):在各个会话中记住用户的身份,因此仅在必要时才需要登录。
3.Shrio架构(外部)
Shrio的架构有3个主要的概念:Subject,Security Manager和Realms
- Subject:应用代码直接交互的对象是Subject,也就是说Shiro的对外API核心就是Subject,Subject代表了当前的用户,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是Subject,如网络爬虫,机器人等,与Subject的所有交互都会委托给Security Manager; Subject其实是一个门面,Security Manager才是实际的执行者。
- Security Manager:安全管理器,即所有与安全有关的操作都会与Security Manager交互,并且它管理着所有的Subject,可以看出它是Shiro的核心,它负责与Shiro的其他组件进行交互,它相当于SpringMVC的DispatcherServlet的角色。
- Realm: Shiro从Realm获取安全数据(如用户,角色,权限),就是说Security Manager要验证用户身份,那么它需要从Realm 获取相应的用户进行比较,来确定用户的身份是否合法;也需要Realm得到用户相应的角色、权限,进行验证用户的操作是否能够进行,可以把Realm看成Data Source;
4.Shiro(内部)
4. Subject:任何可以与应用交互的‘'用户;
5. Security Manager:相当于SpringMVC中的DispatcherServlet;是Shiro的心脏,所有具体的交互都通过Security Manager进行控制,它管理这所有的Subject,且负责进行认证,授权,会话,及缓存的管理。
6. Authenticator:负责Subject认证,是一个扩展点,可以自定义实现;可以使用认证策略(AuthenticationStrategy) ,即什么情况下算用户认证通过了;
7. Authorizer:授权器,即访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中的那些功能;
8. Realm:可以有一个或者多个的realm,可以认为是安全实体数据源,即用于获取安全实体的,可以用JDBC实现,也可以是内存实现等等,由用户提供;所以一般在应用中都需要实现自己的realm
9. Session Manager:管理Session生命周期的组件,而Shiro并不仅仅可以用在Web环境,也可以用在普通的Java SE环境中
10. CacheManager:缓存控制器,来管理如用户,角色,权限等缓存的;因为这些数据基本上很少改变,放到缓存中后可以提高访问的性能;
11. Cryptography:密码模块,Shiro提高了一些常见的加密组件用于密码加密,解密等
二、学习第一步,Hello World
1. 代码实践(官网的十分钟入门)
官网文档:http://shiro.apache.org/tutorial.html
官方的quickstart:
https://github.com/apache/shiro/tree/master/samples/quickstart
1).创建一个maven父工程。用于学习Shiro,删掉不必要的东西
2).创建一个普通的Maven子工程: shiro-01-helloworld
3).根据官方文档。我们来导入Shiro的依赖
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.7.1</version>
</dependency>
<!-- configure logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
3).根据官方文档。我们来创建log4j.properties日志文件
在resource下创建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
4).根据官方文档。我们来创建shiro.ini文件
在resource下创建shiro.ini代码如下
IDEA无法读取ini文件,解决方法https://blog.youkuaiyun.com/qq_43521797/article/details/115473267
[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
5).根据官方文档。我们来创建Quickstart类
因为版本问题和官网有一点点区别(两个包路径变了)
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
/*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.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Quickstart {
//日志输出
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
// The easiest way to create a Shiro SecurityManager with configured
// realms, users, roles and permissions is to use the simple INI config.
// We'll do that by using a factory that can ingest a .ini file and
// return a SecurityManager instance:
// Use the shiro.ini file at the root of the classpath
// (file: and url: prefixes load from files and urls respectively):
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
// for this simple example quickstart, make the SecurityManager
// accessible as a JVM singleton. Most applications wouldn't do this
// and instead rely on their container configuration or web.xml for
// webapps. That is outside the scope of this simple quickstart, so
// we'll just do the bare minimum so you can continue to get a feel
// for things.
SecurityUtils.setSecurityManager(securityManager);
// Now that a simple Shiro environment is set up, let's see what you can do:
// get the currently executing user:
//获取当前用户
Subject currentUser = SecurityUtils.getSubject();
// Do some stuff with a Session (no need for a web or EJB container!!!)
//通过当前用户获取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 + "]");
}
// let's login the current user so we can check against roles and permissions:
//判断当前用户是否被认证
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):
//currentUser.getPrincipal()获取你存储的principal
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//权限验证
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!");
}
//注销
currentUser.logout();
System.exit(0);
}
}
重点
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
currentUser.isAuthenticated()
currentUser.getPrincipal()
currentUser.hasRole(“schwartz”)
urrentUser.isPermitted(“lightsaber:wield”)
currentUser.logout();