美文网首页
5、Shiro认证模块

5、Shiro认证模块

作者: 码农阿川 | 来源:发表于2017-05-15 09:22 被阅读0次

Shiro-Authenticator

Shiro的身份认证器(Authenticator)在应用程序中负责验证用户账户信息,身份认证模块是Shiro的主要模块之一,也是入口API之一。

下面,先看一下Authenticator接口的定义:

public interface Authenticator {

    public AuthenticationInfo authenticate(AuthenticationToken authenticationToken)
            throws AuthenticationException;
}

身份认证器接口的核心方法只有一个,即authenticate方法。

  1. 此方法基于用户提交的AuthenticationToken来验证账户;
  2. 如果验证成功,则返回一个表示Shiro有关账户数据的AuthenticationInfo实例对象,返回的这个对象,通常用来构造一个Subject对象,Subject代表更加完整的安全性视图账户。有关AuthenticationInfo的详细信息请参考:预留
  3. 如果验证失败,通常会抛出一个异常,不同的异常代表了不同的认证失败原因,常见的异常如下:
    1. ExpiredCredentialsException
    2. IncorrectCredentialsException
    3. ExcessiveAttemptsException
    4. LockedAccountException
    5. ConcurrentAccessException
    6. UnknownAccountException

UML 示例

有关AuthenticatorUML示例如下:

Authenticator.uml.png

从类图可以看到,Authenticator的实现主要有两个,一个是ModularRealmAuthenticator,另外一个是SecurityManager。要知道,后者是Shiro的核心控制器,类似Spring MVC中的DispatcherServlet一样。

这里,先不详细讲解SecurityManager相关概念,我们直接来看一下DefaultSecurityManager的认证是如何实现的:

public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
    AuthenticationInfo info;
    try {
        info = authenticate(token);
    } catch (AuthenticationException ae) {
        try {
            onFailedLogin(token, ae, subject);
        } catch (Exception e) {
            if (log.isInfoEnabled()) {
                log.info("onFailedLogin method threw an " +
                        "exception.  Logging and propagating original AuthenticationException.", e);
            }
        }
        throw ae; //propagate
    }

    Subject loggedIn = createSubject(token, info, subject);

    onSuccessfulLogin(token, info, loggedIn);

    return loggedIn;
}
  1. DefaultSecurityManagerlogin方法调用了authenticate方法来进行身份认证。
  2. authenticate方法定义是在父抽象类AuthenticatingSecurityManager中进行定义的。

AuthenticatingSecurityManager

public abstract class AuthenticatingSecurityManager extends RealmSecurityManager {

    /**
     * The internal <code>Authenticator</code> delegate instance that this SecurityManager instance will use
     * to perform all authentication operations.
     */
    private Authenticator authenticator;

    /**
     * Default no-arg constructor that initializes its internal
     * <code>authenticator</code> instance to a
     * {@link org.apache.shiro.authc.pam.ModularRealmAuthenticator ModularRealmAuthenticator}.
     */
    public AuthenticatingSecurityManager() {
        super();
        this.authenticator = new ModularRealmAuthenticator();
    }

    public Authenticator getAuthenticator() {
        return authenticator;
    }

    /**
     * Sets the delegate <code>Authenticator</code> instance that this SecurityManager uses to perform all
     * authentication operations.  Unless overridden by this method, the default instance is a
     * {@link org.apache.shiro.authc.pam.ModularRealmAuthenticator ModularRealmAuthenticator}.
     *
     */
    public void setAuthenticator(Authenticator authenticator) throws IllegalArgumentException {
        if (authenticator == null) {
            String msg = "Authenticator argument cannot be null.";
            throw new IllegalArgumentException(msg);
        }
        this.authenticator = authenticator;
    }


    /**
     * Delegates to the wrapped {@link org.apache.shiro.authc.Authenticator Authenticator} for authentication.
     */
    public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
        return this.authenticator.authenticate(token);
    }
}

可以看到:

  1. SecurityManager并不会自己实现认证功能,而是保持有一个Authenticator代理对象,使用此代理来实现认证验证功能。
  2. SecurityManager默认使用的身份认证器是ModularRealmAuthenticator实例,我们可以通过setAuthenticator方法重新指定一个。默认的指定是在默认构造函数里指定的:
public AuthenticatingSecurityManager() {
        super();
        this.authenticator = new ModularRealmAuthenticator();
    }
  1. 由上述两点及UML类图得出结论,==Shiro中真正实现Authenticator认证器接口的,只有一个实现类:ModularRealmAuthenticatorShiro默认使用此实现来进行身份认证。==

ModularRealmAuthenticator

ModularRealmAuthenticator本质上来讲,也并没有实现真正的认证功能,它保持有Reamls的引用,并把账户查找委托给Realm来实现。而Realms是可插拔的模块化集合,这也使Shiro中的PAM((Pluggable Authentication Module)行为成为可能 。

入口验证方法

protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        assertRealmsConfigured();
        Collection<Realm> realms = getRealms();
        if (realms.size() == 1) {
            return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
        } else {
            return doMultiRealmAuthentication(realms, authenticationToken);
        }
    }
  1. 首先确定Realms已经配置,如果没有配置,则验证失败
  2. 如果配置了1个Reaml,则调用单个Reaml的验证方法,否则调用多个Reaml验证方法。

单个验证方法源码:

protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) {
    if (!realm.supports(token)) {
        String msg = "Realm [" + realm + "] does not support authentication token [" +
                token + "].  Please ensure that the appropriate Realm implementation is " +
                "configured correctly or that the realm accepts AuthenticationTokens of this type.";
        throw new UnsupportedTokenException(msg);
    }
    AuthenticationInfo info = realm.getAuthenticationInfo(token);
    if (info == null) {
        String msg = "Realm [" + realm + "] was unable to find account data for the " +
                "submitted AuthenticationToken [" + token + "].";
        throw new UnknownAccountException(msg);
    }
    return info;
}
  1. 首先确定该Realm是否支持指定的token验证方式,如果不支持,则验证失败。
  2. 调用realmgetAuthenticationInfo方法,获取AuthenticationInfo对象,如果获取为null,则验证失败。
  3. 返回验证成功后的AuthenticationInfo用户信息对象。

多个Reaml验证

protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) {

    AuthenticationStrategy strategy = getAuthenticationStrategy();

    AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token);

    if (log.isTraceEnabled()) {
        log.trace("Iterating through {} realms for PAM authentication", realms.size());
    }

    for (Realm realm : realms) {

        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 throwable) {
                t = throwable;
                if (log.isWarnEnabled()) {
                    String msg = "Realm [" + realm + "] threw an exception during a multi-realm authentication attempt:";
                    log.warn(msg, t);
                }
            }

            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;
}

多个Realm的认证机制涉及到一个策略的问题,Shiro中的认证策略定义接口为:

AuthenticationStrategy认证策略

Shiro中主要有下面几种策略:

  1. AllSuccessfulStrategy: 所有的Reaml都认证成功才算认证成功。
  2. AtLeastOneSuccessfulStrategy: 最少需要一个Realm认证成功才算认证成功,此策略也是ModularRealmAuthenticator的默认策略。
  3. FirstSuccessfulStrategy:第一个Realm认证成功才算成功。

通过阅读策略源码就会发现,实现的方式只要是根据不同策略来决定是否抛出验证异常来实现的策略。有兴趣的可以自己去阅读源码。

到这里,发现关键点又回到了Realm上面,所以接下来要研究一下两块内容:

  1. Authorizer授权模块是如何实现的?
  2. RealmShiro中的默认实现?

相关文章

网友评论

      本文标题:5、Shiro认证模块

      本文链接:https://www.haomeiwen.com/subject/dzwcxxtx.html