---
title: "Shiro User Manual-Realms"
author: "Technoboy"
date: "2013-04-17T11:54:00Z"
tags: []
categories: ["企业架构"]
slug: "shiro-user-manual-realms"
draft: false
lastmod: "2013-04-17T11:56:28Z"
id: 1845377
url: "https://technoboy.iteye.com/blog/1845377"
---

1. Realms
 Realm是可以访问应用系统中数据，例如用户，角色，权限等的组件。Realm将应用系统中的数据转义为Shiro可识别的格式，Shiro就可以提供简单易懂的Subject API。Realms通常有一个一对一的数据源关联，比如关系型数据库，LDAP目录，文件系统或其他类似资源，其实现了Realm接口，并使用指定的数据源API去查找授权数据。一个Realm实质上是和安全相关的DAO。由于大多数数据资源既保存了认证相关的信息，又保存了授权相关的信息，所以每一个Realm都可以执行认证和授权的操作。

2. Realm Configuration
 如果使用INI配置文件，在中定义和引用Realm，以显式和隐式2种方式配置在securityManager里。

2.1 Explicit Assignment(显式配置)
 定义完Realm后，将他们以集合的方式设置到securityManager属性里。

```java

fooRealm = com.company.foo.Realm
barRealm = com.company.another.Realm
bazRealm = com.company.baz.Realm

securityManager.realms = $fooRealm, $barRealm, $bazRealm

```

 显式的配置具有明确性-可以准确的控制使用了哪些realms以及各个realm间调用的顺序。

2.2 Implicit Assignment(隐式配置，不建议使用)
 处于某种原因，你不想显式的配置securityManager.realms属性，可以让Shiro自动检测所有配置的Realm，并装配到securityManager的realms属性里。使用这种方式配置，Realm的调用顺序即为他们定义的顺序：

```java

blahRealm = com.company.blah.Realm
fooRealm = com.company.foo.Realm
barRealm = com.company.another.Realm

# no securityManager.realms assignment here

```

 结果和加上下面这句话是一样的：

```java

securityManager.realms = $blahRealm, $fooRealm, $barRealm

```

 需要注意的是，隐式的配置realm，他们的定义顺序直接影响到他们的调用顺序。如果你改变了定义的顺序，那么也将改变Authenticator的认证顺序。处于这个原因，建议使用显式的定义方式。

3. Realm Authentication
 明白了认证流程后，更应该了解，在认证时，Authenticator是如何与Realm交互的。

3.1 Supporting AuthenticationTokens(token支持)
 在Realm执行认证前，会检查提交的token类型，判断其是否可以处理，如果可以处理，其supports方法会返回true，然后调用getAuthenticationInfo(token)方法。如果无法处理token，supports方法返回false，Realm将不执行认证操作。

3.2 Handling supported AuthenticationTokens(处理支持的token)
 如果Realm支持提交的AuthenticationToken，Authenticator会调用Realm的 getAuthenticationInfo(token)方法，该方法会执行以下逻辑：
 a. 查看token的身份标识
 b. 使用这个标识，到数据源中去查看相应的用户信息。
 c. 确认token中的凭证是否与数据源中存储的匹配。
 d. 如果匹配，返回一个封装了凭证信息的AuthenticationInfo实例。
 e. 如果不匹配，抛出AuthenticationException异常。
 这是getAuthenticationInfo方法最严谨的验证流程。不过，可以在这个方法里做任何操作，比如添加log，更新数据等。唯一需要注意的是，如果凭证和提供的标识匹配，返回一个代表着Subject的非空AuthenticationInfo实例。
 可以通过继承AuthorizingRealm，实现自定义的Realm。

3.3 Credentials Matching(凭证匹配)
 在上面的认证流程中，Realm验证提交凭证是否与数据源中存储的凭证匹配。如果匹配，认证成功，系统就完成了用户身份的验证。验证的过程在所有的系统中大致一样，区别只在于如何进行数据比较。为了保证验证的可移植和可自定义性，AuthenticatingRealm和其子类支持CredentialsMatcher概念。Shiro提供了几个CredentialsMatcher的实现，比如SimpleCredentialsMatcher和HashedCredentialsMatcher。如果想自定义CredentialsMatcher，可以这样做：

```java

Realm myRealm = new com.company.shiro.realm.MyRealm();
CredentialsMatcher customMatcher = new com.company.shiro.realm.CustomCredentialsMatcher();
myRealm.setCredentialsMatcher(customMatcher);

```

 使用INI的配置：

```java

[main]
...
customMatcher = com.company.shiro.realm.CustomCredentialsMatcher
myRealm = com.company.shiro.realm.MyRealm
myRealm.credentialsMatcher = $customMatcher
...

```


3.3.1 Simple Equality Check(相等检查)
 Realm默认实现使用SimpleCredentialsMatcher。它直接拿数据源中存储的凭证和提交的token进行相等比较，支持大部分的字节资源，比如字符串，字符数组，字节数组，文件，流等。

3.3.2 Hashing Credentials(hash凭证)
 比较安全的存储用户凭证的方法是，在存储前进行hash操作。 Shiro提供了HashedCredentialsMatcher支持不同的hash策略。

 a. Hashing and Corresponding Matchers
 Shiro提供了很多HashedCredentialsMatcher实现，只需要在realm中配置即可。比如，使用用户名/密码进行认证，使用SHA-256算法进行密码加密:

```java

import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
...

//We'll use a Random Number Generator to generate salts.  This
//is much more secure than using a username as a salt or not
//having a salt at all.  Shiro makes this easy.
//
//Note that a normal app would reference an attribute rather
//than create a new RNG every time:
RandomNumberGenerator rng = new SecureRandomNumberGenerator();
Object salt = rng.nextBytes();

//Now hash the plain-text password with the random salt and multiple
//iterations and then Base64-encode the value (requires less space than Hex):
String hashedPasswordBase64 = new Sha256Hash(plainTextPassword, salt, 1024).toBase64();

User user = new User(username, hashedPasswordBase64);
//save the salt with the new account.  The HashedCredentialsMatcher
//will need it later when handling login attempts:
user.setPasswordSalt(salt);
userDAO.create(user);

```

由于使用了SHA-256算法hash密码，需要告诉Shiro使用对应的HashedCredentialsMatcher。例子中，我们使用随机盐值和1024的hash迭代，那么需要在INI配置中：

```java

[main]
...
credentialsMatcher = org.apache.shiro.authc.credential.Sha256CredentialsMatcher
# base64 encoding, not hex in this example:
credentialsMatcher.storedCredentialsHexEncoded = false
credentialsMatcher.hashIterations = 1024
# This next property is only needed in Shiro 1.0.  Remove it in 1.1 and later:
credentialsMatcher.hashSalted = true

...
myRealm = com.company.....
myRealm.credentialsMatcher = $credentialsMatcher
...

```

 b. SaltedAuthenticationInfo
 最后，Realm的返回值需要是SaltedAuthenticationInfo类型，而非AuthenticationInfo。