shiro登錄步驟源碼分析


關於 shiro登錄,大多數人應該知道是通過securitymanager調用reaml來實現的。那到底是怎么具體來進行的呢?通過源碼來看一哈,這里我是結合spring來做的登錄;

shiro-1.2.3:

1.登錄代碼

 Subject currentUser = SecurityUtils.getSubject(); 
 currentUser.login(token);

第一句代碼是得到當前subject(subject可看做一個用戶,這是shiro基本知識,可以去百度一哈)。然后就是調用subject的login方法進行登錄。

2.Subject.login

 1 public class DelegatingSubject implements Subject {
 2 ...
 3 public void login(AuthenticationToken token) throws AuthenticationException {
 4         clearRunAsIdentitiesInternal();
 5         Subject subject = securityManager.login(this, token);
 6 
 7         PrincipalCollection principals;
 8 
 9         String host = null;
10 
11         if (subject instanceof DelegatingSubject) {
12             DelegatingSubject delegating = (DelegatingSubject) subject;
13             //we have to do this in case there are assumed identities - we don't want to lose the 'real' principals:
14             principals = delegating.principals;
15             host = delegating.host;
16         } else {
17             principals = subject.getPrincipals();
18         }
19 
20         if (principals == null || principals.isEmpty()) {
21             String msg = "Principals returned from securityManager.login( token ) returned a null or " +
22                     "empty value.  This value must be non null and populated with one or more elements.";
23             throw new IllegalStateException(msg);
24         }
25         this.principals = principals;
26         this.authenticated = true;
27         if (token instanceof HostAuthenticationToken) {
28             host = ((HostAuthenticationToken) token).getHost();
29         }
30         if (host != null) {
31             this.host = host;
32         }
33         Session session = subject.getSession(false);
34         if (session != null) {
35             this.session = decorate(session);
36         } else {
37             this.session = null;
38         }
39     }
40 }

從代碼中標記的部分可知,Subject確實是調用manager的login方法來進行登錄操作;在我的項目中我是用的securitymanager是DefaultWebSecurityManager這個類;

3.DefaultWebSecurityManager.login

public class DefaultSecurityManager extends SessionsSecurityManager {
...
 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;
    }
}

重點是上述標記方法,該方法里會驗證登錄信息,如果登錄通過會返回登錄信息,如不通過則拋出異常;authenticate方法定義在父類AuthenticatingSecurityManager中;

4.AuthenticatingSecurityManager.authenticate

public abstract class AuthenticatingSecurityManager extends RealmSecurityManager {
 private Authenticator authenticator;
 public AuthenticatingSecurityManager() {
        super();
        this.authenticator = new ModularRealmAuthenticator();
    }
...
 public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
        return this.authenticator.authenticate(token);
    }
}

AuthenticatingSecurityManager將authenticate方法交給了ModularRealmAuthenticator類來完成,而該方法是繼承自ModularRealmAuthenticator而來

5.AbstractAuthenticator.

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

代碼不短,但后面都是catch中的處理 代碼,關鍵還是紅色標記的部分;doAuthenticate為抽象方法,由子類ModularRealmAuthenticator來實現

6.ModularRealmAuthenticator.doAuthenticate

public class ModularRealmAuthenticator extends AbstractAuthenticator {
...
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);
        }
    }

}

在這里,我們終於見到了Realm。這個方法就是在判斷程序中定義了幾個realm,分別都單個realm和多個realm的處理方法。這里我們簡單點,直接看單個realm的處理方法doSingleRealmAuthentication;

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

紅色標記部分,就是真正的調用Reaml來實現登錄;接下來,我們來看看Reaml的內容,這里選用JdbcRealm來查看;JdbcRealm繼承自AuthenticatingRealm,而getAuthenticationInfo就來自這個類;

6.AuthenticatingRealm.getAuthenticationInfo方法

public abstract class AuthenticatingRealm extends CachingRealm implements Initializable {
...
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) {
            assertCredentialsMatch(token, info);
        } else {
            log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}].  Returning null.", token);
        }

        return info;
    }
}

第一個標記是從緩存中查看,該用戶是否已經登錄。如果已經登錄怎么直接完成了登錄流程;第二個標記是根據用戶信息,去獲取數據庫保存的該用戶的密碼等信息;第三個標記是利用第二個標記得到的數據庫該用戶的信息和本次登錄該用戶的信息經行比較,如果正確則驗證通過,返回用戶信息。如果不通過則驗證失敗,登錄不成功,拋出錯誤;

protected abstract AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;

這是一個抽象方法,從JdbcReaml里查看該方法

7.JdbcReaml.doGetAuthenticationInfo

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();

        // Null username is invalid
        if (username == null) {
            throw new AccountException("Null usernames are not allowed by this realm.");
        }

        Connection conn = null;
        SimpleAuthenticationInfo info = null;
        try {
            conn = dataSource.getConnection();

            String password = null;
            String salt = null;
            switch (saltStyle) {
            case NO_SALT:
                password = getPasswordForUser(conn, username)[0];
                break;
            case CRYPT:
                // TODO: separate password and hash from getPasswordForUser[0]
                throw new ConfigurationException("Not implemented yet");
                //break;
            case COLUMN:
                String[] queryResults = getPasswordForUser(conn, username);
                password = queryResults[0];
                salt = queryResults[1];
                break;
            case EXTERNAL:
                password = getPasswordForUser(conn, username)[0];
                salt = getSaltForUser(username);
            }

            if (password == null) {
                throw new UnknownAccountException("No account found for user [" + username + "]");
            }

            info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());
            
            if (salt != null) {
                info.setCredentialsSalt(ByteSource.Util.bytes(salt));
            }

        } catch (SQLException e) {
            final String message = "There was a SQL error while authenticating user [" + username + "]";
            if (log.isErrorEnabled()) {
                log.error(message, e);
            }

            // Rethrow any SQL errors as an authentication exception
            throw new AuthenticationException(message, e);
        } finally {
            JdbcUtils.closeConnection(conn);
        }

        return info;
    }
 private String[] getPasswordForUser(Connection conn, String username) throws SQLException {

        String[] result;
        boolean returningSeparatedSalt = false;
        switch (saltStyle) {
        case NO_SALT:
        case CRYPT:
        case EXTERNAL:
            result = new String[1];
            break;
        default:
            result = new String[2];
            returningSeparatedSalt = true;
        }
        
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(authenticationQuery);
            ps.setString(1, username);

            // Execute query
            rs = ps.executeQuery();

            // Loop over results - although we are only expecting one result, since usernames should be unique
            boolean foundResult = false;
            while (rs.next()) {

                // Check to ensure only one row is processed
                if (foundResult) {
                    throw new AuthenticationException("More than one user row found for user [" + username + "]. Usernames must be unique.");
                }

                result[0] = rs.getString(1);
                if (returningSeparatedSalt) {
                    result[1] = rs.getString(2);
                }

                foundResult = true;
            }
        } finally {
            JdbcUtils.closeResultSet(rs);
            JdbcUtils.closeStatement(ps);
        }

        return result;
    }

從這里可以看出來,shiro是根據我們提供的sql代碼( protected String authenticationQuery = DEFAULT_AUTHENTICATION_QUERY,這里有默認值。我們肯定要修改的)來進行jdbc的數據庫查詢;這里如果根據用戶名和所給sql語句查詢到了用戶信息,怎么講數據庫保存的用戶信息返回,否則拋出錯誤;

8.AuthenticatingRealm.assertCredentialsMatch---用戶登錄信息和數據保存用戶信息匹配

 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.");
        }
    }

重點是在標記部分,利用CredentialsMatcher類來進行驗證;CredentialsMatcher是個借口,我們查看他的子類PasswordMatcher

9.PasswordMatcher.doCredentialsMatch---在這里利用PasswordService這個類進行密碼對比驗證,即完成登錄;

 public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {

        PasswordService service = ensurePasswordService();

        Object submittedPassword = getSubmittedPassword(token);
        Object storedCredentials = getStoredPassword(info);
        assertStoredCredentialsType(storedCredentials);

        if (storedCredentials instanceof Hash) {
            Hash hashedPassword = (Hash)storedCredentials;
            HashingPasswordService hashingService = assertHashingPasswordService(service);
            return hashingService.passwordsMatch(submittedPassword, hashedPassword);
        }
        //otherwise they are a String (asserted in the 'assertStoredCredentialsType' method call above):
        String formatted = (String)storedCredentials;
        return passwordService.passwordsMatch(submittedPassword, formatted);
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM