shiro-Realm解读

realm作为shiro框架的三个核心之一,是一个安全数据源,用于获取用户的身份认证、授权等信息,shiro框架不了解用户的身份认证策略、权限管理方式等是如何实现的、存储在哪里,由用户自己去完成这个部分。

shiro-realm继承关系图
在这里插入图片描述

Realm

是一个接口,包含三个方法。总的来说,一个realm至少需要包含这个三个方法:

  1. String getName() 获取唯一的realm名称
  2. boolean supports(AuthenticationToken token); 声明realm支持何种类型的token
  3. 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(带缓存的实现)。
子类:

  1. 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项目里应该比较常见,将用户的身份信息、权限信息都存储在数据库中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值