AbstractAuthenticationStrategy抽象类源码解析

AbstractAuthenticationStrategy抽象类主要是用来定义认证策略的,它实现了AuthenticationStrategy认证策略接口,先对其解析如下:

1.AuthenticationStrategy接口

主要是定义了一些认证时的公共的方法,例如beforeAllAttempts(所有认证前做的操作),beforeAttempt(某一个realm认证前做的操作),afterAttempt(某一个realm认证后做的操作),afterAllAttempts(所有认证后做的操作)。

2.AbstractAuthenticationStrategy抽象类

2.1.所有认证前做的操作(返回一个新建的SimpleAuthenticationInfo信息,实现了AuthenticationStrategy接口的方法)

public AuthenticationInfo beforeAllAttempts(Collection<? extends Realm> realms, AuthenticationToken token) throws AuthenticationException {
        return new SimpleAuthenticationInfo();
}

2.2.某一个realm认证前做的操作(返回此时的认证信息,实现了AuthenticationStrategy接口的方法)

public AuthenticationInfo beforeAttempt(Realm realm, AuthenticationToken token, AuthenticationInfo aggregate) throws AuthenticationException {
        return aggregate;
}

2.3.某一个realm认证后做的操作(如果当前realm认证后得到的认证信息不存在,则返回之前的认证信息;如果当前realm认证后得到的认证信息存在,但是之前的认证信息不存在,则返回当前的认证信息;如果当前realm认证后得到的认证信息和之前的认证信息都存在,则返回合并后的认证信息,实现了AuthenticationStrategy接口的方法)

public AuthenticationInfo afterAttempt(Realm realm, AuthenticationToken token, AuthenticationInfo singleRealmInfo, AuthenticationInfo aggregateInfo, Throwable t) throws AuthenticationException {
        AuthenticationInfo info;
        if (singleRealmInfo == null) {
            info = aggregateInfo;
        } else {
            if (aggregateInfo == null) {
                info = singleRealmInfo;
            } else {
                info = merge(singleRealmInfo, aggregateInfo);
            }
        }

        return info;
    }

2.4.合并当前realm认证的认证信息和之前的认证信息,并返回合并后的认证信息

protected AuthenticationInfo merge(AuthenticationInfo info, AuthenticationInfo aggregate) {
        if( aggregate instanceof MergableAuthenticationInfo ) {
            ((MergableAuthenticationInfo)aggregate).merge(info);
            return aggregate;
        } else {
            throw new IllegalArgumentException( "Attempt to merge authentication info from multiple realms, but aggregate " +
                      "AuthenticationInfo is not of type MergableAuthenticationInfo." );
        }
    }

2.5.所有的认证通过后,返回最终的认证信息

public AuthenticationInfo afterAllAttempts(AuthenticationToken token, AuthenticationInfo aggregate) throws AuthenticationException {
        return aggregate;
    }

相关推荐