入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

shiro登录过程分析

创建时间:2017-06-14 投稿人: 浏览次数:326

转自:http://blog.csdn.net/jin5203344/article/details/53174341


关于shiro就不用做过多介绍了,今天主要分析下登录过程


首先我大致画了个流程图(可能不够详细):

第一步:用户登录,根据用户登录名密码生产Token 

[java] view plain copy
  1. UsernamePasswordToken token = new UsernamePasswordToken(username, password);  
  2. Subject subject = SecurityUtils.getSubject();  
  3. subject.login(token);  
这里调用了代理subject的login方法,代码如下:

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

第二步:调用securityManager的login方法 

[java] view plain copy
  1. public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {  
  2.        AuthenticationInfo info;  
  3.        try {  
  4.            info = authenticate(token);  
  5.        } catch (AuthenticationException ae) {  
  6.            try {  
  7.                onFailedLogin(token, ae, subject);  
  8.            } catch (Exception e) {  
  9.                if (log.isInfoEnabled()) {  
  10.                    log.info("onFailedLogin method threw an " +  
  11.                            "exception.  Logging and propagating original AuthenticationException.", e);  
  12.                }  
  13.            }  
  14.            throw ae; //propagate  
  15.        }  
  16.   
  17.        Subject loggedIn = createSubject(token, info, subject);  
  18.   
  19.        onSuccessfulLogin(token, info, loggedIn);  
  20.   
  21.        return loggedIn;  
  22.    }  
   第三步:调用securityManager的 authenticate方法 该方法在 其上级类 AuthenticatingSecurityManager中,代码如下:

[java] view plain copy
  1. public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {  
  2.        return this.authenticator.authenticate(token);  
  3.    }  
实际调用了authenticator的authenticate方法,而AuthenticatingSecurityManager的无参构造函数中

[java] view plain copy
  1. public AuthenticatingSecurityManager() {  
  2.         super();  
  3.         this.authenticator = new ModularRealmAuthenticator();  
  4.     }  
而ModularRealmAuthenticator类继承了AbstractAuthenticator类

    第四步:调用AbstractAuthenticator的authenticate方法

[java] view plain copy
  1. public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {  
  2.   
  3.         if (token == null) {  
  4.             throw new IllegalArgumentException("Method argumet (authentication token) cannot be null.");  
  5.         }  
  6.   
  7.         log.trace("Authentication attempt received for token [{}]", token);  
  8.   
  9.         AuthenticationInfo info;  
  10.         try {  
  11.             info = doAuthenticate(token);  
  12.             if (info == null) {  
  13.                 String msg = "No account information found for authentication token [" + token + "] by this " +  
  14.                         "Authenticator instance.  Please check that it is configured correctly.";  
  15.                 throw new AuthenticationException(msg);  
  16.             }  
  17.         } catch (Throwable t) {  
  18.             AuthenticationException ae = null;  
  19.             if (t instanceof AuthenticationException) {  
  20.                 ae = (AuthenticationException) t;  
  21.             }  
  22.             if (ae == null) {  
  23.                 //Exception thrown was not an expected AuthenticationException.  Therefore it is probably a little more  
  24.                 //severe or unexpected.  So, wrap in an AuthenticationException, log to warn, and propagate:  
  25.                 String msg = "Authentication failed for token submission [" + token + "].  Possible unexpected " +  
  26.                         "error? (Typical or expected login exceptions should extend from AuthenticationException).";  
  27.                 ae = new AuthenticationException(msg, t);  
  28.             }  
  29.             try {  
  30.                 notifyFailure(token, ae);  
  31.             } catch (Throwable t2) {  
  32.                 if (log.isWarnEnabled()) {  
  33.                     String msg = "Unable to send notification for failed authentication attempt - listener error?.  " +  
  34.                             "Please check your AuthenticationListener implementation(s).  Logging sending exception " +  
  35.                             "and propagating original AuthenticationException instead...";  
  36.                     log.warn(msg, t2);  
  37.                 }  
  38.             }  
  39.   
  40.   
  41.             throw ae;  
  42.         }  
  43.   
  44.         log.debug("Authentication successful for token [{}].  Returned account [{}]", token, info);  
  45.   
  46.         notifySuccess(token, info);  
  47.   
  48.         return info;  
  49.     }  
看try语句中的 doAuthenticate()方法 则是在其子类ModularRealmAuthenticator中实现,所以

第五步:调用ModularRealmAuthenticator的doAuthenticate方法

[java] view plain copy
  1. protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {  
  2.        assertRealmsConfigured();  
  3.        Collection<Realm> realms = getRealms();  
  4.        if (realms.size() == 1) {  
  5.            return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);  
  6.        } else {  
  7.            return doMultiRealmAuthentication(realms, authenticationToken);  
  8.        }  
  9.    }  
第二行获取realms,但我们记得只配置过realm,realms是什么时候赋值的呢,其实很简单  spring对bean属性的赋值是通过反射 实际调用的是set方法,即我们配置了

一个property 为realm的属性  对属性注入的时候调用的setRealm方法

[java] view plain copy
  1. public void setRealm(Realm realm) {  
  2.        if (realm == null) {  
  3.            throw new IllegalArgumentException("Realm argument cannot be null");  
  4.        }  
  5.        Collection<Realm> realms = new ArrayList<Realm>(1);  
  6.        realms.add(realm);  
  7.        setRealms(realms);  
  8.    }  
所以这里我们的realms实际就是配置的realm,当然前提是我们只配置了单个

第六步:调用ModularRealmAuthenticator的doSingleRealmAuthentication方法

[java] view plain copy
  1. protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) {  
  2.         if (!realm.supports(token)) {  
  3.             String msg = "Realm [" + realm + "] does not support authentication token [" +  
  4.                     token + "].  Please ensure that the appropriate Realm implementation is " +  
  5.                     "configured correctly or that the realm accepts AuthenticationTokens of this type.";  
  6.             throw new UnsupportedTokenException(msg);  
  7.         }  
  8.         AuthenticationInfo info = realm.getAuthenticationInfo(token);  
  9.         if (info == null) {  
  10.             String msg = "Realm [" + realm + "] was unable to find account data for the " +  
  11.                     "submitted AuthenticationToken [" + token + "].";  
  12.             throw new UnknownAccountException(msg);  
  13.         }  
  14.         return info;  
  15.     }  
其中调用了realm自身的getAuthenticationInfo方法

第七步:调用AuthenticatingRealm的getAuthenticationInfo方法

[java] view plain copy
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。