七、ModularRealmAuthenticator 的源码分析和配置

                       ModularRealmAuthenticator 的源码分析和配置

SecurityManager得到token信息后,通过调用authenticator.authenticate(token)方法,把身份验证委托给内置的Authenticator的实例进行验证。authenticator通常是ModularRealmAuthenticator
实例,支持对一个或多个Realm实例进行适配。ModularRealmAuthenticator提供了一种可插拔的认证风格,你可以在此处插入自定义Realm实现。

如果配置了多个Realm,ModularRealmAuthenticator会根据配置的AuthenticationStrategy(身份验证策略)进行多Realm认证过程。
注:如果应用程序中仅配置了一个Realm,Realm将被直接调用而无需再配置认证策略。

判断每个Realm是否支持提交的token,如果支持Realm就会调用getAuthenticationInfo(token)方法进行认证处理。
AuthenticationStrategy(身份验证策略)会在后边讲解

在这里插入图片描述
public abstract class AbstractAuthenticator implements Authenticator, LogoutAware {
 
public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {

    if (token == null) {
        throw new IllegalArgumentException("Method argument (authentication token) cannot be null.");
    }

    log.trace("Authentication attempt received for token [{}]", token);

    AuthenticationInfo info;
    try {
    *// 调用 ModularRealmAuthenticator。 doAuthenticate(token) 方法*
        info = doAuthenticate(token);
        if (info == null) {
            String msg = "No account information found for authentication token [" + token + "] by this " +
                    "Authenticator instance.  Please check that it is configured correctly.";
            throw new AuthenticationException(msg);
        }
    } catch (Throwable t) {
        AuthenticationException ae = null;
        if (t instanceof AuthenticationException) {
            ae = (AuthenticationException) t;
        }
        if (ae == null) {
            //Exception thrown was not an expected AuthenticationException.  Therefore it is probably a little more
            //severe or unexpected.  So, wrap in an AuthenticationException, log to warn, and propagate:
            String msg = "Authentication failed for token submission [" + token + "].  Possible unexpected " +
                    "error? (Typical or expected login exceptions should extend from AuthenticationException).";
            ae = new AuthenticationException(msg, t);
            if (log.isWarnEnabled())
                log.warn(msg, t);
        }
        try {
            notifyFailure(token, ae);
        } catch (Throwable t2) {
            if (log.isWarnEnabled()) {
                String msg = "Unable to send notification for failed authentication attempt - listener error?.  " +
                        "Please check your AuthenticationListener implementation(s).  Logging sending exception " +
                        "and propagating original AuthenticationException instead...";
                log.warn(msg, t2);
            }
        }


        throw ae;
    }

    log.debug("Authentication successful for token [{}].  Returned account [{}]", token, info);

    notifySuccess(token, info);

    return info;
}
 
protected abstract AuthenticationInfo doAuthenticate(AuthenticationToken token)
        throws AuthenticationException;
 
 
 
}

ModularRealmAuthenticator 源码分析

public class ModularRealmAuthenticator extends AbstractAuthenticator {
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
    assertRealmsConfigured();
    Collection realms = getRealms();
    if (realms.size() == 1) {
        return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
    } else {
        return doMultiRealmAuthentication(realms, authenticationToken);
    }
}
}
在这里插入图片描述
①当realm==1的时候
public class ModularRealmAuthenticator extends AbstractAuthenticator {
 
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);
    }
    // 去调用自定义realm 中的认证方法
    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;
}
 }

当realm个数大于1 的时候 realms!=1 这里会涉及到>AuthenticationStrategy(身份验证策略)
根据策略进行认证结果

public class ModularRealmAuthenticator extends AbstractAuthenticator {
 
protected AuthenticationInfo doMultiRealmAuthentication(Collection 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.isDebugEnabled()) {
                    String msg = "Realm [" + realm + "] threw an exception during a multi-realm authentication attempt:";
                    log.debug(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 中的认证方法
AuthenticationInfo info = realm.getAuthenticationInfo(token);
多realm 就是for循环调用 getAuthenticationInfo(token);

public class MyRealm extends AuthorizingRealm {
//public class MyRealm extends AuthenticatingRealm {
 
 
/**
 * 认证
 *
 * @param token
 * @return
 * @throws AuthenticationException
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
    String username = usernamePasswordToken.getUsername();
    String password = String.valueOf(usernamePasswordToken.getPassword());

    ByteSource solt = ByteSource.Util.bytes(username);

    if (username.equals("username") && password.equals("password")) {
        return new SimpleAuthenticationInfo(username, password, getName());
    }
    return null;
}
}

进行密码比较

 public abstract class AuthenticatingRealm extends CachingRealm implements Initializable {
 
protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {
    CredentialsMatcher cm = getCredentialsMatcher();
    if (cm != null) {
        if (!cm.doCredentialsMatch(token, info)) {
            //not successful - throw an exception to indicate this:
            String msg = "Submitted credentials for token [" + token + "] did not match the expected credentials.";
            throw new IncorrectCredentialsException(msg);
        }
    } else {
        throw new AuthenticationException("A CredentialsMatcher must be configured in order to verify " +
                "credentials during authentication.  If you do not wish for credentials to be examined, you " +
                "can configure an " + AllowAllCredentialsMatcher.class.getName() + " instance.");
    }
}
 
}

你可能感兴趣的:(七、ModularRealmAuthenticator 的源码分析和配置)