Apache Shiro的三个重要概念(二)

218 阅读2分钟

本系列文章目录如下:

  1.  为什么要使用Apache Shiro(一)

  2. Apache Shiro的三个重要概念(二)

  3. Apache Shiro核心功能之Authentication(三)

  4. Apache Shiro核心功能之Authorization(四)

  5. Apache Shiro核心功能之Session Management(五)

  6. Apache Shiro核心功能之Cryptography(六)

  7. Apache Shiro集成

  8. 将Apache Shiro集成到Spring-Boot应用程序中

Shiro中有三个重要的概念分别是Subject,SecurityManeger,Realms

                   

Subject

The word Subject is a security term that basically means "the currently executing user". It's just not called a 'User' because the word 'User' is usually associated with a human being.

指当前与软件交互的东西

获取方式

import org.apache.shiro.subject.Subject;
import org.apache.shiro.SecurityUtils;
...
Subject currentUser = SecurityUtils.getSubject();

SecurityManager

The Subject’s ‘behind the scenes’ counterpart is the SecurityManager. 

  • 在Subject表示当前用户的安全操作,SecurityManager则管理所有用户的安全操作。

  • 它是Shiro体系结构的核心,充当一种“保护伞”对象,引用了许多内部嵌套的安全组件,这些组件形成了一个对象图。

如何构建SecurityManager

它取决于应用环境,几乎每个应用程序都有一个SecurityManager实例。就像Shiro中的几乎所有东西一样,默认的SecurityManager实现是pojo,并且可以用任何与pojo兼容的配置机制进行配置——普通Java代码、Spring XML、YAML、.properties和.ini文件等。 基本上,可以使用任何能够实例化类和调用与javabeans兼容的方法的方法。为此,Shiro通过基于文本的INI配置提供了默认的“common denominator”解决方案

使用INI构建Shiro

[main]
cm = org.apache.shiro.authc.credential.HashedCredentialsMatcher
cm.hashAlgorithm = SHA-512
cm.hashIterations = 1024
# Base64 encoding (less text):
cm.storedCredentialsHexEncoded = false
iniRealm.credentialsMatcher = $cm
[users]
jdoe = TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJpcyByZWFzb2
asmith = IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbXNoZWQsIG5vdCB

加载shiro.ini配置文件

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.util.Factory;

...

//1. Load the INI configuration
Factory<SecurityManager> factory =new IniSecurityManagerFactory("classpath:shiro.ini");
//2. Create the Security
ManagerSecurityManager securityManager = factory.getInstance();
//3. Make it accessible
SecurityUtils.setSecurityManager(securityManager);

Realms

A Realm acts as the ‘bridge’ or ‘connector’ between Shiro and your application’s security data.

Realm在Shiro和你应用的安全数据之间充当了“bridge”和“connector”的作用。

从这个意义上说,Realm本质上是一个限定安全的DAO:它封装了数据源的连接细节,并在需要时让Shiro可以使用相关的数据。 在配置Shiro时,必须指定至少一个用于authentication和/或authorization的Realm。可以配置多个Realm,但至少需要一个。  

shiro提供了开箱即用的Realms连接到安全的数据源(也就是目录),比如LDAP、关系数据库(JDBC)、文本配置源(比如INI和属性文件)等等。你还可以定制你自己的Realms实现去连自定义的数据源。

连接LDAP数据源的realm配置示例

[main]
ldapRealm = org.apache.shiro.realm.ldap.JndiLdapRealm
ldapRealm.userDnTemplate = uid={0},ou=users,dc=mycompany,dc=com
ldapRealm.contextFactory.url = ldap://ldapHost:389
ldapRealm.contextFactory.authenticationMechanism = DIGEST-MD5