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
今天看了教程的第三章...是关于授权的......和以前一样.....自己也研究了下....我觉得看那篇教程怎么说呢.....总体上是为数不多的精品教程了吧....但是有些地方确实是讲的太少了.... ...
随机推荐
- Windows动态库的使用 part one
二.动态库程序 这篇写得比较乱,看不懂的可以跳part 2,直接上图片的. 动态库的使用: 4.3.1 隐式链接 动态库的隐式连接,需要动态库的 动态库文件".dll" , 动 ...
- [Buzz Today]2013.08.18
# Go 语言实现memcached:groupcache memcached作者Brad Fitzpatrick用Go语言重新实现了memcached. groupcache继承了memcached ...
- 【vijos】1769 网络的关键边(割边)
https://vijos.org/p/1769 啊,割边写挫了害得我交了那么多发... 本题多想想就出来了.. 首先求出割边,显然关键边就在割边上. 求完割边后,我们先从一个点dfs,维护A的点数和 ...
- ARM汇编语言(3)(寄存器读写控制外设)
DAY4:ARM汇编(4) 一,GPIO编程 连接内存(二级cache),用来寻址:连接外设,用来控制: 1,GPIO,General-Purpose IO ports,通用输入输出端口, ...
- 蓝桥杯 第四届C/C++预赛真题(5) 前缀判断(水题)
题目标题:前缀判断 如下的代码判断 needle_start指向的串是否为haystack_start指向的串的前缀,如不是,则返回NULL. 比如:"abcd1234" 就包含了 ...
- RPolar项目进度记录
PolarMesDlg.cpp,中的 void PolarMesDlg::CImage2CImagedata(unsigned char* src,CImage* desimg,unsigned ch ...
- 马普尔小姐探案集S02E03【熙阳岭的疑云】
--Why the husband love his wife so much? --Because she was the last one in their family.
- EntityFramework增删改查
http://www.cnblogs.com/libingql/archive/2013/01/29/2881988.html
- JZOJ.5280【NOIP2017模拟8.15】膜法师
Description
- jpa双向一对一关联外键映射
项目结构: Wife package auth.model; import javax.persistence.CascadeType; import javax.persistence.Column ...