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);
    }
posted @ 2017-08-21 16:16  jkavor  阅读(8891)  评论(3编辑  收藏  举报