上一篇文章,实现了用户验证 查看,接下来实现下权限控制

权限控制,是管理资源访问的过程,用于对用户进行的操作授权,证明该用户是否允许进行当前操作,如访问某个链接,某个资源文件等

Apache Shiro 通过继承AuthorizingRealm自定义实现ShiroRealm类,实现 doGetAuthenticationInfo()方法完成用户认证,实现doGetAuthorizationInfo()方法完成权限控制

ShiroRealm 涉及到: 
  principal:主体,就是登陆的当前用户类型的数据实体 
  credentials:凭证,用户的密码,具体加密方式用户自己实现,什么都不做就是原文

1.数据库

shiro本身只提供拦截路由,具体的数据源则由用户自己提供

使用RBAC(Role-Based Access Control,基于角色的访问控制)设计用户,角色和权限间的关系

表结构

用户表user

  1. CREATE TABLE `user` (
  2. `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  3. `account` varchar(64) NOT NULL COMMENT '账号',
  4. `password` char(32) NOT NULL COMMENT '密码',
  5. `email` varchar(50) NOT NULL COMMENT '邮箱',
  6. `status` tinyint(1) DEFAULT '' COMMENT '状态 1-正常,0-禁用,-1-删除',
  7. `create_time` int(11) unsigned NOT NULL COMMENT '添加时间',
  8. `last_login_time` int(11) unsigned DEFAULT '' COMMENT '上次登陆时间',
  9. `last_login_ip` varchar(40) DEFAULT NULL COMMENT '上次登录IP',
  10. `login_count` mediumint(8) unsigned DEFAULT '' COMMENT '登陆次数',
  11. PRIMARY KEY (`id`),
  12. UNIQUE KEY `account` (`account`)
  13. ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='管理员';
  14.  
  15. -- ----------------------------
  16. -- Records of user
  17. -- ----------------------------
  18. INSERT INTO `user` VALUES ('', 'super', 'ba98ee766e18d8352c9ad4add8387d54', 'z11qq118@126.com', '', '', '', '', '');
  19. INSERT INTO `user` VALUES ('', 'superadmin', 'e2dfe8256580c9d514863979f86b43b6', 'z11z13@126.com1', '', '', '', '127.0.0.1', '');
  20. INSERT INTO `user` VALUES ('', 'manager', '0da1810a78a0a6134d4535b995df8e89', '123@qq.com', '', '', '', '', '');

角色表role

  1. CREATE TABLE `role` (
  2. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  3. `name` varchar(100) DEFAULT NULL COMMENT '角色名称',
  4. `memo` varchar(100) DEFAULT NULL COMMENT '角色描述',
  5. PRIMARY KEY (`id`)
  6. ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
  7.  
  8. -- ----------------------------
  9. -- Records of role
  10. -- ----------------------------
  11. INSERT INTO `role` VALUES ('', 'admin', '超级管理员');
  12. INSERT INTO `role` VALUES ('', 'test', '测试账户');

用户角色关联表user_role

  1. CREATE TABLE `user_role` (
  2. `uid` int(10) DEFAULT NULL COMMENT '用户id',
  3. `rid` int(10) DEFAULT NULL COMMENT '角色id'
  4. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  5.  
  6. -- ----------------------------
  7. -- Records of user_role
  8. -- ----------------------------
  9. INSERT INTO `user_role` VALUES ('', '');
  10. INSERT INTO `user_role` VALUES ('', '');

权限表permission

  1. CREATE TABLE `permission` (
  2. `id` int(10) NOT NULL,
  3. `url` varchar(255) DEFAULT NULL COMMENT 'url地址',
  4. `name` varchar(100) DEFAULT NULL COMMENT 'url描述',
  5. PRIMARY KEY (`id`)
  6. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  7.  
  8. -- ----------------------------
  9. -- Records of permission
  10. -- ----------------------------
  11. INSERT INTO `permission` VALUES ('', '/user', 'user:user');
  12. INSERT INTO `permission` VALUES ('', '/user/add', 'user:add');
  13. INSERT INTO `permission` VALUES ('', '/user/delete', 'user:delete');

权限角色关联表role_permission

  1. CREATE TABLE `role_permission` (
  2. `rid` int(10) DEFAULT NULL COMMENT '角色id',
  3. `pid` int(10) DEFAULT NULL COMMENT '权限id'
  4. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  5.  
  6. -- ----------------------------
  7. -- Records of role_permission
  8. -- ----------------------------
  9. INSERT INTO `role_permission` VALUES ('', '');
  10. INSERT INTO `role_permission` VALUES ('', '');
  11. INSERT INTO `role_permission` VALUES ('', '');
  12. INSERT INTO `role_permission` VALUES ('', '');

2.数据层

修改mybatis-generator.xml中的tableName和domainObjectName,自动生成上面上面表的相关代码再进行添加或修改

  1. <table tableName="USER" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
  2. <generatedKey column="id" sqlStatement="mysql" identity="true"/>
  3. </table>

  (1)User

    User

  1. package com.sfn.bms.system.model;
  2.  
  3. import java.io.Serializable;
  4. import javax.persistence.*;
  5.  
  6. public class User implements Serializable {
  7. @Id
  8. @GeneratedValue(strategy = GenerationType.IDENTITY)
  9. private Short id;
  10.  
  11. /**
  12. * 账号
  13. */
  14. private String account;
  15.  
  16. /**
  17. * 密码
  18. */
  19. private String password;
  20.  
  21. /**
  22. * 邮箱
  23. */
  24. private String email;
  25.  
  26. /**
  27. * 状态 1-正常,0-禁用,-1-删除
  28. */
  29. private Boolean status;
  30.  
  31. /**
  32. * 添加时间
  33. */
  34. @Column(name = "create_time")
  35. private Integer createTime;
  36.  
  37. /**
  38. * 上次登陆时间
  39. */
  40. @Column(name = "last_login_time")
  41. private Integer lastLoginTime;
  42.  
  43. /**
  44. * 上次登录IP
  45. */
  46. @Column(name = "last_login_ip")
  47. private String lastLoginIp;
  48.  
  49. /**
  50. * 登陆次数
  51. */
  52. @Column(name = "login_count")
  53. private Integer loginCount;
  54.  
  55. private static final long serialVersionUID = 1L;
  56.  
  57. /**
  58. * @return id
  59. */
  60. public Short getId() {
  61. return id;
  62. }
  63.  
  64. /**
  65. * @param id
  66. */
  67. public void setId(Short id) {
  68. this.id = id;
  69. }
  70.  
  71. /**
  72. * 获取账号
  73. *
  74. * @return account - 账号
  75. */
  76. public String getAccount() {
  77. return account;
  78. }
  79.  
  80. /**
  81. * 设置账号
  82. *
  83. * @param account 账号
  84. */
  85. public void setAccount(String account) {
  86. this.account = account == null ? null : account.trim();
  87. }
  88.  
  89. /**
  90. * 获取密码
  91. *
  92. * @return password - 密码
  93. */
  94. public String getPassword() {
  95. return password;
  96. }
  97.  
  98. /**
  99. * 设置密码
  100. *
  101. * @param password 密码
  102. */
  103. public void setPassword(String password) {
  104. this.password = password == null ? null : password.trim();
  105. }
  106.  
  107. /**
  108. * 获取邮箱
  109. *
  110. * @return email - 邮箱
  111. */
  112. public String getEmail() {
  113. return email;
  114. }
  115.  
  116. /**
  117. * 设置邮箱
  118. *
  119. * @param email 邮箱
  120. */
  121. public void setEmail(String email) {
  122. this.email = email == null ? null : email.trim();
  123. }
  124.  
  125. /**
  126. * 获取状态 1-正常,0-禁用,-1-删除
  127. *
  128. * @return status - 状态 1-正常,0-禁用,-1-删除
  129. */
  130. public Boolean getStatus() {
  131. return status;
  132. }
  133.  
  134. /**
  135. * 设置状态 1-正常,0-禁用,-1-删除
  136. *
  137. * @param status 状态 1-正常,0-禁用,-1-删除
  138. */
  139. public void setStatus(Boolean status) {
  140. this.status = status;
  141. }
  142.  
  143. /**
  144. * 获取添加时间
  145. *
  146. * @return create_time - 添加时间
  147. */
  148. public Integer getCreateTime() {
  149. return createTime;
  150. }
  151.  
  152. /**
  153. * 设置添加时间
  154. *
  155. * @param createTime 添加时间
  156. */
  157. public void setCreateTime(Integer createTime) {
  158. this.createTime = createTime;
  159. }
  160.  
  161. /**
  162. * 获取上次登陆时间
  163. *
  164. * @return last_login_time - 上次登陆时间
  165. */
  166. public Integer getLastLoginTime() {
  167. return lastLoginTime;
  168. }
  169.  
  170. /**
  171. * 设置上次登陆时间
  172. *
  173. * @param lastLoginTime 上次登陆时间
  174. */
  175. public void setLastLoginTime(Integer lastLoginTime) {
  176. this.lastLoginTime = lastLoginTime;
  177. }
  178.  
  179. /**
  180. * 获取上次登录IP
  181. *
  182. * @return last_login_ip - 上次登录IP
  183. */
  184. public String getLastLoginIp() {
  185. return lastLoginIp;
  186. }
  187.  
  188. /**
  189. * 设置上次登录IP
  190. *
  191. * @param lastLoginIp 上次登录IP
  192. */
  193. public void setLastLoginIp(String lastLoginIp) {
  194. this.lastLoginIp = lastLoginIp == null ? null : lastLoginIp.trim();
  195. }
  196.  
  197. /**
  198. * 获取登陆次数
  199. *
  200. * @return login_count - 登陆次数
  201. */
  202. public Integer getLoginCount() {
  203. return loginCount;
  204. }
  205.  
  206. /**
  207. * 设置登陆次数
  208. *
  209. * @param loginCount 登陆次数
  210. */
  211. public void setLoginCount(Integer loginCount) {
  212. this.loginCount = loginCount;
  213. }
  214. }

    UserMapper

  1. package com.sfn.bms.system.mapper;
  2.  
  3. import com.sfn.bms.common.config.MyMapper;
  4. import com.sfn.bms.system.model.User;
  5.  
  6. public interface UserMapper extends MyMapper<User> {
  7. }

    UserService(新增)

  1. package com.sfn.bms.system.service;
  2.  
  3. import com.sfn.bms.common.service.IService;
  4. import com.sfn.bms.system.model.User;
  5.  
  6. public interface UserService extends IService<User> {
  7. User findByAccount(String account);
  8. }

    UserServiceImpl (新增)

  1. package com.sfn.bms.system.service.impl;
  2.  
  3. import com.sfn.bms.common.service.impl.BaseService;
  4. import com.sfn.bms.system.model.User;
  5. import com.sfn.bms.system.service.UserService;
  6. import org.springframework.stereotype.Repository;
  7. import tk.mybatis.mapper.entity.Example;
  8.  
  9. import java.util.List;
  10.  
  11. @Repository("userService")
  12. public class UserServiceImpl extends BaseService<User> implements UserService {
  13. @Override
  14. public User findByAccount(String account) {
  15. Example example = new Example(User.class);
  16. example.createCriteria().andCondition("lower(account)=", account.toLowerCase());
  17. List<User> list = this.selectByExample(example);
  18. return list.isEmpty() ? null : list.get(0);
  19. }
  20.  
  21. }

    UserMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.sfn.bms.system.mapper.UserMapper">
  4. <resultMap id="BaseResultMap" type="com.sfn.bms.system.model.User">
  5. <!--
  6. WARNING - @mbg.generated
  7. -->
  8. <id column="id" jdbcType="SMALLINT" property="id" />
  9. <result column="account" jdbcType="VARCHAR" property="account" />
  10. <result column="password" jdbcType="CHAR" property="password" />
  11. <result column="email" jdbcType="VARCHAR" property="email" />
  12. <result column="status" jdbcType="BIT" property="status" />
  13. <result column="create_time" jdbcType="INTEGER" property="createTime" />
  14. <result column="last_login_time" jdbcType="INTEGER" property="lastLoginTime" />
  15. <result column="last_login_ip" jdbcType="VARCHAR" property="lastLoginIp" />
  16. <result column="login_count" jdbcType="INTEGER" property="loginCount" />
  17. </resultMap>
  18.  
  19. </mapper>

  (2)Role

    Role

  1. package com.sfn.bms.system.model;
  2.  
  3. import java.io.Serializable;
  4. import javax.persistence.*;
  5.  
  6. public class Role implements Serializable {
  7. @Id
  8. @GeneratedValue(strategy = GenerationType.IDENTITY)
  9. private Integer id;
  10.  
  11. /**
  12. * 角色名称
  13. */
  14. private String name;
  15.  
  16. /**
  17. * 角色描述
  18. */
  19. private String memo;
  20.  
  21. private static final long serialVersionUID = 1L;
  22.  
  23. /**
  24. * @return id
  25. */
  26. public Integer getId() {
  27. return id;
  28. }
  29.  
  30. /**
  31. * @param id
  32. */
  33. public void setId(Integer id) {
  34. this.id = id;
  35. }
  36.  
  37. /**
  38. * 获取角色名称
  39. *
  40. * @return name - 角色名称
  41. */
  42. public String getName() {
  43. return name;
  44. }
  45.  
  46. /**
  47. * 设置角色名称
  48. *
  49. * @param name 角色名称
  50. */
  51. public void setName(String name) {
  52. this.name = name == null ? null : name.trim();
  53. }
  54.  
  55. /**
  56. * 获取角色描述
  57. *
  58. * @return memo - 角色描述
  59. */
  60. public String getMemo() {
  61. return memo;
  62. }
  63.  
  64. /**
  65. * 设置角色描述
  66. *
  67. * @param memo 角色描述
  68. */
  69. public void setMemo(String memo) {
  70. this.memo = memo == null ? null : memo.trim();
  71. }
  72. }

    RoleMapper(修改)

  1. package com.sfn.bms.system.mapper;
  2.  
  3. import com.sfn.bms.common.config.MyMapper;
  4. import com.sfn.bms.system.model.Role;
  5.  
  6. import java.util.List;
  7.  
  8. public interface RoleMapper extends MyMapper<Role> {
  9. List<Role> findUserRole(String account);
  10. }

    RoleService (新增)

  1. package com.sfn.bms.system.service;
  2.  
  3. import com.sfn.bms.common.service.IService;
  4. import com.sfn.bms.system.model.Role;
  5.  
  6. import java.util.List;
  7.  
  8. public interface RoleService extends IService<Role> {
  9. List<Role> findUserRole(String account);
  10. }

    RoleServiceImpl (新增)

  1. package com.sfn.bms.system.service.impl;
  2.  
  3. import com.sfn.bms.common.service.impl.BaseService;
  4. import com.sfn.bms.system.mapper.RoleMapper;
  5. import com.sfn.bms.system.model.Role;
  6. import com.sfn.bms.system.service.RoleService;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Service;
  9. import org.springframework.transaction.annotation.Propagation;
  10. import org.springframework.transaction.annotation.Transactional;
  11.  
  12. import java.util.List;
  13.  
  14. @Service("RoleService")
  15. @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
  16. public class RoleServiceImpl extends BaseService<Role> implements RoleService {
  17.  
  18. @Autowired
  19. private RoleMapper mapper;
  20.  
  21. @Override
  22. public List<Role> findUserRole(String account) {
  23. return this.mapper.findUserRole(account);
  24. }
  25. }

    RoleMapper.xml(修改)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.sfn.bms.system.mapper.RoleMapper">
  4. <resultMap id="BaseResultMap" type="com.sfn.bms.system.model.Role">
  5. <!--
  6. WARNING - @mbg.generated
  7. -->
  8. <id column="id" jdbcType="INTEGER" property="id" />
  9. <result column="name" jdbcType="VARCHAR" property="name" />
  10. <result column="memo" jdbcType="VARCHAR" property="memo" />
  11. </resultMap>
  12. <select id="findUserRole" resultMap="BaseResultMap">
  13. select r.* from role r
  14. left join user_role ur on(r.id = ur.rid)
  15. left join user u on(u.id = ur.uid)
  16. where u.account = #{account}
  17. </select>
  18. </mapper>

  (3)Permission    

    Permission

  1. package com.sfn.bms.system.model;
  2.  
  3. import java.io.Serializable;
  4. import javax.persistence.*;
  5.  
  6. public class Permission implements Serializable {
  7. @Id
  8. @GeneratedValue(strategy = GenerationType.IDENTITY)
  9. private Integer id;
  10.  
  11. /**
  12. * url地址
  13. */
  14. private String url;
  15.  
  16. /**
  17. * url描述
  18. */
  19. private String name;
  20.  
  21. private static final long serialVersionUID = 1L;
  22.  
  23. /**
  24. * @return id
  25. */
  26. public Integer getId() {
  27. return id;
  28. }
  29.  
  30. /**
  31. * @param id
  32. */
  33. public void setId(Integer id) {
  34. this.id = id;
  35. }
  36.  
  37. /**
  38. * 获取url地址
  39. *
  40. * @return url - url地址
  41. */
  42. public String getUrl() {
  43. return url;
  44. }
  45.  
  46. /**
  47. * 设置url地址
  48. *
  49. * @param url url地址
  50. */
  51. public void setUrl(String url) {
  52. this.url = url == null ? null : url.trim();
  53. }
  54.  
  55. /**
  56. * 获取url描述
  57. *
  58. * @return name - url描述
  59. */
  60. public String getName() {
  61. return name;
  62. }
  63.  
  64. /**
  65. * 设置url描述
  66. *
  67. * @param name url描述
  68. */
  69. public void setName(String name) {
  70. this.name = name == null ? null : name.trim();
  71. }
  72. }

    PermissionMapper(修改)

  1. package com.sfn.bms.system.mapper;
  2.  
  3. import com.sfn.bms.common.config.MyMapper;
  4. import com.sfn.bms.system.model.Permission;
  5.  
  6. import java.util.List;
  7.  
  8. public interface PermissionMapper extends MyMapper<Permission> {
  9. List<Permission> findUserPermissions(String account);
  10. }

    PermissionService (新增)

  1. package com.sfn.bms.system.service;
  2.  
  3. import com.sfn.bms.common.service.IService;
  4. import com.sfn.bms.system.model.Permission;
  5.  
  6. import java.util.List;
  7.  
  8. public interface PermissionService extends IService<Permission> {
  9. List<Permission> findUserPermissions(String account);
  10. }

    PermissionServiceImpl (新增)

  1. package com.sfn.bms.system.service.impl;
  2.  
  3. import com.sfn.bms.common.service.impl.BaseService;
  4. import com.sfn.bms.system.mapper.PermissionMapper;
  5. import com.sfn.bms.system.model.Permission;
  6. import com.sfn.bms.system.service.PermissionService;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Service;
  9. import org.springframework.transaction.annotation.Propagation;
  10. import org.springframework.transaction.annotation.Transactional;
  11.  
  12. import java.util.List;
  13.  
  14. @Service("PermissionService")
  15. @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
  16. public class PermissionServiceImpl extends BaseService<Permission> implements PermissionService {
  17. @Autowired
  18. private PermissionMapper mapper;
  19. @Override
  20. public List<Permission> findUserPermissions(String account) {
  21. return this.mapper.findUserPermissions(account);
  22. }
  23. }

    PermissionMapper.xml(修改)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.sfn.bms.system.mapper.PermissionMapper">
  4. <resultMap id="BaseResultMap" type="com.sfn.bms.system.model.Permission">
  5. <!--
  6. WARNING - @mbg.generated
  7. -->
  8. <id column="id" jdbcType="INTEGER" property="id" />
  9. <result column="url" jdbcType="VARCHAR" property="url" />
  10. <result column="name" jdbcType="VARCHAR" property="name" />
  11. </resultMap>
  12. <select id="findUserPermissions" resultMap="BaseResultMap">
  13. select p.* from role r
  14. left join user_role ur on(r.id = ur.rid)
  15. left join user u on(u.id = ur.uid)
  16. left join role_permission rp on(rp.rid = r.id)
  17. left join permission p on(p.id = rp.pid )
  18. where u.account = #{account} and p.name is not null and p.name &lt;&gt; ''
  19. </select>
  20. </mapper>

  (4)UserRole

    UserRole

  1. package com.sfn.bms.system.model;
  2.  
  3. import java.io.Serializable;
  4. import javax.persistence.*;
  5.  
  6. @Table(name = "user_role")
  7. public class UserRole implements Serializable {
  8. /**
  9. * 用户id
  10. */
  11. private Integer uid;
  12.  
  13. /**
  14. * 角色id
  15. */
  16. private Integer rid;
  17.  
  18. private static final long serialVersionUID = 1L;
  19.  
  20. /**
  21. * 获取用户id
  22. *
  23. * @return uid - 用户id
  24. */
  25. public Integer getUid() {
  26. return uid;
  27. }
  28.  
  29. /**
  30. * 设置用户id
  31. *
  32. * @param uid 用户id
  33. */
  34. public void setUid(Integer uid) {
  35. this.uid = uid;
  36. }
  37.  
  38. /**
  39. * 获取角色id
  40. *
  41. * @return rid - 角色id
  42. */
  43. public Integer getRid() {
  44. return rid;
  45. }
  46.  
  47. /**
  48. * 设置角色id
  49. *
  50. * @param rid 角色id
  51. */
  52. public void setRid(Integer rid) {
  53. this.rid = rid;
  54. }
  55. }

    UserRoleMapper

  1. package com.sfn.bms.system.mapper;
  2.  
  3. import com.sfn.bms.common.config.MyMapper;
  4. import com.sfn.bms.system.model.UserRole;
  5.  
  6. public interface UserRoleMapper extends MyMapper<UserRole> {
  7. }

    UserRoleMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.sfn.bms.system.mapper.UserRoleMapper">
  4. <resultMap id="BaseResultMap" type="com.sfn.bms.system.model.UserRole">
  5. <!--
  6. WARNING - @mbg.generated
  7. -->
  8. <result column="uid" jdbcType="INTEGER" property="uid" />
  9. <result column="rid" jdbcType="INTEGER" property="rid" />
  10. </resultMap>
  11. </mapper>

  (5)RolePermission  

    RolePermission

  1. package com.sfn.bms.system.model;
  2.  
  3. import java.io.Serializable;
  4. import javax.persistence.*;
  5.  
  6. @Table(name = "role_permission")
  7. public class RolePermission implements Serializable {
  8. /**
  9. * 角色id
  10. */
  11. private Integer rid;
  12.  
  13. /**
  14. * 权限id
  15. */
  16. private Integer pid;
  17.  
  18. private static final long serialVersionUID = 1L;
  19.  
  20. /**
  21. * 获取角色id
  22. *
  23. * @return rid - 角色id
  24. */
  25. public Integer getRid() {
  26. return rid;
  27. }
  28.  
  29. /**
  30. * 设置角色id
  31. *
  32. * @param rid 角色id
  33. */
  34. public void setRid(Integer rid) {
  35. this.rid = rid;
  36. }
  37.  
  38. /**
  39. * 获取权限id
  40. *
  41. * @return pid - 权限id
  42. */
  43. public Integer getPid() {
  44. return pid;
  45. }
  46.  
  47. /**
  48. * 设置权限id
  49. *
  50. * @param pid 权限id
  51. */
  52. public void setPid(Integer pid) {
  53. this.pid = pid;
  54. }
  55. }

  RolePermissionMapper

  1. package com.sfn.bms.system.mapper;
  2.  
  3. import com.sfn.bms.common.config.MyMapper;
  4. import com.sfn.bms.system.model.RolePermission;
  5.  
  6. public interface RolePermissionMapper extends MyMapper<RolePermission> {
  7. }

  RolePermissionMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.sfn.bms.system.mapper.RolePermissionMapper">
  4. <resultMap id="BaseResultMap" type="com.sfn.bms.system.model.RolePermission">
  5. <!--
  6. WARNING - @mbg.generated
  7. -->
  8. <result column="rid" jdbcType="INTEGER" property="rid" />
  9. <result column="pid" jdbcType="INTEGER" property="pid" />
  10. </resultMap>
  11. </mapper>

3.配置shiro相关文件

  (1)Realm

  1. package com.sfn.bms.common.shiro;
  2. import com.sfn.bms.system.model.Permission;
  3. import com.sfn.bms.system.model.Role;
  4. import com.sfn.bms.system.model.User;
  5. import com.sfn.bms.system.service.PermissionService;
  6. import com.sfn.bms.system.service.RoleService;
  7. import com.sfn.bms.system.service.UserService;
  8. import org.apache.shiro.SecurityUtils;
  9. import org.apache.shiro.authc.*;
  10. import org.apache.shiro.authz.AuthorizationInfo;
  11. import org.apache.shiro.authz.SimpleAuthorizationInfo;
  12. import org.apache.shiro.realm.AuthorizingRealm;
  13. import org.apache.shiro.subject.PrincipalCollection;
  14. import org.apache.shiro.subject.SimplePrincipalCollection;
  15. import org.springframework.beans.factory.annotation.Autowired;
  16. import org.springframework.stereotype.Component;
  17.  
  18. import java.util.HashSet;
  19. import java.util.List;
  20. import java.util.Set;
  21. import java.util.stream.Collectors;
  22.  
  23. /**
  24. * 自定义实现 ShiroRealm,包含认证和授权两大模块
  25. */
  26. @Component("shiroRealm")
  27. public class MyShiroRealm extends AuthorizingRealm {
  28.  
  29. @Autowired
  30. private UserService userService;
  31.  
  32. @Autowired
  33. private RoleService roleService;
  34. @Autowired
  35. private PermissionService permissionService;
  36.  
  37. /**
  38. * 授权模块,获取用户角色和权限
  39. *
  40. * @param principal principal
  41. * @return AuthorizationInfo 权限信息
  42. */
  43. @Override
  44. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
  45.  
  46. User user = (User) SecurityUtils.getSubject().getPrincipal();
  47. String account = user.getAccount();
  48.  
  49. System.out.println("用户" + account + "获取权限-----ShiroRealm.doGetAuthorizationInfo");
  50. SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
  51.  
  52. // 获取用户角色集
  53. List<Role> roleList = this.roleService.findUserRole(account);
  54. Set<String> roleSet = roleList.stream().map(Role::getName).collect(Collectors.toSet());
  55. simpleAuthorizationInfo.setRoles(roleSet);
  56.  
  57. // 获取用户权限集
  58. List<Permission> permissionList = permissionService.findUserPermissions(account);
  59. Set<String> permissionSet = permissionList.stream().map(Permission::getName).collect(Collectors.toSet());
  60. simpleAuthorizationInfo.setStringPermissions(permissionSet);
  61.  
  62. return simpleAuthorizationInfo;
  63. }
  64.  
  65. /**
  66. * 用户认证
  67. *
  68. * @param token AuthenticationToken 身份认证 token
  69. * @return AuthenticationInfo 身份认证信息
  70. * @throws AuthenticationException 认证相关异常
  71. */
  72. @Override
  73. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  74. ……
  75. }
  76. }

  (2)ShiroConfig

    添加

  1. @Bean
  2. public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator(){
  3. DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
  4. advisorAutoProxyCreator.setProxyTargetClass(true);
  5. return advisorAutoProxyCreator;
  6. }
  7.  
  8. @Bean
  9. public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
  10. AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
  11. authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
  12. return authorizationAttributeSourceAdvisor;
  13. }

4.使用

  (1)Controller

  添加UserController

  1. package com.sfn.bms.system.controller;
  2.  
  3. import com.github.pagehelper.PageHelper;
  4. import com.github.pagehelper.PageInfo;
  5. import com.sfn.bms.system.model.Permission;
  6. import com.sfn.bms.system.model.Role;
  7. import com.sfn.bms.system.model.User;
  8. import com.sfn.bms.system.service.PermissionService;
  9. import com.sfn.bms.system.service.RoleService;
  10. import com.sfn.bms.system.service.UserService;
  11. import org.apache.shiro.authz.annotation.RequiresPermissions;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.stereotype.Controller;
  14. import org.springframework.ui.Model;
  15. import org.springframework.web.bind.annotation.GetMapping;
  16. import org.springframework.web.bind.annotation.RequestMapping;
  17. import org.springframework.web.bind.annotation.ResponseBody;
  18.  
  19. import java.util.List;
  20.  
  21. @Controller
  22. public class UserController {
  23.  
  24. @Autowired
  25. UserService userService;
  26.  
  27. @Autowired
  28. private RoleService roleService;
  29.  
  30. @Autowired
  31. private PermissionService permissionService;
  32.  
  33. @RequiresPermissions("user:user")
  34. @RequestMapping("user/list")
  35. public String userList(Model model) {
  36. model.addAttribute("value", "获取用户信息");
  37. return "user";
  38. }
  39.  
  40. @RequiresPermissions("user:add")
  41. @RequestMapping("user/add")
  42. public String userAdd(Model model) {
  43. model.addAttribute("value", "新增用户");
  44. return "user";
  45. }
  46.  
  47. @RequiresPermissions("user:delete")
  48. @RequestMapping("user/delete")
  49. public String userDelete(Model model) {
  50. model.addAttribute("value", "删除用户");
  51. return "user";
  52. }
  53.  
  54. }

  在LoginController添加/403跳转

  1. @GetMapping("/403")
  2. public String forbid() {
  3. return "403";
  4. }

  (2)前端页面

  index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>首页</title>
  6. </head>
  7. <body>
  8. <p>你好![[${user.account}]]</p>
  9. <h3>用户管理</h3>
  10. <div>
  11. <a th:href="@{/user/list}">获取用户信息</a>
  12. <a th:href="@{/user/add}">新增用户</a>
  13. <a th:href="@{/user/delete}">删除用户</a>
  14. </div>
  15. <a th:href="@{/logout}">注销</a>
  16. </body>
  17. </html>

  user.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>[[${value}]]</title>
  6. </head>
  7. <body>
  8. <p>[[${value}]]</p>
  9. <a th:href="@{/index}">返回</a>
  10. </body>
  11. </html>

  error/403.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>暂无权限</title>
  6. </head>
  7. <body>
  8. <p>您没有权限访问该资源!!</p>
  9. <a th:href="@{/index}">返回</a>
  10. </body>
  11. </html>

5.测试

启动项目,在登录页输入用户名 manager密码123456,来到主页

数据库中manager属于test角色,没有添加和删除的权限,在跳转到新增用户或删除用户时,页面会被重定向到/403

后台抛出异常org.apache.shiro.authz.AuthorizationException: Not authorized to invoke method

定义一个全局异常捕获类

  1. package com.sfn.bms.common.handler;
  2.  
  3. import com.sfn.bms.common.domian.ResponseBo;
  4. import com.sfn.bms.common.util.HttpUtils;
  5. import org.apache.shiro.authz.AuthorizationException;
  6. import org.springframework.core.Ordered;
  7. import org.springframework.core.annotation.Order;
  8. import org.springframework.web.bind.annotation.ExceptionHandler;
  9. import org.springframework.web.bind.annotation.RestControllerAdvice;
  10. import org.springframework.web.servlet.ModelAndView;
  11.  
  12. import javax.servlet.http.HttpServletRequest;
  13. @RestControllerAdvice
  14. @Order(value = Ordered.HIGHEST_PRECEDENCE)
  15. public class GlobalExceptionHandler {
  16. @ExceptionHandler(value = AuthorizationException.class)
  17. public Object handleAuthorizationException(HttpServletRequest request) {
  18. if (HttpUtils.isAjaxRequest(request)) {
  19. return ResponseBo.error("暂无权限,请联系管理员!");
  20. } else {
  21. ModelAndView mav = new ModelAndView();
  22. mav.setViewName("error/403");
  23. return mav;
  24. }
  25. }
  26. }

再次运行项目,登录后选择新增用户,页面成功重定向到/403

相关代码 地址

Spring boot后台搭建二集成Shiro权限控制的更多相关文章

  1. Spring boot后台搭建二集成Shiro实现用户验证

    上一篇文章中介绍了Shiro 查看 将Shiro集成到spring boot的步骤: (1)定义一个ShiroConfig,配置SecurityManager Bean,SecurityManager ...

  2. Spring boot后台搭建二集成Shiro添加Remember Me

    上一片文章实现了用户验证  查看 当用户成功登录后,关闭浏览器,重新打开浏览器访问http://localhost:8080,页面会跳转到登录页,因为浏览器的关闭后之前的登录已失效 Shiro提供了R ...

  3. Spring boot后台搭建二为Shiro权限控制添加缓存

    在添加权限控制后,添加方法 查看 当用户访问”获取用户信息”.”新增用户”和”删除用户”的时,后台输出打印如下信息 , Druid数据源SQL监控 为了避免频繁访问数据库获取权限信息,在Shiro中加 ...

  4. 七、spring boot 1.5.4 集成shiro+cas,实现单点登录和权限控制

    1.安装cas-server-3.5.2 官网:https://github.com/apereo/cas/releases/tag/v3.5.2 下载地址:cas-server-3.5.2-rele ...

  5. Spring boot后台搭建一使用MyBatis集成Mapper和PageHelper

    目标: 使用 Spring  boot+MyBatis+mysql 集成 Mapper 和 PageHelper,实现基本的增删改查 先建一个基本的 Spring Boot 项目开启 Spring B ...

  6. 2017.2.13 开涛shiro教程-第十二章-与Spring集成(二)shiro权限注解

    原博客地址:http://jinnianshilongnian.iteye.com/blog/2018398 根据下载的pdf学习. 第十二章-与Spring集成(二)shiro权限注解 shiro注 ...

  7. Spring Boot 2.X(二):集成 MyBatis 数据层开发

    MyBatis 简介 概述 MyBatis 是一款优秀的持久层框架,支持定制化 SQL.存储过程以及高级映射.它采用面向对象编程的方式对数据库进行 CRUD 的操作,使程序中对关系数据库的操作更方便简 ...

  8. Spring Boot(十四):spring boot整合shiro-登录认证和权限管理

    Spring Boot(十四):spring boot整合shiro-登录认证和权限管理 使用Spring Boot集成Apache Shiro.安全应该是互联网公司的一道生命线,几乎任何的公司都会涉 ...

  9. spring boot / cloud (十二) 异常统一处理进阶

    spring boot / cloud (十二) 异常统一处理进阶 前言 在spring boot / cloud (二) 规范响应格式以及统一异常处理这篇博客中已经提到了使用@ExceptionHa ...

随机推荐

  1. 动态生成16位不重复随机数、随机创建2位ID

    /** 1. * 动态生成16位不重复随机数 * * @return */ public synchronized static String generate16() { StringBuffer ...

  2. Python练习题——用列表的方法输出杨辉三角

    def main(): num = int(input('请输入行数: ')) yh = [[]] * num #创建num行空列表 for row in range(len(yh)): #遍历每一行 ...

  3. test20190903 JKlover

    100+65+100=265,T2就差了一点. 乌合之众 给出一个 n × n 的, 元素为自然数的矩阵.这个矩阵有许许多多个子矩阵, 定义它的所有子矩阵形成的集合为 S . 对于一个矩阵 k , 定 ...

  4. LeetCode 1219. Path with Maximum Gold

    原题链接在这里:https://leetcode.com/problems/path-with-maximum-gold/ 题目: In a gold mine grid of size m * n, ...

  5. HDU 6091 - Rikka with Match | 2017 Multi-University Training Contest 5

    思路来自 某FXXL 不过复杂度咋算的.. /* HDU 6091 - Rikka with Match [ 树形DP ] | 2017 Multi-University Training Conte ...

  6. 如何把上传图片时候的文件对象转换为图片的url !

    getObjectURL(file) { var url = null; if (window.createObjectURL != undefined) { url = window.createO ...

  7. Theano入门笔记1:Theano中的Graph Structure

    译自:http://deeplearning.net/software/theano/extending/graphstructures.html#graphstructures 理解Theano计算 ...

  8. [译博文]CUDA是什么

    翻译自:https://blogs.nvidia.com/blog/2012/09/10/what-is-cuda-2/ 你可能并没有意识到,GPU的应用有多广泛,它不但用于视频.游戏以及科学研究中, ...

  9. 55、Spark Streaming:updateStateByKey以及基于缓存的实时wordcount程序

    一.updateStateByKey 1.概述 SparkStreaming 7*24 小时不间断的运行,有时需要管理一些状态,比如wordCount,每个batch的数据不是独立的而是需要累加的,这 ...

  10. nodejs之express生成项目[windows平台]

    安装nvm,nvm下载地址   用于管理多个版本node,此处可省略! 安装nodejs,nodejs下载地址    淘宝镜像 安装cnpm命令,后面包可以使用cnpm命令安装,此处可省略,如果安装了 ...