鲁春利的工作笔记,好记性不如烂笔头



subject.login(token);


  • DelegatingSubject类的login方法

package org.apache.shiro.subject.support;

public class DelegatingSubject implements Subject {

    protected PrincipalCollection principals;
    protected boolean authenticated;
    protected String host;
    protected Session session;

    public void login(AuthenticationToken token) throws AuthenticationException {
        // 清除RunAs的身份信息
        clearRunAsIdentitiesInternal();
        /* 通过securityManager实现真正的登录,并返回登录之后的主体(subject)数据 */
        Subject subject = securityManager.login(this, token);

        PrincipalCollection principals;

        // 通过subject获取身份信息,略
        
        this.principals = principals;
        this.authenticated = true;
        // 部分代码略
    }

    public boolean isAuthenticated() {
        return authenticated;
    }
}


  • DefaultSecurityManager类的login方法

Apache Shiro学习笔记(二)身份验证subject.login过程_Login

package org.apache.shiro.mgt;

public class DefaultSecurityManager extends SessionsSecurityManager {
    
    /**
     * 如果登录失败会抛出异常,如果成功会返回代表身份信息的subject
     */
    public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
        AuthenticationInfo info;
        try {
            info = authenticate(token);
        } catch (AuthenticationException ae) {
            // 认证失败,抛出异常
        }

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

        onSuccessfulLogin(token, info, loggedIn);

        return loggedIn;
    }
}


  • AuthenticatingSecurityManager类的authenticate(token)方法

Apache Shiro学习笔记(二)身份验证subject.login过程_Apache_02

package org.apache.shiro.mgt;

public abstract class AuthenticatingSecurityManager extends RealmSecurityManager {
    // org.apache.shiro.authc.Authenticator的职责是验证用户帐号,
    // 是Shiro API中身份验证核心的入口点:就一个authenticate方法。
    private Authenticator authenticator;
    
    // org.apache.shiro.authc.pam.ModularRealmAuthenticator
    public AuthenticatingSecurityManager() {
        super();
        this.authenticator = new ModularRealmAuthenticator();
    }
    
    /**
     * 调用ModularRealmAuthenticator的authenticate,而ModularRealmAuthenticator无该方法 
     * 因此调用该类的父类AbstractAuthenticator的authenticate方法
     */
    public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
        return this.authenticator.authenticate(token);
    }
}


  • AbstractAuthenticator的authenticate方法

package org.apache.shiro.authc;

public abstract class AbstractAuthenticator implements Authenticator, LogoutAware {
     public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {

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

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

        AuthenticationInfo info;
        try {
             // 真正执行验证的方法
            info = doAuthenticate(token);
            if (info == null) {
                // 认证失败,抛出异常
                throw new AuthenticationException(msg);
            }
        } catch (Throwable t) {
            // 认证失败,抛出异常
        }

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

        notifySuccess(token, info);

        return info;
    }
    // 抽象方法,调用子类ModularRealmAuthenticator的实现
    protected abstract AuthenticationInfo doAuthenticate(AuthenticationToken token)
            throws AuthenticationException;
}


  • ModularRealmAuthenticator类的doAuthenticate方法

package org.apache.shiro.authc.pam;

public class ModularRealmAuthenticator extends AbstractAuthenticator {
    /**
     * List of realms that will be iterated through when a user authenticates.
     */
    private Collection<Realm> realms;
    
    /**
     * 认证策略, 默认org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy
     */
    private AuthenticationStrategy authenticationStrategy;
    
    // 默认无参构造方法
    public ModularRealmAuthenticator() {
        this.authenticationStrategy = new AtLeastOneSuccessfulStrategy();
    }
    
    // 执行认证 
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        assertRealmsConfigured();
        Collection<Realm> realms = getRealms();
        if (realms.size() == 1) {
            // 最终调用AuthenticationInfo info = realm.getAuthenticationInfo(token);
            return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
        } else {
            // 最终调用AuthenticationInfo info = realm.getAuthenticationInfo(token);
            return doMultiRealmAuthentication(realms, authenticationToken);
        }
    }
}


  • 调用AuthenticatingRealm类的getAuthenticationInfo

package org.apache.shiro.realm;

public abstract class AuthenticatingRealm extends CachingRealm implements Initializable {
    /**
     * Credentials matcher used to determine if the provided credentials match the credentials stored in the data store.
     */
    private CredentialsMatcher credentialsMatcher;

     /**-------------------------------------------
    |     C O N S T R U C T O R S      |
    ============================================*/
    public AuthenticatingRealm() {
        this(null, new SimpleCredentialsMatcher());
    }

    public AuthenticatingRealm(CacheManager cacheManager) {
        this(cacheManager, new SimpleCredentialsMatcher());
    }

    public AuthenticatingRealm(CredentialsMatcher matcher) {
        this(null, matcher);
    }

    public AuthenticatingRealm(CacheManager cacheManager, CredentialsMatcher matcher) {
        authenticationTokenClass = UsernamePasswordToken.class;
        // 代码略
    }
    
    /** 获取认证信息,只有AuthenticatingRealm类实现了该方法 */
    public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        AuthenticationInfo info = getCachedAuthenticationInfo(token);
        if (info == null) {
            //otherwise not cached, perform the lookup:
            info = doGetAuthenticationInfo(token);
            log.debug("Looked up AuthenticationInfo [{}] from doGetAuthenticationInfo", info);
            if (token != null && info != null) {
                cacheAuthenticationInfoIfPossible(token, info);
            }
        } else {
            log.debug("Using cached authentication info [{}] to perform credentials matching.", info);
        }

        if (info != null) {
            // 比较传入的token和doGetAuthenticationInfo获取到的值是否一样;
            // info实际上是调用doGetAuthenticationInfo方法返回的,一般是自定义doGetAuthenticationInfo方法来处理认证。
            assertCredentialsMatch(token, info);    
        } else {
            log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}].  Returning null.", token);
        }

        return info;
    }
    
    /** Retrieves authentication data from an implementation-specific datasource (RDBMS, LDAP, etc) for the given
     * authentication token. 
     * 用户自定义的Realm一般都实现该方法,用来实现自己的身份认证(如根据用户名查询用户是否存在,若存在进行密码比对)
     */
    protected abstract AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;
}

实际上在ModularRealmAuthenticator中获取到的Realm是IniRealm,而继承关系为:

org.apache.shiro.realm.text.IniRealm
    extends org.apache.shiro.realm.text.TextConfigurationRealm
        extends org.apache.shiro.realm.SimpleAccountRealm
            extends org.apache.shiro.realm.AuthorizingRealm
                extends org.apache.shiro.realm.AuthenticatingRealm

在IniRealm的实例中调用getAuthenticationInfo时,实际调用的是父类AuthenticatingRealm的getAuthenticationInfo方法,而doGetAuthenticationInfo方法在子类中有自己的实现。

package org.apache.shiro.realm.text;

public class IniRealm extends TextConfigurationRealm {

    public static final String USERS_SECTION_NAME = "users";
    public static final String ROLES_SECTION_NAME = "roles";

    private static transient final Logger log = LoggerFactory.getLogger(IniRealm.class);

    private String resourcePath;
    private Ini ini; //reference added in 1.2 for SHIRO-322

    public IniRealm() {
        super();
    }
    
    /** SecurityManager中的createRealm中会调用该构造函数创建实例 */
    public IniRealm(Ini ini) {
        this();
        processDefinitions(ini);
    }
    
     private void processDefinitions(Ini ini) {
        /** 处理ini文件中的[roles]定义 */
        Ini.Section rolesSection = ini.getSection(ROLES_SECTION_NAME);
        if (!CollectionUtils.isEmpty(rolesSection)) {
            log.debug("Discovered the [{}] section.  Processing...", ROLES_SECTION_NAME);
            processRoleDefinitions(rolesSection);
        }
        /** 处理ini文件中的[users]定义 */
        Ini.Section usersSection = ini.getSection(USERS_SECTION_NAME);
        if (!CollectionUtils.isEmpty(usersSection)) {
            log.debug("Discovered the [{}] section.  Processing...", USERS_SECTION_NAME);
            /* 
            * 在该方法中会执行new SimpleAccount(username, password, getName()); 
            * SimpleAccount构造方法:public SimpleAccount(Object principal, Object credentials, String realmName) {......}
            */
            processUserDefinitions(usersSection);
        }
     }
}
  • IniRealm中未定义doGetAuthenticationInfo的实现,会自动调用其父类SimpleAccountRealm的实现

package org.apache.shiro.realm;
/**
 * User accounts and roles are stored in two Maps in memory, 
 * so it is expected that the total number of either is not sufficiently large.
 */
public class SimpleAccountRealm extends AuthorizingRealm {
    protected final Map<String, SimpleAccount> users; //username-to-SimpleAccount
    protected final Map<String, SimpleRole> roles; //roleName-to-SimpleRole
    protected final ReadWriteLock USERS_LOCK;
    protected final ReadWriteLock ROLES_LOCK;
    
    public SimpleAccountRealm() {
        this.users = new LinkedHashMap<String, SimpleAccount>();
        this.roles = new LinkedHashMap<String, SimpleRole>();
        USERS_LOCK = new ReentrantReadWriteLock();
        ROLES_LOCK = new ReentrantReadWriteLock();
        //SimpleAccountRealms are memory-only realms - no need for an additional cache mechanism since we're
        //already as memory-efficient as we can be:
        setCachingEnabled(false);
    }
    
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        
        // getUser就是从IniRealm的processUserDefinitions方法处理时,调用SimpleAccountRealm.add添加的Account
        SimpleAccount account = getUser(upToken.getUsername());

        // 略

        return account;
    }
}

总结,至此,身份认证完成(具体的比对token的工作由AuthenticatingRealm.assertCredentialsMatch(token,  info);完成)。