5、Shiro认证模块

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中的默认实现?
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,744评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,505评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,105评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,242评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,269评论 6 389
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,215评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,096评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,939评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,354评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,573评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,745评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,448评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,048评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,683评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,838评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,776评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,652评论 2 354

推荐阅读更多精彩内容