shiro讲解之 多Realm 之 Authentication

ゞ 浴缸里的玫瑰 2022-06-06 03:16 329阅读 0赞

shiro讲解之 多Realm Authentication

本章节将详细讲解 Shiro 多 Realm 认证以、多 Realm 配置以及多 Realm 认证策略。


实例

首先我们以我们之前搭建的Spring + SpringMVC + Shiro 的基本框架为例子,然后进行多 Realm 配置。

  • 多Realm 的实现

    • Realms 代码
      为了直观体提现多Realm 认证策略,我们再次设定 ShiroRealm 中的认证能够顺利通过,而 MyRealm 中的不能。

      • ShiroRealm

        1. package com.shiro.example.interceptor.realm;
        2. import java.util.HashSet;
        3. import java.util.Set;
        4. import org.apache.shiro.authc.AuthenticationException;
        5. import org.apache.shiro.authc.AuthenticationInfo;
        6. import org.apache.shiro.authc.AuthenticationToken;
        7. import org.apache.shiro.authc.LockedAccountException;
        8. import org.apache.shiro.authc.SimpleAuthenticationInfo;
        9. import org.apache.shiro.authc.UnknownAccountException;
        10. import org.apache.shiro.authc.UsernamePasswordToken;
        11. import org.apache.shiro.authz.AuthorizationInfo;
        12. import org.apache.shiro.authz.SimpleAuthorizationInfo;
        13. import org.apache.shiro.crypto.hash.SimpleHash;
        14. import org.apache.shiro.realm.AuthorizingRealm;
        15. import org.apache.shiro.subject.PrincipalCollection;
        16. import org.apache.shiro.util.ByteSource;
        17. import com.shiro.example.entity.SubjectEntity;
        18. public class ShiroRealm extends AuthorizingRealm {
        19. @Override
        20. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        21. System.out.println("[FirstRealm] doGetAuthenticationInfo");
        22. // 1. 把 AuthenticationToken 转换为 UsernamePasswordToken
        23. UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        24. // 2. 从 UsernamePasswordToken 中来获取 username
        25. String username = upToken.getUsername();
        26. // 3. 调用数据库的方法, 从数据库中查询 username 对应的用户记录
        27. SubjectEntity principals = new SubjectEntity("580655386dc0bef1105a44f9dcbe4a1d3a7b0781", "Dustyone");
        28. // 4. 若用户不存在, 则可以抛出 UnknownAccountException 异常
        29. if ("unknown".equals(username)) {
        30. throw new UnknownAccountException("用户不存在!");
        31. }
        32. // 5. 根据用户信息的情况, 决定是否需要抛出其他的 AuthenticationException 异常.
        33. if ("monster".equals(username)) {
        34. throw new LockedAccountException("用户被锁定");
        35. }
        36. // 6. 根据用户的情况, 来构建 AuthenticationInfo 对象并返回. 通常使用的实现类为:
        37. // SimpleAuthenticationInfo
        38. // 以下信息是从数据库中获取的.
        39. // 1). principal: 认证的实体信息. 可以是 username, 也可以是数据表对应的用户的实体类对象.
        40. Object principal = principals.getUsername();
        41. // 2). credentials: 密码.
        42. Object credentials = principals.getPassword(); // "fc1709d0a95a6be30bc5926fdb7f22f4";
        43. // 3). realmName: 当前 realm 对象的 name. 调用父类的 getName() 方法即可
        44. String realmName = getName();
        45. // 4). 盐值.
        46. ByteSource credentialsSalt = ByteSource.Util.bytes(username);
        47. /* * SimpleAuthenticationInfo info = new * SimpleAuthenticationInfo(principal, credentials, realmName); */
        48. SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt,realmName);
  1. return info;
  2. }
  3. // 授权会被 shiro 回调的方法
  4. @Override
  5. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  6. // 1. 从 PrincipalCollection 中来获取登录用户的信息
  7. Object principal = principals.getPrimaryPrincipal();
  8. // 2. 利用登录的用户的信息来用户当前用户的角色或权限(可能需要查询数据库)
  9. Set<String> roles = new HashSet<>();
  10. roles.add("user");
  11. if ("admin".equals(principal)) {
  12. roles.add("admin");
  13. }
  14. // 3. 创建 SimpleAuthorizationInfo, 并设置其 roles 属性.
  15. SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
  16. // 4. 返回 SimpleAuthorizationInfo 对象.
  17. return info;
  18. }
  19. }
  20. * MyRealm
  21. package com.shiro.example.interceptor.realm;
  22. import java.util.HashSet;
  23. import java.util.Set;
  24. import org.apache.shiro.authc.AuthenticationException;
  25. import org.apache.shiro.authc.AuthenticationInfo;
  26. import org.apache.shiro.authc.AuthenticationToken;
  27. import org.apache.shiro.authc.SimpleAuthenticationInfo;
  28. import org.apache.shiro.authc.UsernamePasswordToken;
  29. import org.apache.shiro.authz.AuthorizationInfo;
  30. import org.apache.shiro.authz.SimpleAuthorizationInfo;
  31. import org.apache.shiro.realm.AuthorizingRealm;
  32. import org.apache.shiro.subject.PrincipalCollection;
  33. import org.apache.shiro.util.ByteSource;
  34. import com.shiro.example.entity.SubjectEntity;
  35. public class MyRealm extends AuthorizingRealm {
  36. @Override
  37. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  38. System.out.println("[Second] doGetAuthenticationInfo");
  39. // 1. 把 AuthenticationToken 转换为 UsernamePasswordToken
  40. UsernamePasswordToken upToken = (UsernamePasswordToken) token;
  41. String username = upToken.getUsername();
  42. SubjectEntity principals = new SubjectEntity("580655386dc0bef1105a44f9dcbe4a1d3a7b0781", "Dustyone");
  43. Object principal = principals.getUsername();
  44. Object credentials = principals.getPassword();
  45. String realmName = getName();
  46. ByteSource credentialsSalt = ByteSource.Util.bytes(username);
  47. SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt,realmName);
  48. return info;
  49. }
  50. @Override
  51. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  52. Object principal = principals.getPrimaryPrincipal();
  53. Set<String> roles = new HashSet<>();
  54. roles.add("user");
  55. if ("admin".equals(principal)) {
  56. roles.add("admin");
  57. }
  58. SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
  59. return info;
  60. }
  61. }
  62. Realm 认证的差异性体现在 Realm SpringContext中的配置,即一下配置。
  63. * 设置多个 Realm Bean
  64. * ShiroRealm
  65. <bean id="shiroRealm" class="com.shiro.example.interceptor.realm.ShiroRealm">
  66. <property name="credentialsMatcher">
  67. <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
  68. <property name="hashAlgorithmName" value="SHA-1"></property>
  69. <property name="hashIterations" value="1024"></property>
  70. </bean>
  71. </property>
  72. </bean>
  73. * MyRealm
  74. <bean id="myRealm" class="com.shiro.example.interceptor.realm.MyRealm">
  75. <property name="credentialsMatcher">
  76. <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
  77. <property name="hashAlgorithmName" value="MD5"></property>
  78. <property name="hashIterations" value="100"></property>
  79. </bean>
  80. </property>
  81. </bean>
  82. * 设置 Realm 认证策略
  83. <!-- Realm认证策略 -->
  84. <bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
  85. <property name="authenticationStrategy">
  86. <!-- 多个Reaml认证中有一个认证成功即成功策略 -->
  87. <bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>
  88. <!-- 第一个Reaml认证策略 -->
  89. <!-- <bean class="org.apache.shiro.authc.pam.FirstSuccessfulStrategy"></bean> -->
  90. <!-- 必须所有Reaml都成功认证策略 -->
  91. <!-- <bean class="org.apache.shiro.authc.pam.AllSuccessfulStrategy"></bean> -->
  92. </property>
  93. </bean>
  94. * Realm 和多认证策略 Bean 交由SecurityManager 统一管理
  95. <!-- 1.配置SecurityManager -->
  96. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
  97. <property name="cacheManager" ref="cacheManager" />
  98. <!-- Shiro Realm认证策略 -->
  99. <property name="authenticator" ref="authenticator"></property>
  100. <!-- Realm Bean 引用 -->
  101. <property name="realms">
  102. <list>
  103. <ref bean="shiroRealm"></ref>
  104. <ref bean="myRealm"></ref>
  105. </list>
  106. </property>
  107. </bean>
  • 结果

    这里写图片描述

    这里写图片描述

    这里写图片描述


多 Realm 认证策略

在我们的Application 中 如果我们使用的是Realm,那么一般而言 SecurityManager 继承了 Authenticator(Shiro API 中身份验证核心的入口点)。

如果使用的是多 Realm的话 一般继承 ModularRealmAuthenticator 即 SecurityManager 的身份认证将交由指定的多个 Realm 去实现,此时默认实现 AuthenticationStrategy(默认的认证策略,我们也可以自定义认证策略,自定义方式参考上文。) 接口。那么下面我们将详细了解下 Shiro 的多 Realm 认证策略。

  • FirstSuccessfulStrategy
    只要有一个 Realm 验证成功即可,只返回第一个 Realm 身份验证成功的认证信息,其他的忽略
  • AtLeastOneSuccessfulStrategy
    只要有一个Realm验证成功即可,和FirstSuccessfulStrategy 不同,将返回所有Realm身份验证成功的认证信息;
  • AllSuccessfulStrategy
    所有Realm验证成功才算成功,且返回所有Realm身份验证成功的认证信息,如果有一个失败就失败了

ModularRealmAuthenticator 默认是 AtLeastOneSuccessfulStrategy 策略

下图为 Shiro 的 Realm、SecurityManager、Authenticator以及认证策略之间的关系

这里写图片描述


小结

  • Shiro 中多 Realm 的配置和实现,以本章实例为例 需在Spring的 Context中配置

    • Realm 的配置
    • 多Realm 的认证策略
    • 多Realm 和 多 Realm 认证策略统一交由 SecurityManager 管理。
  • 理解 Realm、SecurityManager、Authenticator以及认证策略之间的关系 以便我们在设计多 Realm的时候能很好地实现我们的需求。
  • 使用多 Realm 做认证时 realm 被执行的顺序与Spring Context 配置有关。顺序执行。

发表评论

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

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

相关阅读