realm作为shiro框架的三个核心之一,是一个安全数据源,用于获取用户的身份认证、授权等信息,shiro框架不了解用户的身份认证策略、权限管理方式等是如何实现的、存储在哪里,由用户自己去完成这个部分。
shiro-realm继承关系图
Realm
是一个接口,包含三个方法。总的来说,一个realm至少需要包含这个三个方法:
- String getName() 获取唯一的realm名称
- boolean supports(AuthenticationToken token); 声明realm支持何种类型的token
- AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) 对于支持的token,返回何种身份认证信息
再看一下源码:
/** 返回realm的名字,这个名字在应用中应该是唯一的。
* Returns the (application-unique) name assigned to this <code>Realm</code>. All realms configured for a single
* application must have a unique name.
*
* @return the (application-unique) name assigned to this <code>Realm</code>.
*/
String getName();
/** 表明这个realm支持哪种类型的token,入参是AuthenticationToken,返回值为bool
如果realm不支持某种类型的token,那么相应的 AuthenticationInfo getAuthenticationInfo(AuthenticationToken token)方法也不会被调用,也就无法获取相应的认证信息。
* Returns <tt>true</tt> if this realm wishes to authenticate the Subject represented by the given
* {@link org.apache.shiro.authc.AuthenticationToken AuthenticationToken} instance, <tt>false</tt> otherwise.
*
* <p>If this method returns <tt>false</tt>, it will not be called to authenticate the Subject represented by
* the token - more specifically, a <tt>false</tt> return value means this Realm instance's
* {@link #getAuthenticationInfo} method will not be invoked for that token.
*
* @param token the AuthenticationToken submitted for the authentication attempt
* @return <tt>true</tt> if this realm can/will authenticate Subjects represented by specified token,
* <tt>false</tt> otherwise.
*/
boolean supports(AuthenticationToken token);
//这个方法是获取某种token对应的认证信息
AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;
使用:
1.一般继承AuthorizingRealm即可,其继承了AuthenticatingRealm(授权),间接继承了CachingRealm(带缓存的实现)。
子类:
- SimpleAccountRealm
包含了两个map表示的属性,包含身份认证信息(users)和角色信息(roles)。除此之外这里使用了读写锁,保证线程安全。
public class SimpleAccountRealm extends AuthorizingRealm {
//TODO - complete JavaDoc
protected final Map<String, SimpleAccount> users; //username-to-SimpleAccount
protected final Map<String, SimpleRole> roles; //roleName-to-SimpleRole
protected final ReadWriteLock USERS_LOCK;
protected final ReadWriteLock ROLES_LOCK;
之前使用的ini文件来配置realm,IniRealm,是SimpleAccountRealm的子类,允许用户以ini文件形式配置realm。除此之外还支持PropertiesRealm,使用.properties文件来配置.
2.JDBCRealm
这个在web项目里应该比较常见,将用户的身份信息、权限信息都存储在数据库中。