前言
Realm在Shiro中充当获取应用认证数据或者授权数据的角色,它可以访问像数据库、文件系统等等的数据存储系统。可以把它理解成Shiro的‘DAO’层。
Realm配置
Realm可以在ini配置文件中进行声明式的配置。如下:
fooRealm = com.company.foo.Realm
barRealm = com.company.another.Realm
bazRealm = com.company.baz.Realm
securityManager.realms = $fooRealm, $barRealm, $bazRealm
值得注意的是securityManager.realms中定义了Realm执行的顺序。
Real 授权
AuthenticationTokens
在进行授权的流程中,Shiro最后会通过SecurityManager中的Authenticator 将AuthenticationToken传递给Realm,对Reaml来说认证分成了如下几个主要的步骤。
- Realm会判断传入的AuthenticationToken是否支持认证。
- 检查认证主体的token
- 基于主体查询数据源中用户的相关数据
- 确保token中提供的凭证(经常指密码)和数据源中的匹配
- 如果匹配成功, 返回AuthenticationInfo(用来保存用户的数据)
- 如果匹配失败,抛出AuthenticationException异常
Credentials Matching(凭证配置)
Shiro默认使用的是SimpleCredentialsMatcher,如果想自定义Matcher,可以通过如下方式
Realm myRealm = new com.company.shiro.realm.MyRealm();
CredentialsMatcher customMatcher = new com.company.shiro.realm.CustomCredentialsMatcher();
myRealm.setCredentialsMatcher(customMatcher);
或者是
[main]
...
customMatcher = com.company.shiro.realm.CustomCredentialsMatcher
myRealm = com.company.shiro.realm.MyRealm
myRealm.credentialsMatcher = $customMatcher
...
Realm授权
基于角色的授权
- Subject会委派SecurityManager识别被赋予的角色
- SecurityManager委派Authorizer去检查所有Authorizing Realm是否存在给定的角色。如果没有符合的角色返回false
- 将所有角色赋值给主体
- 如果存在符合的角色,则放行
基于Permission的授权
- Subject委派给SecurityManager最终还是会委派给Authorizer
- Authorizer 通过通过查询Realms来判断是否符合权限
总结,Realm负责Shiro用户的安全数据的查询,并且负责对用户进行最终的认证和授权工作。