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
今天看了教程的第三章...是关于授权的......和以前一样.....自己也研究了下....我觉得看那篇教程怎么说呢.....总体上是为数不多的精品教程了吧....但是有些地方确实是讲的太少了.... ...
随机推荐
- 【BZOJ】3296: [USACO2011 Open] Learning Languages(tarjan)
http://www.lydsy.com/JudgeOnline/problem.php?id=3296 显然,每群能交流的群是个强联通块 然后求出scc的数量,答案就是scc-1 #include ...
- EEPlat的基于浏览器的在线开发技术
EEPlat的开发内容主要包含配置开发和基于API的扩展开发两块内容. EEPlat的配置开发基于后台的配置环境.直接通过界面操作配置就可以. EEPlat的配置平台是用EEPlat自解释构建的.本身 ...
- 蓝桥杯 第三届C/C++预赛真题(2) 古堡算式(数学题)
福尔摩斯到某古堡探险,看到门上写着一个奇怪的算式: ABCDE * ? = EDCBA 他对华生说:“ABCDE应该代表不同的数字,问号也代表某个数字!” 华生:“我猜也是!” 于是,两人沉默了好久, ...
- 【统计分析】ROC曲线
http://baike.baidu.com/link?url=O8nVf39qW4UpYAegk9cJfYARCFDg8YHQ6p5wFnWxYvo151doXo-WvG5Rfz0j4R-r 受试者 ...
- flask-第三方组件
flask-script 离线脚本 from flask_demo import create_app from flask_script import Manager app = create_a ...
- storyboard设置navigation controller
到storyboard选中我们唯一一个的viewcontroller,找到xcode的菜单栏,Edit->Embed In->NavigationController.这时候storybo ...
- 并发编程8 线程的创建&验证线程之间数据共享&守护线程&线程进程效率对比&锁(死锁/递归锁)
1.线程理论以及线程的两种创建方法 2.线程之间是数据共享的与join方法 3.多线程和多进程的效率对比 4.数据共享的补充线程开启太快 5.线程锁 互斥锁 同步锁 6.死锁现象和递归锁 7.守护线程 ...
- grep、egrep命令用法
何谓正则表达式 正则表达式,又称正规表示法.常规表示法(Regular Expression,在代码中常简写为regex.regexp或RE),是一类字符所书写的模式,其中许多字符不表示其字面意义,而 ...
- C# WinForm 中进行UrlEncode
public static string ToUrlEncode(string strCode) { StringBuilder sb = new StringBuilder(); byte[] by ...
- cocopods
一.什么是CocoaPods 1.为什么需要CocoaPods 在进行iOS开发的时候,总免不了使用第三方的开源库,比如SBJson.AFNetworking.Reachability等等.使用这些库 ...