Shiro理解与总结
Feature
Apache Shiro is a comprehensive application security framework with many features. The following diagram shows where Shiro focuses its energy, and this reference manual will be organized similarly:
Shiro targets what the Shiro development team calls “the four cornerstones of application security” - Authentication, Authorization, Session Management, and Cryptography:
Authentication: Sometimes referred to as ‘login’, this is the act of proving a user is who they say they are.
Authorization: The process of access control, i.e. determining ‘who’ has access to ‘what’.
Session Management: Managing user-specific sessions, even in non-web or EJB applications.
Cryptography: Keeping data secure using cryptographic algorithms while still being easy to use.
There are also additional features to support and reinforce these concerns in different application environments, especially:
- Web Support: Shiro’s web support APIs help easily secure web applications.
- Caching: Caching is a first-tier citizen in Apache Shiro’s API to ensure that security operations remain fast and efficient.
- Concurrency: Apache Shiro supports multi-threaded applications with its concurrency features.
- Testing: Test support exists to help you write unit and integration tests and ensure your code will be secured as expected.
- “Run As”: A feature that allows users to assume the identity of another user (if they are allowed), sometimes useful in administrative scenarios.
- “Remember Me”: Remember users’ identities across sessions so they only need to log in when mandatory.
Architecture
Subject (
org.apache.shiro.subject.Subject
)
A security-specific ‘view’ of the entity (user, 3rd-party service, cron job, etc) currently interacting with the software.SecurityManager (org.apache.shiro.mgt.SecurityManager)
As mentioned above, theSecurityManager
is the heart of Shiro’s architecture. It is mostly an ‘umbrella’ object that coordinates its managed components to ensure they work smoothly together. It also manages Shiro’s view of every application user, so it knows how to perform security operations per user.Authenticator (org.apache.shiro.authc.Authenticator)
TheAuthenticator
is the component that is responsible for executing and reacting to authentication (log-in) attempts by users. When a user tries to log-in, that logic is executed by theAuthenticator
. TheAuthenticator
knows how to coordinate with one or moreRealms
that store relevant user/account information. The data obtained from theseRealms
is used to verify the user’s identity to guarantee the user really is who they say they are.Authentication Strategy (org.apache.shiro.authc.pam.AuthenticationStrategy)
If more than oneRealm
is configured, theAuthenticationStrategy
will coordinate the Realms to determine the conditions under which an authentication attempt succeeds or fails (for example, if one realm succeeds but others fail, is the attempt successful? Must all realms succeed? Only the first?).
Authorizer (org.apache.shiro.authz.Authorizer)
TheAuthorizer
is the component responsible determining users’ access control in the application. It is the mechanism that ultimately says if a user is allowed to do something or not. Like theAuthenticator
, theAuthorizer
also knows how to coordinate with multiple back-end data sources to access role and permission information. TheAuthorizer
uses this information to determine exactly if a user is allowed to perform a given action.SessionManager (org.apache.shiro.session.mgt.SessionManager)
TheSessionManager
knows how to create and manage userSession
lifecycles to provide a robust Session experience for users in all environments. This is a unique feature in the world of security frameworks - Shiro has the ability to natively manage user Sessions in any environment, even if there is no Web/Servlet or EJB container available. By default, Shiro will use an existing session mechanism if available, (e.g. Servlet Container), but if there isn’t one, such as in a standalone application or non-web environment, it will use its built-in enterprise session management to offer the same programming experience. TheSessionDAO
exists to allow any datasource to be used to persist sessions.SessionDAO (org.apache.shiro.session.mgt.eis.SessionDAO)
TheSessionDAO
performsSession
persistence (CRUD) operations on behalf of theSessionManager
. This allows any data store to be plugged in to the Session Management infrastructure.
CacheManager (org.apache.shiro.cache.CacheManager)
TheCacheManager
creates and managesCache
instance lifecycles used by other Shiro components. Because Shiro can access many back-end data sources for authentication, authorization and session management, caching has always been a first-class architectural feature in the framework to improve performance while using these data sources. Any of the modern open-source and/or enterprise caching products can be plugged in to Shiro to provide a fast and efficient user-experience.Cryptography (org.apache.shiro.crypto.*)
Cryptography is a natural addition to an enterprise security framework. Shiro’scrypto
package contains easy-to-use and understand representations of crytographic Ciphers, Hashes (aka digests) and different codec implementations. All of the classes in this package are carefully designed to be very easy to use and easy to understand. Anyone who has used Java’s native cryptography support knows it can be a challenging animal to tame. Shiro’s crypto APIs simplify the complicated Java mechanisms and make cryptography easy to use for normal mortal human beings.Realms (org.apache.shiro.realm.Realm)
As mentioned above, Realms act as the ‘bridge’ or ‘connector’ between Shiro and your application’s security data. When it comes time to actually interact with security-related data like user accounts to perform authentication (login) and authorization (access control), Shiro looks up many of these things from one or more Realms configured for an application. You can configure as manyRealms
as you need (usually one per data source) and Shiro will coordinate with them as necessary for both authentication and authorization.
Shiro example
java:
package com.hjp.shiro.shiro_tutorial; 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) {
log.info("My First Apache Shiro Application"); Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager); // 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 = 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()) {
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:weild")) {
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); } }
pom:
<?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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>org.apache.shiro.tutorials</groupId>
<artifactId>shiro-tutorial</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>First Apache Shiro Application</name>
<packaging>jar</packaging> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.5</source>
<target>1.5</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin> <!-- This plugin is only to test run our little application. It is not
needed in most Shiro-enabled applications: -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<classpathScope>test</classpathScope>
<mainClass>Tutorial</mainClass>
</configuration>
</plugin>
</plugins>
</build> <dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.1.0</version>
</dependency>
<!-- Shiro uses SLF4J for logging. We'll use the 'simple' binding in this
example app. See http://www.slf4j.org for more info. -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.4</version>
</dependency> </dependencies> </project>
output:
0 [main] INFO com.hjp.shiro.shiro_tutorial.Tutorial - My First Apache Shiro Application
26582 [main] INFO org.apache.shiro.session.mgt.AbstractValidatingSessionManager - Enabling session validation scheduler...
44789 [main] INFO com.hjp.shiro.shiro_tutorial.Tutorial - Retrieved the correct value! [aValue]
80397 [main] INFO com.hjp.shiro.shiro_tutorial.Tutorial - User [lonestarr] logged in successfully.
85201 [main] INFO com.hjp.shiro.shiro_tutorial.Tutorial - May the Schwartz be with you!
90551 [main] INFO com.hjp.shiro.shiro_tutorial.Tutorial - You may use a lightsaber ring. Use it wisely.
95185 [main] INFO com.hjp.shiro.shiro_tutorial.Tutorial - You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. Here are the keys - have fun!
Refer
http://shiro.apache.org/architecture.html
Shiro理解与总结的更多相关文章
- SpringBoot集成Apache Shiro
笔者因为项目转型的原因,对Apache Shiro安全框架做了一点研究工作,故想写点东西以便将来查阅.之所以选择Shiro也是看了很多人的推荐,号称功能丰富强大,而且易于使用.实践下来的确如大多数人所 ...
- shiro的原理理解
1.shiro原理图如下: 框架解释: subject:主体,可以是用户也可以是程序,主体要访问系统,系统需要对主体进行认证.授权. securityManager:安全管理器,主体进行认证和授权都 ...
- shiro登录验证简单理解
这两天接手了下师兄的项目,要给系统加个日志管理模块,其中需要记录登录功能的日志,那么首先要知道系统的登录是在哪里实现验证的. 该系统把所有登录验证还有权限控制的工作都交给了shiro. 这篇文章就先简 ...
- shiro real的理解,密码匹配等
1 .定义实体及关系 即用户-角色之间是多对多关系,角色-权限之间是多对多关系:且用户和权限之间通过角色建立关系:在系统中验证时通过权限验证,角色只是权限集合,即所谓的显示角色:其实权限应该对应到资源 ...
- shiro+jwt+springboot理解
转自 https://www.cnblogs.com/fengli9998/p/6676783.html https://www.jianshu.com/p/0366a1675bb6 https:// ...
- shiro实现session共享
session共享:在多应用系统中,如果使用了负载均衡,用户的请求会被分发到不同的应用中,A应用中的session数据在B应用中是获取不到的,就会带来共享的问题. 假设:用户第一次访问,连接的A服务器 ...
- Shiro安全框架入门篇(登录验证实例详解与源码)
转载自http://blog.csdn.net/u013142781 一.Shiro框架简单介绍 Apache Shiro是Java的一个安全框架,旨在简化身份验证和授权.Shiro在JavaSE和J ...
- Apache Shiro 学习记录5
本来这篇文章是想写从Factory加载ini配置到生成securityManager的过程的....但是貌似涉及的东西有点多...我学的又比较慢...很多类都来不及研究,我又怕等我后面的研究了前面的都 ...
- Apache Shiro 学习记录4
今天看了教程的第三章...是关于授权的......和以前一样.....自己也研究了下....我觉得看那篇教程怎么说呢.....总体上是为数不多的精品教程了吧....但是有些地方确实是讲的太少了.... ...
随机推荐
- spring 的redis操作类RedisTemplate
spring 集成的redis操作几乎都在RedisTemplate内了. 已spring boot为例, 再properties属性文件内配置好 redis的参数 spring.redis.host ...
- Python 使用标准库根据进程名获取进程PID
应用场景 在进行 Linux 运维的环境中,我们经常会遇到维护同一台服务器上的多个程序,涉及到程序的启动.关闭和重启操作. 通常这些程序之间存在着相互依存的关系需要进行依次的启动关闭操作. 下面介绍几 ...
- HTML 文档的基本结构
HTML文件是什么? q HTML表示超文本标记语言(Hyper Text Markup Language). q HTML文件是一个包含标记的文本文件. q 这些标记保速浏览器怎样显示这个页面 ...
- c# 可变数目参数params实例
一般来说,参数个数都是固定的,定义为集群类型的参数可以实现可变数目参数的目的,但是.NET提供了更灵活的机制来实现可变数目参数,这就是使用params修饰符 一般来说,参数个数都是固定的,定义为集群类 ...
- uva 10494 - If We Were a Child Again 大数除法和取余
uva 10494 - If We Were a Child Again If We Were a Child Again Input: standard inputOutput: standard ...
- c++11小计
[capture] (parameters) mutable -> return-type { statement } " (parameters)" 和 "-&g ...
- AngularJS bind
闲着无聊怕手生 小练习 <!DOCTYPE html><html><head><meta charset="utf-8"><s ...
- Linux各文件颜色的含义
Linux系统中文件有多种颜色,不同颜色文件代表不同类型的文件,具体如下: 蓝色:目录 绿色:可执行文件 红色:压缩文件 浅蓝色:链接文件 白色:普通文件 黄色:设备文件
- iOS xcode6.0使用7.1运行程序 iphone5上下有黑条
转自:http://stackoverflow.com/questions/25817562/black-bars-appear-in-app-when-targeting-ios7-1-or-7-0 ...
- 『浅入深出』MySQL 中事务的实现
在关系型数据库中,事务的重要性不言而喻,只要对数据库稍有了解的人都知道事务具有 ACID 四个基本属性,而我们不知道的可能就是数据库是如何实现这四个属性的:在这篇文章中,我们将对事务的实现进行分析,尝 ...