Shiro Realm 分析

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

  • 情景一,使用同一个Token
    下面为配置多个Realm时Shiro的处理代码,源码在ModularRealmAuthenticator.class
protected AuthenticationInfo doMultiRealmAuthentication(Collection 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

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

你可能感兴趣的:(Shiro Realm 分析)