Spring Boot整合Apache Shiro小节

下面介绍一下我在项目中如何将Apache Shiro整合入Spring Boot项目中的。Apache Shiro是一款功能强大,灵活的开源框架,不像Spring Security那么庞大和复杂,Shiro易于理解和使用。

先介绍下Apache Shiro的特性和架构,Shiro官方网站:http://shiro.apache.org/ 

Apache Shiro 特性:

Apache Shiro是一个综合的、有多种特性的应用安全框架。

  • Authentication(认证):用户身份识别,通常被称为用户“登录”
  • Authorization(授权):访问控制。比如某个用户是否具有某个操作的使用权限。
  • Session Management(会话管理):特定于用户的会话管理,甚至在非web 或 EJB 应用程序。
  • Cryptography(加密):在对数据源使用加密算法加密的同时,保证易于使用。

还有其他的功能来支持和加强这些不同应用环境下安全领域的关注点

  • Web Support(Web支持): Shiro’s web support APIs help easily secure web applications.
  • Caching(缓存): Caching is a first-tier citizen in Apache Shiro’s API to ensure that security operations remain fast and efficient.
  • Concurrency(并发): Apache Shiro supports multi-threaded applications with its concurrency features.
  • Testing: Test support exists to help you write unit and integration tests and ensure your code will be secured as expected.
  • “Run As”: A feature that allows users to assume the identity of another user (if they are allowed), sometimes useful in administrative scenarios.
  • “Remember Me”: Remember users’ identities across sessions so they only need to log in when mandatory.

Apache Shiro有三大核心概念:SubjectSecurityManager and Realms

Subject:当前用户

SecurityManager: 管理所有的Subjects

Realm: Realm作为Shiro和访问你的应用安全数据的桥梁或者是连接器,这一部分是真正需要我们自己实现的

下面开始介绍将Shiro整合到Spring Boot中。

1. 数据库表准备

这里需要五张表,用户表,角色表,权限表,用户-角色表,角色-权限表,下面是建表语句

 
  1. CREATE TABLE `sys_user` (

  2. `user_id` bigint(20) NOT NULL AUTO_INCREMENT,

  3. `username` varchar(50) DEFAULT NULL COMMENT '用户名',

  4. `name` varchar(100) DEFAULT NULL,

  5. `password` varchar(50) DEFAULT NULL COMMENT '密码',

  6. `dept_id` int(20) DEFAULT NULL,

  7. `email` varchar(100) DEFAULT NULL COMMENT '邮箱',

  8. `mobile` varchar(100) DEFAULT NULL COMMENT '手机号',

  9. `status` tinyint(255) DEFAULT NULL COMMENT '状态 0:禁用,1:正常',

  10. `user_id_create` bigint(255) DEFAULT NULL COMMENT '创建用户id',

  11. `gmt_create` datetime DEFAULT NULL COMMENT '创建时间',

  12. `gmt_modified` datetime DEFAULT NULL COMMENT '修改时间',

  13. PRIMARY KEY (`user_id`)

  14. ) ENGINE=InnoDB AUTO_INCREMENT=137 DEFAULT CHARSET=utf8;

  15.  
  16. -- ----------------------------

  17. -- Records of sys_user

  18. -- ----------------------------

  19. INSERT INTO `sys_user` VALUES ('1', 'admin', '超级管理员', '27bd386e70f280e24c2f4f2a549b82cf', '6', '[email protected]', '123456', '1', '1', '2017-08-15 21:40:39', '2017-08-15 21:41:00');

  20. INSERT INTO `sys_user` VALUES ('2', 'test', '临时用户', '6cf3bb3deba2aadbd41ec9a22511084e', '6', '[email protected]', null, '1', '1', '2017-08-14 13:43:05', '2017-08-14 21:15:36');

  21. INSERT INTO `sys_user` VALUES ('36', 'ldh', '刘德华', 'bfd9394475754fbe45866eba97738c36', '6', '[email protected]', null, '1', null, null, null);

  22. CREATE TABLE `sys_user_role` (

  23. `id` bigint(20) NOT NULL AUTO_INCREMENT,

  24. `user_id` bigint(20) DEFAULT NULL COMMENT '用户ID',

  25. `role_id` bigint(20) DEFAULT NULL COMMENT '角色ID',

  26. PRIMARY KEY (`id`)

  27. ) ENGINE=InnoDB AUTO_INCREMENT=127 DEFAULT CHARSET=utf8 COMMENT='用户与角色对应关系';

  28.  
  29. -- ----------------------------

  30. -- Records of sys_user_role

  31. -- ----------------------------

  32. INSERT INTO `sys_user_role` VALUES ('73', '30', '48');

  33. INSERT INTO `sys_user_role` VALUES ('74', '30', '49');

  34. INSERT INTO `sys_user_role` VALUES ('75', '30', '50');

  35. INSERT INTO `sys_user_role` VALUES ('76', '31', '48');

  36.  
  37. CREATE TABLE `sys_menu` (

  38. `menu_id` bigint(20) NOT NULL AUTO_INCREMENT,

  39. `parent_id` bigint(20) DEFAULT NULL COMMENT '父菜单ID,一级菜单为0',

  40. `name` varchar(50) DEFAULT NULL COMMENT '菜单名称',

  41. `url` varchar(200) DEFAULT NULL COMMENT '菜单URL',

  42. `perms` varchar(500) DEFAULT NULL COMMENT '授权(多个用逗号分隔,如:user:list,user:create)',

  43. `type` int(11) DEFAULT NULL COMMENT '类型 0:目录 1:菜单 2:按钮',

  44. `icon` varchar(50) DEFAULT NULL COMMENT '菜单图标',

  45. `order_num` int(11) DEFAULT NULL COMMENT '排序',

  46. `gmt_create` datetime DEFAULT NULL COMMENT '创建时间',

  47. `gmt_modified` datetime DEFAULT NULL COMMENT '修改时间',

  48. PRIMARY KEY (`menu_id`)

  49. ) ENGINE=InnoDB AUTO_INCREMENT=102 DEFAULT CHARSET=utf8 COMMENT='菜单管理';

  50.  
  51. -- ----------------------------

  52. -- Records of sys_menu

  53. -- ----------------------------

  54. INSERT INTO `sys_menu` VALUES ('1', '0', '基础管理', '', '', '0', 'fa fa-bars', '0', '2017-08-09 22:49:47', null);

  55. INSERT INTO `sys_menu` VALUES ('2', '3', '系统菜单', 'sys/menu/', 'sys:menu:menu', '1', 'fa fa-th-list', '2', '2017-08-09 22:55:15', null);

  56. INSERT INTO `sys_menu` VALUES ('3', '0', '系统管理', null, null, '0', 'fa fa-desktop', '1', '2017-08-09 23:06:55', '2017-08-14 14:13:43');

  57. INSERT INTO `sys_menu` VALUES ('6', '3', '用户管理', 'sys/user/', 'sys:user:user', '1', 'fa fa-user', '0', '2017-08-10 14:12:11', null);

  58.  
  59. CREATE TABLE `sys_user_role` (

  60. `id` bigint(20) NOT NULL AUTO_INCREMENT,

  61. `user_id` bigint(20) DEFAULT NULL COMMENT '用户ID',

  62. `role_id` bigint(20) DEFAULT NULL COMMENT '角色ID',

  63. PRIMARY KEY (`id`)

  64. ) ENGINE=InnoDB AUTO_INCREMENT=127 DEFAULT CHARSET=utf8 COMMENT='用户与角色对应关系';

  65.  
  66. -- ----------------------------

  67. -- Records of sys_user_role

  68. -- ----------------------------

  69. INSERT INTO `sys_user_role` VALUES ('73', '30', '48');

  70. INSERT INTO `sys_user_role` VALUES ('74', '30', '49');

  71.  
  72. CREATE TABLE `sys_role_menu` (

  73. `id` bigint(20) NOT NULL AUTO_INCREMENT,

  74. `role_id` bigint(20) DEFAULT NULL COMMENT '角色ID',

  75. `menu_id` bigint(20) DEFAULT NULL COMMENT '菜单ID',

  76. PRIMARY KEY (`id`)

  77. ) ENGINE=InnoDB AUTO_INCREMENT=2974 DEFAULT CHARSET=utf8 COMMENT='角色与菜单对应关系';

  78.  
  79. -- ----------------------------

  80. -- Records of sys_role_menu

  81. -- ----------------------------

  82. INSERT INTO `sys_role_menu` VALUES ('367', '44', '1');

  83. INSERT INTO `sys_role_menu` VALUES ('368', '44', '32');


2. 对应实体类

UserDO.java

 
  1. package com.bootdo.system.domain;

  2.  
  3. import java.io.Serializable;

  4. import java.util.Date;

  5. import java.util.List;

  6.  
  7. public class UserDO implements Serializable {

  8. private static final long serialVersionUID = 1L;

  9.  
  10. //

  11. private Long userId;

  12. // 用户名

  13. private String username;

  14. // 用户真实姓名

  15. private String name;

  16. // 密码

  17. private String password;

  18. // 部门

  19. private Long deptId;

  20. private String deptName;

  21. // 邮箱

  22. private String email;

  23. // 手机号

  24. private String mobile;

  25. // 状态 0:禁用,1:正常

  26. private Integer status;

  27. // 创建用户id

  28. private Long userIdCreate;

  29. // 创建时间

  30. private Date gmtCreate;

  31. // 修改时间

  32. private Date gmtModified;

  33. //角色

  34. private List<Long> roleIds;

  35.  
  36. /**

  37. * 设置:

  38. */

  39. public void setUserId(Long userId) {

  40. this.userId = userId;

  41. }

  42.  
  43. /**

  44. * 获取:

  45. */

  46. public Long getUserId() {

  47. return userId;

  48. }

  49.  
  50. /**

  51. * 设置:用户名

  52. */

  53. public void setUsername(String username) {

  54. this.username = username;

  55. }

  56.  
  57. /**

  58. * 获取:用户名

  59. */

  60. public String getUsername() {

  61. return username;

  62. }

  63.  
  64.  
  65. public String getName() {

  66. return name;

  67. }

  68.  
  69. public void setName(String name) {

  70. this.name = name;

  71. }

  72.  
  73. /**

  74. * 设置:密码

  75. */

  76. public void setPassword(String password) {

  77. this.password = password;

  78. }

  79.  
  80. /**

  81. * 获取:密码

  82. */

  83. public String getPassword() {

  84. return password;

  85. }

  86.  
  87. public Long getDeptId() {

  88. return deptId;

  89. }

  90.  
  91. public void setDeptId(Long deptId) {

  92. this.deptId = deptId;

  93. }

  94.  
  95. public String getDeptName() {

  96. return deptName;

  97. }

  98.  
  99. public void setDeptName(String deptName) {

  100. this.deptName = deptName;

  101. }

  102.  
  103. /**

  104. * 设置:邮箱

  105. */

  106. public void setEmail(String email) {

  107. this.email = email;

  108. }

  109.  
  110. /**

  111. * 获取:邮箱

  112. */

  113. public String getEmail() {

  114. return email;

  115. }

  116.  
  117. /**

  118. * 设置:手机号

  119. */

  120. public void setMobile(String mobile) {

  121. this.mobile = mobile;

  122. }

  123.  
  124. /**

  125. * 获取:手机号

  126. */

  127. public String getMobile() {

  128. return mobile;

  129. }

  130.  
  131. /**

  132. * 设置:状态 0:禁用,1:正常

  133. */

  134. public void setStatus(Integer status) {

  135. this.status = status;

  136. }

  137.  
  138. /**

  139. * 获取:状态 0:禁用,1:正常

  140. */

  141. public Integer getStatus() {

  142. return status;

  143. }

  144.  
  145. /**

  146. * 设置:创建用户id

  147. */

  148. public void setUserIdCreate(Long userIdCreate) {

  149. this.userIdCreate = userIdCreate;

  150. }

  151.  
  152. /**

  153. * 获取:创建用户id

  154. */

  155. public Long getUserIdCreate() {

  156. return userIdCreate;

  157. }

  158.  
  159. /**

  160. * 设置:创建时间

  161. */

  162. public void setGmtCreate(Date gmtCreate) {

  163. this.gmtCreate = gmtCreate;

  164. }

  165.  
  166. /**

  167. * 获取:创建时间

  168. */

  169. public Date getGmtCreate() {

  170. return gmtCreate;

  171. }

  172.  
  173. /**

  174. * 设置:修改时间

  175. */

  176. public void setGmtModified(Date gmtModified) {

  177. this.gmtModified = gmtModified;

  178. }

  179.  
  180. /**

  181. * 获取:修改时间

  182. */

  183. public Date getGmtModified() {

  184. return gmtModified;

  185. }

  186.  
  187. public List<Long> getroleIds() {

  188. return roleIds;

  189. }

  190.  
  191. public void setroleIds(List<Long> roleIds) {

  192. this.roleIds = roleIds;

  193. }

  194.  
  195. @Override

  196. public String toString() {

  197. return "UserDO{" +

  198. "userId=" + userId +

  199. ", username='" + username + '\'' +

  200. ", name='" + name + '\'' +

  201. ", password='" + password + '\'' +

  202. ", deptId=" + deptId +

  203. ", deptName='" + deptName + '\'' +

  204. ", email='" + email + '\'' +

  205. ", mobile='" + mobile + '\'' +

  206. ", status=" + status +

  207. ", userIdCreate=" + userIdCreate +

  208. ", gmtCreate=" + gmtCreate +

  209. ", gmtModified=" + gmtModified +

  210. ", roleIds=" + roleIds +

  211. '}';

  212. }

  213. }

RoleDO.java

 
  1. package com.bootdo.system.domain;

  2.  
  3. import java.sql.Timestamp;

  4. import java.util.List;

  5.  
  6. public class RoleDO {

  7.  
  8. private Long roleId;

  9. private String roleName;

  10. private String roleSign;

  11. private String remark;

  12. private Long userIdCreate;

  13. private Timestamp gmtCreate;

  14. private Timestamp gmtModified;

  15. private List<Long> menuIds;

  16.  
  17. public Long getRoleId() {

  18. return roleId;

  19. }

  20.  
  21. public void setRoleId(Long roleId) {

  22. this.roleId = roleId;

  23. }

  24.  
  25. public String getRoleName() {

  26. return roleName;

  27. }

  28.  
  29. public void setRoleName(String roleName) {

  30. this.roleName = roleName;

  31. }

  32.  
  33. public String getRoleSign() {

  34. return roleSign;

  35. }

  36.  
  37. public void setRoleSign(String roleSign) {

  38. this.roleSign = roleSign;

  39. }

  40.  
  41. public String getRemark() {

  42. return remark;

  43. }

  44.  
  45. public void setRemark(String remark) {

  46. this.remark = remark;

  47. }

  48.  
  49. public Long getUserIdCreate() {

  50. return userIdCreate;

  51. }

  52.  
  53. public void setUserIdCreate(Long userIdCreate) {

  54. this.userIdCreate = userIdCreate;

  55. }

  56.  
  57. public Timestamp getGmtCreate() {

  58. return gmtCreate;

  59. }

  60.  
  61. public void setGmtCreate(Timestamp gmtCreate) {

  62. this.gmtCreate = gmtCreate;

  63. }

  64.  
  65. public Timestamp getGmtModified() {

  66. return gmtModified;

  67. }

  68.  
  69. public void setGmtModified(Timestamp gmtModified) {

  70. this.gmtModified = gmtModified;

  71. }

  72.  
  73. public List<Long> getMenuIds() {

  74. return menuIds;

  75. }

  76.  
  77. public void setMenuIds(List<Long> menuIds) {

  78. this.menuIds = menuIds;

  79. }

  80.  
  81. @Override

  82. public String toString() {

  83. return "RoleDO{" +

  84. "roleId=" + roleId +

  85. ", roleName='" + roleName + '\'' +

  86. ", roleSign='" + roleSign + '\'' +

  87. ", remark='" + remark + '\'' +

  88. ", userIdCreate=" + userIdCreate +

  89. ", gmtCreate=" + gmtCreate +

  90. ", gmtModified=" + gmtModified +

  91. ", menuIds=" + menuIds +

  92. '}';

  93. }

  94. }

MenuDO.java
 

 
  1. package com.bootdo.system.domain;

  2.  
  3. import java.io.Serializable;

  4. import java.util.Date;

  5.  
  6. public class MenuDO implements Serializable {

  7. private static final long serialVersionUID = 1L;

  8. //

  9. private Long menuId;

  10. // 父菜单ID,一级菜单为0

  11. private Long parentId;

  12. // 菜单名称

  13. private String name;

  14. // 菜单URL

  15. private String url;

  16. // 授权(多个用逗号分隔,如:user:list,user:create)

  17. private String perms;

  18. // 类型 0:目录 1:菜单 2:按钮

  19. private Integer type;

  20. // 菜单图标

  21. private String icon;

  22. // 排序

  23. private Integer orderNum;

  24. // 创建时间

  25. private Date gmtCreate;

  26. // 修改时间

  27. private Date gmtModified;

  28.  
  29. /**

  30. * 设置:

  31. */

  32. public void setMenuId(Long menuId) {

  33. this.menuId = menuId;

  34. }

  35.  
  36. /**

  37. * 获取:

  38. */

  39. public Long getMenuId() {

  40. return menuId;

  41. }

  42.  
  43. /**

  44. * 设置:父菜单ID,一级菜单为0

  45. */

  46. public void setParentId(Long parentId) {

  47. this.parentId = parentId;

  48. }

  49.  
  50. /**

  51. * 获取:父菜单ID,一级菜单为0

  52. */

  53. public Long getParentId() {

  54. return parentId;

  55. }

  56.  
  57. /**

  58. * 设置:菜单名称

  59. */

  60. public void setName(String name) {

  61. this.name = name;

  62. }

  63.  
  64. /**

  65. * 获取:菜单名称

  66. */

  67. public String getName() {

  68. return name;

  69. }

  70.  
  71. /**

  72. * 设置:菜单URL

  73. */

  74. public void setUrl(String url) {

  75. this.url = url;

  76. }

  77.  
  78. /**

  79. * 获取:菜单URL

  80. */

  81. public String getUrl() {

  82. return url;

  83. }

  84.  
  85. /**

  86. * 设置:授权(多个用逗号分隔,如:user:list,user:create)

  87. */

  88. public void setPerms(String perms) {

  89. this.perms = perms;

  90. }

  91.  
  92. /**

  93. * 获取:授权(多个用逗号分隔,如:user:list,user:create)

  94. */

  95. public String getPerms() {

  96. return perms;

  97. }

  98.  
  99. /**

  100. * 设置:类型 0:目录 1:菜单 2:按钮

  101. */

  102. public void setType(Integer type) {

  103. this.type = type;

  104. }

  105.  
  106. /**

  107. * 获取:类型 0:目录 1:菜单 2:按钮

  108. */

  109. public Integer getType() {

  110. return type;

  111. }

  112.  
  113. /**

  114. * 设置:菜单图标

  115. */

  116. public void setIcon(String icon) {

  117. this.icon = icon;

  118. }

  119.  
  120. /**

  121. * 获取:菜单图标

  122. */

  123. public String getIcon() {

  124. return icon;

  125. }

  126.  
  127. /**

  128. * 设置:排序

  129. */

  130. public void setOrderNum(Integer orderNum) {

  131. this.orderNum = orderNum;

  132. }

  133.  
  134. /**

  135. * 获取:排序

  136. */

  137. public Integer getOrderNum() {

  138. return orderNum;

  139. }

  140.  
  141. /**

  142. * 设置:创建时间

  143. */

  144. public void setGmtCreate(Date gmtCreate) {

  145. this.gmtCreate = gmtCreate;

  146. }

  147.  
  148. /**

  149. * 获取:创建时间

  150. */

  151. public Date getGmtCreate() {

  152. return gmtCreate;

  153. }

  154.  
  155. /**

  156. * 设置:修改时间

  157. */

  158. public void setGmtModified(Date gmtModified) {

  159. this.gmtModified = gmtModified;

  160. }

  161.  
  162. /**

  163. * 获取:修改时间

  164. */

  165. public Date getGmtModified() {

  166. return gmtModified;

  167. }

  168.  
  169. @Override

  170. public String toString() {

  171. return "MenuDO{" +

  172. "menuId=" + menuId +

  173. ", parentId=" + parentId +

  174. ", name='" + name + '\'' +

  175. ", url='" + url + '\'' +

  176. ", perms='" + perms + '\'' +

  177. ", type=" + type +

  178. ", icon='" + icon + '\'' +

  179. ", orderNum=" + orderNum +

  180. ", gmtCreate=" + gmtCreate +

  181. ", gmtModified=" + gmtModified +

  182. '}';

  183. }

  184. }

UserRoleDO.java

 
  1. package com.bootdo.system.domain;

  2.  
  3. public class UserRoleDO {

  4. private Long id;

  5. private Long userId;

  6. private Long roleId;

  7.  
  8. public Long getId() {

  9. return id;

  10. }

  11.  
  12. public void setId(Long id) {

  13. this.id = id;

  14. }

  15.  
  16. public Long getUserId() {

  17. return userId;

  18. }

  19.  
  20. public void setUserId(Long userId) {

  21. this.userId = userId;

  22. }

  23.  
  24. public Long getRoleId() {

  25. return roleId;

  26. }

  27.  
  28. public void setRoleId(Long roleId) {

  29. this.roleId = roleId;

  30. }

  31.  
  32. @Override

  33. public String toString() {

  34. return "UserRoleDO{" +

  35. "id=" + id +

  36. ", userId=" + userId +

  37. ", roleId=" + roleId +

  38. '}';

  39. }

  40. }

RoleMenu.java

 
  1. package com.bootdo.system.domain;

  2.  
  3. public class RoleMenuDO {

  4. private Long id;

  5. private Long roleId;

  6. private Long menuId;

  7.  
  8. public Long getId() {

  9. return id;

  10. }

  11. public void setId(Long id) {

  12. this.id = id;

  13. }

  14. public Long getRoleId() {

  15. return roleId;

  16. }

  17. public void setRoleId(Long roleId) {

  18. this.roleId = roleId;

  19. }

  20. public Long getMenuId() {

  21. return menuId;

  22. }

  23. public void setMenuId(Long menuId) {

  24. this.menuId = menuId;

  25. }

  26.  
  27. @Override

  28. public String toString() {

  29. return "RoleMenuDO{" +

  30. "id=" + id +

  31. ", roleId=" + roleId +

  32. ", menuId=" + menuId +

  33. '}';

  34. }

  35. }

3. Shiro 配置,相当于XML里的配置

 
  1. package com.bootdo.system.config;

  2.  
  3. import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;

  4. import com.bootdo.system.shiro.UserRealm;

  5. import org.apache.shiro.cache.ehcache.EhCacheManager;

  6. import org.apache.shiro.mgt.SecurityManager;

  7. import org.apache.shiro.session.SessionListener;

  8. import org.apache.shiro.session.mgt.SessionManager;

  9. import org.apache.shiro.session.mgt.eis.MemorySessionDAO;

  10. import org.apache.shiro.session.mgt.eis.SessionDAO;

  11. import org.apache.shiro.spring.LifecycleBeanPostProcessor;

  12. import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;

  13. import org.apache.shiro.spring.web.ShiroFilterFactoryBean;

  14. import org.apache.shiro.web.mgt.DefaultWebSecurityManager;

  15. import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;

  16. import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;

  17. import org.springframework.beans.factory.annotation.Qualifier;

  18. import org.springframework.context.annotation.Bean;

  19. import org.springframework.context.annotation.Configuration;

  20.  
  21. import java.util.ArrayList;

  22. import java.util.Collection;

  23. import java.util.LinkedHashMap;

  24.  
  25. @Configuration

  26. public class ShiroConfig {

  27. @Bean

  28. public EhCacheManager getEhCacheManager() {

  29. EhCacheManager em = new EhCacheManager();

  30. em.setCacheManagerConfigFile("classpath:config/ehcache.xml");

  31. return em;

  32. }

  33.  
  34. @Bean

  35. UserRealm userRealm(EhCacheManager cacheManager) {

  36. UserRealm userRealm = new UserRealm();

  37. userRealm.setCacheManager(cacheManager);

  38. return userRealm;

  39. }

  40. @Bean

  41. SessionDAO sessionDAO() {

  42. MemorySessionDAO sessionDAO = new MemorySessionDAO();

  43. return sessionDAO;

  44. }

  45.  
  46. @Bean

  47. public SessionManager sessionManager() {

  48. DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();

  49. Collection<SessionListener> listeners = new ArrayList<SessionListener>();

  50. listeners.add(new BDSessionListener());

  51. sessionManager.setSessionListeners(listeners);

  52. sessionManager.setSessionDAO(sessionDAO());

  53. return sessionManager;

  54. }

  55.  
  56. @Bean

  57. SecurityManager securityManager(UserRealm userRealm) {

  58. DefaultWebSecurityManager manager = new DefaultWebSecurityManager();

  59. manager.setRealm(userRealm);

  60. manager.setCacheManager(getEhCacheManager());

  61. manager.setSessionManager(sessionManager());

  62. return manager;

  63. }

  64.  
  65. @Bean

  66. ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {

  67. ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

  68. shiroFilterFactoryBean.setSecurityManager(securityManager);

  69. shiroFilterFactoryBean.setLoginUrl("/login");

  70. shiroFilterFactoryBean.setSuccessUrl("/index");

  71. shiroFilterFactoryBean.setUnauthorizedUrl("/403");

 
  1. //配置访问权限控制规则

  2. LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();

  3. filterChainDefinitionMap.put("/css/**", "anon"); //表示可以匿名访问

  4. filterChainDefinitionMap.put("/js/**", "anon");

  5. filterChainDefinitionMap.put("/fonts/**", "anon");

  6. filterChainDefinitionMap.put("/img/**", "anon");

  7. filterChainDefinitionMap.put("/docs/**", "anon");

  8. filterChainDefinitionMap.put("/druid/**", "anon");

  9. filterChainDefinitionMap.put("/upload/**", "anon");

  10. filterChainDefinitionMap.put("/files/**", "anon");

  11. filterChainDefinitionMap.put("/logout", "logout");

  12. filterChainDefinitionMap.put("/", "anon");

  13. filterChainDefinitionMap.put("/blog", "anon");

  14. filterChainDefinitionMap.put("/blog/open/**", "anon");

  15. filterChainDefinitionMap.put("/**", "authc"); //表示需要认证才可以访问

  16. shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

  17. return shiroFilterFactoryBean;

  18. }

  19.  
  20. @Bean("lifecycleBeanPostProcessor")

  21. public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {

  22. return new LifecycleBeanPostProcessor();

  23. }

  24.  
  25. @Bean

  26. public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {

  27. DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();

  28. proxyCreator.setProxyTargetClass(true);

  29. return proxyCreator;

  30. }

  31.  
  32. @Bean

  33. public ShiroDialect shiroDialect() {

  34. return new ShiroDialect();

  35. }

  36.  
  37. @Bean

  38. public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(

  39. @Qualifier("securityManager") SecurityManager securityManager) {

  40. AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();

  41. authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);

  42. return authorizationAttributeSourceAdvisor;

  43. }

  44.  
  45. }

4. Realm方法,实现认证和授权

 
  1. package com.bootdo.system.shiro;

  2.  
  3. import java.util.HashMap;

  4. import java.util.Map;

  5. import java.util.Set;

  6.  
  7. import com.bootdo.common.config.ApplicationContextRegister;

  8. import org.apache.shiro.authc.AuthenticationException;

  9. import org.apache.shiro.authc.AuthenticationInfo;

  10. import org.apache.shiro.authc.AuthenticationToken;

  11. import org.apache.shiro.authc.IncorrectCredentialsException;

  12. import org.apache.shiro.authc.LockedAccountException;

  13. import org.apache.shiro.authc.SimpleAuthenticationInfo;

  14. import org.apache.shiro.authc.UnknownAccountException;

  15. import org.apache.shiro.authz.AuthorizationInfo;

  16. import org.apache.shiro.authz.SimpleAuthorizationInfo;

  17. import org.apache.shiro.realm.AuthorizingRealm;

  18. import org.apache.shiro.subject.PrincipalCollection;

  19. import org.springframework.beans.factory.annotation.Autowired;

  20.  
  21. import com.bootdo.common.utils.ShiroUtils;

  22. import com.bootdo.system.dao.UserDao;

  23. import com.bootdo.system.domain.UserDO;

  24. import com.bootdo.system.service.MenuService;

  25.  
  26. public class UserRealm extends AuthorizingRealm {

  27. /* @Autowired

  28. UserDao userMapper;

  29. @Autowired

  30. MenuService menuService;*/

  31.  
  32. //授权

  33. @Override

  34. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {

  35. Long userId = ShiroUtils.getUserId();

  36. MenuService menuService = ApplicationContextRegister.getBean(MenuService.class);

  37. Set<String> perms = menuService.listPerms(userId);

  38. SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

  39. info.setStringPermissions(perms);

  40. return info;

  41. }

  42.  
  43. //认证

  44. @Override

  45. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

  46. String username = (String) token.getPrincipal();

  47. Map<String, Object> map = new HashMap<>(16);

  48. map.put("username", username);

  49. String password = new String((char[]) token.getCredentials());

  50.  
  51. UserDao userMapper = ApplicationContextRegister.getBean(UserDao.class);

  52. // 查询用户信息

  53. UserDO user = userMapper.list(map).get(0);

  54.  
  55. // 账号不存在

  56. if (user == null) {

  57. throw new UnknownAccountException("账号或密码不正确");

  58. }

  59.  
  60. // 密码错误

  61. if (!password.equals(user.getPassword())) {

  62. throw new IncorrectCredentialsException("账号或密码不正确");

  63. }

  64.  
  65. // 账号锁定

  66. if (user.getStatus() == 0) {

  67. throw new LockedAccountException("账号已被锁定,请联系管理员");

  68. }

  69. SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());

  70. return info;

  71. }

  72.  
  73. }

5.  接下来就是controller和页面了

LoginController.java

 
  1. package com.bootdo.system.controller;

  2.  
  3. import com.bootdo.common.annotation.Log;

  4. import com.bootdo.common.controller.BaseController;

  5. import com.bootdo.common.domain.Tree;

  6. import com.bootdo.common.utils.MD5Utils;

  7. import com.bootdo.common.utils.R;

  8. import com.bootdo.common.utils.ShiroUtils;

  9. import com.bootdo.system.domain.MenuDO;

  10. import com.bootdo.system.service.MenuService;

  11. import org.apache.shiro.SecurityUtils;

  12. import org.apache.shiro.authc.AuthenticationException;

  13. import org.apache.shiro.authc.UsernamePasswordToken;

  14. import org.apache.shiro.subject.Subject;

  15. import org.slf4j.Logger;

  16. import org.slf4j.LoggerFactory;

  17. import org.springframework.beans.factory.annotation.Autowired;

  18. import org.springframework.stereotype.Controller;

  19. import org.springframework.ui.Model;

  20. import org.springframework.web.bind.annotation.GetMapping;

  21. import org.springframework.web.bind.annotation.PostMapping;

  22. import org.springframework.web.bind.annotation.ResponseBody;

  23.  
  24. import java.util.List;

  25.  
  26. @Controller

  27. public class LoginController extends BaseController {

  28. private final Logger logger = LoggerFactory.getLogger(this.getClass());

  29.  
  30. @Autowired

  31. MenuService menuService;

  32.  
  33. @GetMapping({ "/", "" })

  34. String welcome(Model model) {

  35. return "redirect:/blog";

  36. }

  37.  
  38. @Log("请求访问主页")

  39. @GetMapping({ "/index" })

  40. String index(Model model) {

  41. List<Tree<MenuDO>> menus = menuService.listMenuTree(getUserId());

  42. model.addAttribute("menus", menus);

  43. model.addAttribute("name", getUser().getName());

  44. model.addAttribute("username", getUser().getUsername());

  45. return "index_v1";

  46. }

  47.  
  48. @GetMapping("/login")

  49. String login() {

  50. return "login";

  51. }

  52.  
  53. @Log("登录")

  54. @PostMapping("/login")

  55. @ResponseBody

  56. R ajaxLogin(String username, String password) {

  57. password = MD5Utils.encrypt(username, password);

  58. UsernamePasswordToken token = new UsernamePasswordToken(username, password);

  59. Subject subject = SecurityUtils.getSubject();

  60. try {

  61. subject.login(token);

  62. return R.ok();

  63. } catch (AuthenticationException e) {

  64. return R.error("用户或密码错误");

  65. }

  66. }

  67.  
  68. @GetMapping("/logout")

  69. String logout() {

  70. ShiroUtils.logout();

  71. return "redirect:/login";

  72. }

  73.  
  74. @GetMapping("/main")

  75. String main() {

  76. return "main";

  77. }

  78.  
  79. @GetMapping("/403")

  80. String error403() {

  81. return "403";

  82. }

  83.  
  84. }


login.html

 
  1. <div>

  2. <form id="signupForm">

  3. <h3 class="text-center">用户登录</h3>

  4. <input type="text" name="username" class="form-control uname"

  5. value="admin"/>

  6. <input type="password" name="password"

  7. class="form-control pword m-b" value="111111"/>

  8. <button class="btn btn-login btn-block">登录</button>

  9.  
  10. </form>

  11. </div>

以上是Spring Boot 整合Shiro的几大要素了,接下来就可以测试了,在没有登录的情况下,访问主页的时候会跳到登录的页面,而登录不同的用户也会随着用户所拥有的角色不同而显示不同的模块。

猜你喜欢

转载自blog.csdn.net/xinzi11243094/article/details/81133219
今日推荐