1. shiro介绍

Apache Shiro是一个强大易用的Java安全框架,提供了认证、授权、加密和会话管理等功能:

  • 认证 - 用户身份识别,常被称为用户“登录”;
  • 授权 - 访问控制;
  • 密码加密 - 保护或隐藏数据防止被偷窥;
  • 会话管理 - 每用户相关的时间敏感的状态。

对于任何一个应用程序,Shiro都可以提供全面的安全管理服务。并且相对于其他安全框架,Shiro要简单的多。

2. shiro源码概况

先要了解shiro的基本框架(见http://www.cnblogs.com/davidwang456/p/4425145.html)。

然后看一下各个组件之间的关系:

一下内容参考:http://kdboy.iteye.com/blog/1154644

Subject:即“当前操作用户”。但是,在Shiro中,Subject这一概念并不仅仅指人,也可以是第三方进程、后台帐户(Daemon Account)或其他类似事物。它仅仅意味着“当前跟软件交互的东西”。但考虑到大多数目的和用途,你可以把它认为是Shiro的“用户”概念。 
Subject代表了当前用户的安全操作,SecurityManager则管理所有用户的安全操作。

SecurityManager:它是Shiro框架的核心,典型的Facade模式,Shiro通过SecurityManager来管理内部组件实例,并通过它来提供安全管理的各种服务。

Realm: Realm充当了Shiro与应用安全数据间的“桥梁”或者“连接器”。也就是说,当对用户执行认证(登录)和授权(访问控制)验证时,Shiro会从应用配置的Realm中查找用户及其权限信息。 
从这个意义上讲,Realm实质上是一个安全相关的DAO:它封装了数据源的连接细节,并在需要时将相关数据提供给Shiro。当配置Shiro时,你必须至少指定一个Realm,用于认证和(或)授权。配置多个Realm是可以的,但是至少需要一个。 
Shiro内置了可以连接大量安全数据源(又名目录)的Realm,如LDAP、关系数据库(JDBC)、类似INI的文本配置资源以及属性文件等。如果缺省的Realm不能满足需求,你还可以插入代表自定义数据源的自己的Realm实现。

Shiro主要组件还包括: 
Authenticator :认证就是核实用户身份的过程。这个过程的常见例子是大家都熟悉的“用户/密码”组合。多数用户在登录软件系统时,通常提供自己的用户名(当事人)和支持他们的密码(证书)。如果存储在系统中的密码(或密码表示)与用户提供的匹配,他们就被认为通过认证。 
Authorizer :授权实质上就是访问控制 - 控制用户能够访问应用中的哪些内容,比如资源、Web页面等等。 
SessionManager :在安全框架领域,Apache Shiro提供了一些独特的东西:可在任何应用或架构层一致地使用Session API。即,Shiro为任何应用提供了一个会话编程范式 - 从小型后台独立应用到大型集群Web应用。这意味着,那些希望使用会话的应用开发者,不必被迫使用Servlet或EJB容器了。或者,如果正在使用这些容器,开发者现在也可以选择使用在任何层统一一致的会话API,取代Servlet或EJB机制。 
CacheManager :对Shiro的其他组件提供缓存支持。

3. 做一个demo,跑shiro的源码,从login开始:

第一步:用户根据表单信息填写用户名和密码,然后调用登陆按钮。内部执行如下:

  1. UsernamePasswordToken token = new UsernamePasswordToken(loginForm.getUsername(), loginForm.getPassphrase());
  2.  
  3. token.setRememberMe(true);
  4.  
  5. Subject currentUser = SecurityUtils.getSubject();
  6.  
  7. currentUser.login(token);

第二步:代理DelegatingSubject继承Subject执行login

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

第三步:调用DefaultSecurityManager继承SessionsSecurityManager执行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.  
  17. Subject loggedIn = createSubject(token, info, subject);
  18.  
  19. onSuccessfulLogin(token, info, loggedIn);
  20.  
  21. return loggedIn;
  22. }

第四步:认证管理器AuthenticatingSecurityManager继承RealmSecurityManager执行authenticate方法:

  1. /**
  2. * Delegates to the wrapped {@link org.apache.shiro.authc.Authenticator Authenticator} for authentication.
  3. */
  4. public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
  5. return this.authenticator.authenticate(token);
  6. }

第五步:抽象认证管理器AbstractAuthenticator继承Authenticator, LogoutAware 执行authenticate方法:

  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. throw ae;
  41. }
  42.  
  43. log.debug("Authentication successful for token [{}]. Returned account [{}]", token, info);
  44.  
  45. notifySuccess(token, info);
  46.  
  47. return info;
  48. }

第六步:ModularRealmAuthenticator继承AbstractAuthenticator执行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. }

接着调用:

  1. /**
  2. * Performs the authentication attempt by interacting with the single configured realm, which is significantly
  3. * simpler than performing multi-realm logic.
  4. *
  5. * @param realm the realm to consult for AuthenticationInfo.
  6. * @param token the submitted AuthenticationToken representing the subject's (user's) log-in principals and credentials.
  7. * @return the AuthenticationInfo associated with the user account corresponding to the specified {@code token}
  8. */
  9. protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) {
  10. if (!realm.supports(token)) {
  11. String msg = "Realm [" + realm + "] does not support authentication token [" +
  12. token + "]. Please ensure that the appropriate Realm implementation is " +
  13. "configured correctly or that the realm accepts AuthenticationTokens of this type.";
  14. throw new UnsupportedTokenException(msg);
  15. }
  16. AuthenticationInfo info = realm.getAuthenticationInfo(token);
  17. if (info == null) {
  18. String msg = "Realm [" + realm + "] was unable to find account data for the " +
  19. "submitted AuthenticationToken [" + token + "].";
  20. throw new UnknownAccountException(msg);
  21. }
  22. return info;
  23. }

第七步:AuthenticatingRealm继承CachingRealm执行getAuthenticationInfo方法

  1. public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  2.  
  3. AuthenticationInfo info = getCachedAuthenticationInfo(token); //从缓存中读取
  4. if (info == null) {
  5. //otherwise not cached, perform the lookup:
  6. info = doGetAuthenticationInfo(token); //缓存中读不到,则到数据库或者ldap或者jndi等去读
  7. log.debug("Looked up AuthenticationInfo [{}] from doGetAuthenticationInfo", info);
  8. if (token != null && info != null) {
  9. cacheAuthenticationInfoIfPossible(token, info);
  10. }
  11. } else {
  12. log.debug("Using cached authentication info [{}] to perform credentials matching.", info);
  13. }
  14.  
  15. if (info != null) {
  16. assertCredentialsMatch(token, info);
  17. } else {
  18. log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}]. Returning null.", token);
  19. }
  20.  
  21. return info;
  22. }

1. 从缓存中读取的方法:

  1. /**
  2. * Checks to see if the authenticationCache class attribute is null, and if so, attempts to acquire one from
  3. * any configured {@link #getCacheManager() cacheManager}. If one is acquired, it is set as the class attribute.
  4. * The class attribute is then returned.
  5. *
  6. * @return an available cache instance to be used for authentication caching or {@code null} if one is not available.
  7. * @since 1.2
  8. */
  9. private Cache<Object, AuthenticationInfo> getAuthenticationCacheLazy() {
  10.  
  11. if (this.authenticationCache == null) {
  12.  
  13. log.trace("No authenticationCache instance set. Checking for a cacheManager...");
  14.  
  15. CacheManager cacheManager = getCacheManager();
  16.  
  17. if (cacheManager != null) {
  18. String cacheName = getAuthenticationCacheName();
  19. log.debug("CacheManager [{}] configured. Building authentication cache '{}'", cacheManager, cacheName);
  20. this.authenticationCache = cacheManager.getCache(cacheName);
  21. }
  22. }
  23.  
  24. return this.authenticationCache;
  25. }

2. 从数据库中读取的方法:

JdbcRealm继承 AuthorizingRealm执行doGetAuthenticationInfo方法

  1. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  2.  
  3. UsernamePasswordToken upToken = (UsernamePasswordToken) token;
  4. String username = upToken.getUsername();
  5.  
  6. // Null username is invalid
  7. if (username == null) {
  8. throw new AccountException("Null usernames are not allowed by this realm.");
  9. }
  10.  
  11. Connection conn = null;
  12. SimpleAuthenticationInfo info = null;
  13. try {
  14. conn = dataSource.getConnection();
  15.  
  16. String password = null;
  17. String salt = null;
  18. switch (saltStyle) {
  19. case NO_SALT:
  20. password = getPasswordForUser(conn, username)[0];
  21. break;
  22. case CRYPT:
  23. // TODO: separate password and hash from getPasswordForUser[0]
  24. throw new ConfigurationException("Not implemented yet");
  25. //break;
  26. case COLUMN:
  27. String[] queryResults = getPasswordForUser(conn, username);
  28. password = queryResults[0];
  29. salt = queryResults[1];
  30. break;
  31. case EXTERNAL:
  32. password = getPasswordForUser(conn, username)[0];
  33. salt = getSaltForUser(username);
  34. }
  35.  
  36. if (password == null) {
  37. throw new UnknownAccountException("No account found for user [" + username + "]");
  38. }
  39.  
  40. info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());
  41.  
  42. if (salt != null) {
  43. info.setCredentialsSalt(ByteSource.Util.bytes(salt));
  44. }
  45.  
  46. } catch (SQLException e) {
  47. final String message = "There was a SQL error while authenticating user [" + username + "]";
  48. if (log.isErrorEnabled()) {
  49. log.error(message, e);
  50. }
  51.  
  52. // Rethrow any SQL errors as an authentication exception
  53. throw new AuthenticationException(message, e);
  54. } finally {
  55. JdbcUtils.closeConnection(conn);
  56. }
  57.  
  58. return info;
  59. }

接着调用sql语句:

  1. private String[] getPasswordForUser(Connection conn, String username) throws SQLException {
  2.  
  3. String[] result;
  4. boolean returningSeparatedSalt = false;
  5. switch (saltStyle) {
  6. case NO_SALT:
  7. case CRYPT:
  8. case EXTERNAL:
  9. result = new String[1];
  10. break;
  11. default:
  12. result = new String[2];
  13. returningSeparatedSalt = true;
  14. }
  15.  
  16. PreparedStatement ps = null;
  17. ResultSet rs = null;
  18. try {
  19. ps = conn.prepareStatement(authenticationQuery);
  20. ps.setString(1, username);
  21.  
  22. // Execute query
  23. rs = ps.executeQuery();
  24.  
  25. // Loop over results - although we are only expecting one result, since usernames should be unique
  26. boolean foundResult = false;
  27. while (rs.next()) {
  28.  
  29. // Check to ensure only one row is processed
  30. if (foundResult) {
  31. throw new AuthenticationException("More than one user row found for user [" + username + "]. Usernames must be unique.");
  32. }
  33.  
  34. result[0] = rs.getString(1);
  35. if (returningSeparatedSalt) {
  36. result[1] = rs.getString(2);
  37. }
  38.  
  39. foundResult = true;
  40. }
  41. } finally {
  42. JdbcUtils.closeResultSet(rs);
  43. JdbcUtils.closeStatement(ps);
  44. }
  45.  
  46. return result;
  47. }

其中authenticationQuery定义如下:

  1. protected String authenticationQuery = DEFAULT_AUTHENTICATION_QUERY;
  2. protected static final String DEFAULT_AUTHENTICATION_QUERY = "select password from users where username = ?";

4. 小结

Apache Shiro 是功能强大并且容易集成的开源权限框架,它能够完成认证、授权、加密、会话管理等功能。认证和授权为权限控制的核心,简单来说,“认证”就是证明你是谁? Web 应用程序一般做法通过表单提交用户名及密码达到认证目的。“授权”即是否允许已认证用户访问受保护资源。

参考文献:

http://kdboy.iteye.com/blog/1154644

http://www.ibm.com/developerworks/cn/java/j-lo-shiro/ 

源码分析shiro认证授权流程的更多相关文章

  1. Solr4.8.0源码分析(5)之查询流程分析总述

    Solr4.8.0源码分析(5)之查询流程分析总述 前面已经写到,solr查询是通过http发送命令,solr servlet接受并进行处理.所以solr的查询流程从SolrDispatchsFilt ...

  2. (转)linux内存源码分析 - 内存回收(整体流程)

    http://www.cnblogs.com/tolimit/p/5435068.html------------linux内存源码分析 - 内存回收(整体流程) 概述 当linux系统内存压力就大时 ...

  3. HDFS源码分析DataXceiver之整体流程

    在<HDFS源码分析之DataXceiverServer>一文中,我们了解到在DataNode中,有一个后台工作的线程DataXceiverServer.它被用于接收来自客户端或其他数据节 ...

  4. JVM源码分析之JVM启动流程

      原创申明:本文由公众号[猿灯塔]原创,转载请说明出处标注 “365篇原创计划”第十四篇. 今天呢!灯塔君跟大家讲: JVM源码分析之JVM启动流程 前言: 执行Java类的main方法,程序就能运 ...

  5. Yii2 源码分析 入口文件执行流程

    Yii2 源码分析  入口文件执行流程 1. 入口文件:web/index.php,第12行.(new yii\web\Application($config)->run()) 入口文件主要做4 ...

  6. Django rest framework源码分析(一) 认证

    一.基础 最近正好有机会去写一些可视化的东西,就想着前后端分离,想使用django rest framework写一些,顺便复习一下django rest framework的知识,只是顺便哦,好吧. ...

  7. ASP.NET Core[源码分析篇] - 认证

    追本溯源,从使用开始 首先看一下我们的通常是如何使用微软自带的认证,一般在Startup里面配置我们所需的依赖认证服务,这里通过JWT的认证方式讲解 public void ConfigureServ ...

  8. drf源码分析系列---认证

    认证的使用 from rest_framework.authentication import BaseAuthentication from api import models # 认证类 clas ...

  9. Tomcat源码分析之—具体启动流程分析

    从Tomcat启动调用栈可知,Bootstrap类的main方法为整个Tomcat的入口,在init初始化Bootstrap类的时候为设置Catalina的工作路径也就是Catalina_HOME信息 ...

随机推荐

  1. 基于Python的Grib数据可视化

    http://www.cnblogs.com/kallan/p/5160017.html

  2. 多校6 1010 HDU5802 Windows 10 dfs

    // 多校6 1010 HDU5802 Windows 10 // 题意:从p到q有三种操作,要么往上升只能1步,要么往下降,如果连续往下降就是2^n, // 中途停顿或者向上,下次再降的时候从1开始 ...

  3. Nuttx操作系统

    前几天答辩的时候看到有同学在用,回来后查了点资料. 来源:天又亮了 1  NuttX 实时操作系统 NuttX 是一个实时操作系统(RTOS),强调标准兼容和小型封装,具有从8位到32位微控制器环境的 ...

  4. BestCoder Round #85

    sum Accepts: 640 Submissions: 1744 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/13107 ...

  5. cmake编译win下64位obs

    obs是一款开源编码推流工具,简单易用,非常流行.一次项目中,发现本台式机I3处理器下32位obs推流CPU使用率100%.而使用的第三方设备在64位下,性能较好.所以需要编译64位obs并且编译相应 ...

  6. jquery easyui添加图标扩展

    easyui中有很多通过iconCls="icon-reload"这样的属性引入小图标显示,当然我们也可以自己添加自己的小图标. 方式:1.我们可以在jquery easyui的文 ...

  7. BestCoder Round #68 (div.2) tree(hdu 5606)

    tree Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Total Submis ...

  8. Quality Center配置邮箱服务

    Quality Center上要配置二个地方 mail direct pro配置 DNS地址是本机的地址就好了,不需要真实的DNS地址 SMTP端口使用普通的25就好了,不需要使用SSL的·465端口 ...

  9. Python多线程学习资料1

    一.Python中的线程使用: Python中使用线程有两种方式:函数或者用类来包装线程对象. 1.  函数式:调用thread模块中的start_new_thread()函数来产生新线程.如下例: ...

  10. C#学习笔记(二):继承、接口和抽象类

    继承 密封类 密封类(关键字sealed)是不允许其它类继承的,类似Java中的final关键字. public sealed class SealedClassName { //... } 初始化顺 ...