Apache Shiro的登录过程分析

来源:https://blog.csdn.net/jin5203344/article/details/53174341

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


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

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

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

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

第二步:调用securityManager的login方法 

  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. Subject loggedIn = createSubject(token, info, subject);
  17. onSuccessfulLogin(token, info, loggedIn);
  18. return loggedIn;
  19. }
   第三步:调用securityManager的 authenticate方法 该方法在 其上级类 AuthenticatingSecurityManager中,代码如下:

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

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

    第四步:调用AbstractAuthenticator的authenticate方法

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

第五步:调用ModularRealmAuthenticator的doAuthenticate方法

  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方法

  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方法

  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方法

  1. public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  2. AuthenticationInfo info = getCachedAuthenticationInfo(token);
  3. if (info == null) {
  4. //otherwise not cached, perform the lookup:
  5. info = doGetAuthenticationInfo(token);
  6. log.debug( "Looked up AuthenticationInfo [{}] from doGetAuthenticationInfo", info);
  7. if (token != null && info != null) {
  8. cacheAuthenticationInfoIfPossible(token, info);
  9. }
  10. } else {
  11. log.debug( "Using cached authentication info [{}] to perform credentials matching.", info);
  12. }
  13. if (info != null) {
  14. assertCredentialsMatch(token, info);
  15. } else {
  16. log.debug( "No AuthenticationInfo found for submitted AuthenticationToken [{}]. Returning null.", token);
  17. }
  18. return info;
  19. }
     第一行代码,通过缓存获取AuthenticationInfo,说到这里正好看看缓存是怎么实现的,同样代码全在这,跟着走就行

 而我们的cacheManager哪来的呢,我们发现在setRealm方法中调用了setRealms

  1. public void setRealms(Collection<Realm> realms) {
  2. if (realms == null) {
  3. throw new IllegalArgumentException( "Realms collection argument cannot be null.");
  4. }
  5. if (realms.isEmpty()) {
  6. throw new IllegalArgumentException( "Realms collection argument cannot be empty.");
  7. }
  8. this.realms = realms;
  9. afterRealmsSet();
  10. }
  11. protected void afterRealmsSet() {
  12. applyCacheManagerToRealms();
  13. applyEventBusToRealms();
  14. }
可以看到在设置完realms以后调用了一个后续处理方法,在afterRealmsSet中 有个调用 applyCacheManagerToRealms方法 ,字面意思也是很好理解 应用缓存管理器

到realms中,而这种方法代码为:

  1. protected void applyCacheManagerToRealms() {
  2. CacheManager cacheManager = getCacheManager();
  3. Collection<Realm> realms = getRealms();
  4. if (cacheManager != null && realms != null && !realms.isEmpty()) {
  5. for (Realm realm : realms) {
  6. if (realm instanceof CacheManagerAware) {
  7. ((CacheManagerAware) realm).setCacheManager(cacheManager);
  8. }
  9. }
  10. }
  11. }
实际就是判断如果cacheManager不为空 就循环realms设置cacheManager

(有点啰嗦,哈哈,自己当时就是这么想的)

在上面getAuthenticationInfo方法中,我们刚才说过第一行是从缓存中取AuthenticationInfo,如果为空

第八步:调用realm的doGetAuthenticationInfo方法

  1. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  2. // TODO Auto-generated method stub
  3. String userName = (String) token.getPrincipal();
  4. //通过token获取用户信息,这里我们一般从数据库中查询
  5. SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, password, getName());
  6. return authenticationInfo;
  7. }
返回AuthenticationInfo,接着下面代码

  1. if (token != null && info != null) {
  2. cacheAuthenticationInfoIfPossible(token, info);
  3. }
判断 如果token与获取到的 AuthenticationInfo都不为空,缓存 AuthenticationInfo信息

关于从缓存中查询AuthenticationInfo以及缓存AuthenticationInfo信息的方法 这里就不作分析了,可以看做对一个map的操作吧

当然到这里还没完,同样在上面方法中,

  1. if (info != null) {
  2. assertCredentialsMatch(token, info);
  3. } else {
  4. log.debug( "No AuthenticationInfo found for submitted AuthenticationToken [{}]. Returning null.", token);
  5. }
如果 AuthenticationInfo不为空 即通过登录用户查询到了对应的信息

第九步:调用assertCredentialsMatch方法

  1. protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {
  2. CredentialsMatcher cm = getCredentialsMatcher();
  3. if (cm != null) {
  4. if (!cm.doCredentialsMatch(token, info)) {
  5. //not successful - throw an exception to indicate this:
  6. String msg = "Submitted credentials for token [" + token + "] did not match the expected credentials.";
  7. throw new IncorrectCredentialsException(msg);
  8. }
  9. } else {
  10. throw new AuthenticationException( "A CredentialsMatcher must be configured in order to verify " +
  11. "credentials during authentication. If you do not wish for credentials to be examined, you " +
  12. "can configure an " + AllowAllCredentialsMatcher.class.getName() + " instance.");
  13. }
  14. }
第一行获取CredentialsMatcher,如果不为空

第十步:调用CredentialsMatcher的doCredentialsMatch方法,当然CredentialsMatcher我们可以自定义了

第十一步:上面步骤都通过以后回到DefualtSecurityManager的login方法中

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

  1. protected Subject createSubject(AuthenticationToken token, AuthenticationInfo info, Subject existing) {
  2. SubjectContext context = createSubjectContext();
  3. context.setAuthenticated( true);
  4. context.setAuthenticationToken(token);
  5. context.setAuthenticationInfo(info);
  6. if (existing != null) {
  7. context.setSubject(existing);
  8. }
  9. return createSubject(context);
  10. }
接着就是通过SubjectFactory生成subject,这里就不说了,就是从我们查询把我们查询到的用户身份信息关联到对应的subject中
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值