Shiro Realm 分析

在Shirio中Realm所做的事就是提供自定义的用户认证、角色和权限分配。
如果实现了多个Realm用来认证,我们必须保证至少有一个Realm认证是通过的否者会抛出AuthenticationException

  • 情景一,使用同一个Token
    下面为配置多个Realm时Shiro的处理代码,源码在ModularRealmAuthenticator.class
protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) {
        AuthenticationStrategy strategy = this.getAuthenticationStrategy();
        AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token);
        if (log.isTraceEnabled()) {
            log.trace("Iterating through {} realms for PAM authentication", realms.size());
        }

        Iterator var5 = realms.iterator();

        while(var5.hasNext()) {
            Realm realm = (Realm)var5.next();
            aggregate = strategy.beforeAttempt(realm, token, aggregate);
            if (realm.supports(token)) {
                log.trace("Attempting to authenticate token [{}] using realm [{}]", token, realm);
                AuthenticationInfo info = null;
                Throwable t = null;

                try {
                    info = realm.getAuthenticationInfo(token);
                } catch (Throwable var11) {
                    t = var11;
                    if (log.isWarnEnabled()) {
                        String msg = "Realm [" + realm + "] threw an exception during a multi-realm authentication attempt:";
                        log.warn(msg, var11);
                    }
                }

                aggregate = strategy.afterAttempt(realm, token, info, aggregate, t);
            } else {
                log.debug("Realm [{}] does not support token {}.  Skipping realm.", realm, token);
            }
        }

        aggregate = strategy.afterAllAttempts(token, aggregate);
        return aggregate;
    }

在遍历完Realms后,会调用如下的代码判断是否有认证成功的Realm。如果没有,就会抛出AuthenticationException

aggregate = strategy.afterAllAttempts(token, aggregate);

#默认调用AtLeastOneSuccessfulStrategy类的afterAllAttempts(AuthenticationToken token, AuthenticationInfo aggregate)方法
public AuthenticationInfo afterAllAttempts(AuthenticationToken token, AuthenticationInfo aggregate) throws AuthenticationException {
        if (aggregate != null && !CollectionUtils.isEmpty(aggregate.getPrincipals())) {
            return aggregate;
        } else {
            throw new AuthenticationException("Authentication token of type [" + token.getClass() + "] could not be authenticated by any configured realms.  Please ensure that at least one realm can authenticate these tokens.");
        }
    }
  • 情景二,使用不同的Realm使用不同的Token。
    如果不特殊处理,则会抛出不支持的Token异常
#这里会校验当前Realm是否支持这中Token
if (realm.supports(token)) {
....
}

下面为realm.suppots()的源码,在AuthenticatingRealm.class中

public boolean supports(AuthenticationToken token) {
        return token != null && this.getAuthenticationTokenClass().isAssignableFrom(token.getClass());
    }

解决办法:
在自定义Reamls中手动设置Token类型AuthenticationToken。这样无论什么样的Token都是可以支持,以下类继承AuthorizingRealm

public MyRealm() {
        super();
        setAuthenticationTokenClass(AuthenticationToken.class);
    }

在遍历完Realms后,会调用如下的代码判断是否有认证成功的Realm。如果没有,就会抛出AuthenticationException

aggregate = strategy.afterAllAttempts(token, aggregate);

#默认调用AtLeastOneSuccessfulStrategy类的afterAllAttempts(AuthenticationToken token, AuthenticationInfo aggregate)方法
public AuthenticationInfo afterAllAttempts(AuthenticationToken token, AuthenticationInfo aggregate) throws AuthenticationException {
        if (aggregate != null && !CollectionUtils.isEmpty(aggregate.getPrincipals())) {
            return aggregate;
        } else {
            throw new AuthenticationException("Authentication token of type [" + token.getClass() + "] could not be authenticated by any configured realms.  Please ensure that at least one realm can authenticate these tokens.");
        }
    }
  • 总结
    实现多个Realm必须要保证至少一个能认证通过,否者抛出的AuthenticationException异常。在捕获login(token)时,无法得到具体的错误信息。也就不能准确的知道是用户不存在或则是用户名密码错误。

  • 建议
    使用一个Realm验证,通过继承UsernamePasswordToken类拓展,增加额外的变量来实现多种认证方式。

参考资料:
http://shiro.apache.org/realm.html
https://nutz.cn/yvr/t/59tufi5mjijado7thspa9pbqvp

不足之处,欢迎留言指出。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 文章转载自:http://blog.csdn.net/w1196726224/article/details/53...
    wangzaiplus阅读 3,421评论 0 3
  • 前言 上一章主要对Shiro功能,运行原理,架构设计进行了介绍,这一章我们主要学习Shiro的身份验证。本章的代码...
    卑微幻想家阅读 2,096评论 0 12
  • 跨平台:现在很多应用都是要兼顾iOS和Android两个平台同时开发。如果两个平台都能使用相同的数据库,那就不用考...
    CoderZS阅读 2,575评论 2 16
  • 《疑似风月》意犹未尽,继续来叨叨几句。 现在很多人都陷入了一个怪圈,平时忙着攒钱,攒够了钱就去旅行,然后在嘈杂声中...
    篱落疏疏阅读 213评论 0 0