源码分析shiro认证授权流程

红太狼 2022-05-26 11:42 340阅读 0赞

原文地址:

https://www.cnblogs.com/davidwang456/p/4428421.html

  1. shiro介绍

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

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

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

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

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

170914431824958.png

以下内容参考: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的其他组件提供缓存支持。

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

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

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

第二步:代理DelegatingSubject继承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. }

第三步:调用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. Subject loggedIn = createSubject(token, info, subject);
  17. onSuccessfulLogin(token, info, loggedIn);
  18. return loggedIn;
  19. }

第四步:认证管理器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. 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. }

第六步: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. AuthenticationInfo info = getCachedAuthenticationInfo(token); //从缓存中读取
  3. if (info == null) {
  4. //otherwise not cached, perform the lookup:
  5. info = doGetAuthenticationInfo(token); //缓存中读不到,则到数据库或者ldap或者jndi等去读
  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. }
  1. 从缓存中读取的方法:
  1. private Cache<Object, AuthenticationInfo> getAuthenticationCacheLazy() {
  2. if (this.authenticationCache == null) {
  3. log.trace("No authenticationCache instance set. Checking for a cacheManager...");
  4. CacheManager cacheManager = getCacheManager();
  5. if (cacheManager != null) {
  6. String cacheName = getAuthenticationCacheName();
  7. log.debug("CacheManager [{}] configured. Building authentication cache '{}'", cacheManager, cacheName);
  8. this.authenticationCache = cacheManager.getCache(cacheName);
  9. }
  10. }
  11. return this.authenticationCache;
  12. }
  1. 从数据库中读取的方法:

JdbcRealm继承 AuthorizingRealm执行doGetAuthenticationInfo方法

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

接着调用sql语句:

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

其中authenticationQuery定义如下:

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

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

发表评论

表情:
评论列表 (有 0 条评论,340人围观)

还没有评论,来说两句吧...

相关阅读