经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
Spring Boot集成Shiro实现动态加载权限的完整步骤
来源:jb51  时间:2019/9/29 10:40:00  对本文有异议

一、前言

本文小编将基于 SpringBoot 集成 Shiro 实现动态uri权限,由前端vue在页面配置uri,Java后端动态刷新权限,不用重启项目,以及在页面分配给用户 角色 、 按钮 、uri 权限后,后端动态分配权限,用户无需在页面重新登录才能获取最新权限,一切权限动态加载,灵活配置

基本环境

  • spring-boot 2.1.7
  • mybatis-plus 2.1.0
  • mysql 5.7.24
  • redis 5.0.5

温馨小提示:案例demo源码附文章末尾,有需要的小伙伴们可参考哦 ~

二、SpringBoot集成Shiro

1、引入相关maven依赖

  1. <properties>
  2. <shiro-spring.version>1.4.0</shiro-spring.version>
  3. <shiro-redis.version>3.1.0</shiro-redis.version>
  4. </properties>
  5. <dependencies>
  6. <!-- AOP依赖,一定要加,否则权限拦截验证不生效 【注:系统日记也需要此依赖】 -->
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-aop</artifactId>
  10. </dependency>
  11. <!-- Redis -->
  12. <dependency>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
  15. </dependency>
  16. <!-- Shiro 核心依赖 -->
  17. <dependency>
  18. <groupId>org.apache.shiro</groupId>
  19. <artifactId>shiro-spring</artifactId>
  20. <version>${shiro-spring.version}</version>
  21. </dependency>
  22. <!-- Shiro-redis插件 -->
  23. <dependency>
  24. <groupId>org.crazycake</groupId>
  25. <artifactId>shiro-redis</artifactId>
  26. <version>${shiro-redis.version}</version>
  27. </dependency>
  28. </dependencies>

2、自定义Realm

  • doGetAuthenticationInfo:身份认证 (主要是在登录时的逻辑处理)
  • doGetAuthorizationInfo:登陆认证成功后的处理 ex: 赋予角色和权限
    【 注:用户进行权限验证时 Shiro会去缓存中找,如果查不到数据,会执行doGetAuthorizationInfo这个方法去查权限,并放入缓存中 】 -> 因此我们在前端页面分配用户权限时 执行清除shiro缓存的方法即可实现动态分配用户权限
  1. @Slf4j
  2. public class ShiroRealm extends AuthorizingRealm {
  3.  
  4. @Autowired
  5. private UserMapper userMapper;
  6. @Autowired
  7. private MenuMapper menuMapper;
  8. @Autowired
  9. private RoleMapper roleMapper;
  10.  
  11. @Override
  12. public String getName() {
  13. return "shiroRealm";
  14. }
  15.  
  16. /**
  17. * 赋予角色和权限:用户进行权限验证时 Shiro会去缓存中找,如果查不到数据,会执行这个方法去查权限,并放入缓存中
  18. */
  19. @Override
  20. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
  21. SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
  22. // 获取用户
  23. User user = (User) principalCollection.getPrimaryPrincipal();
  24. Integer userId =user.getId();
  25. // 这里可以进行授权和处理
  26. Set<String> rolesSet = new HashSet<>();
  27. Set<String> permsSet = new HashSet<>();
  28. // 获取当前用户对应的权限(这里根据业务自行查询)
  29. List<Role> roleList = roleMapper.selectRoleByUserId( userId );
  30. for (Role role:roleList) {
  31. rolesSet.add( role.getCode() );
  32. List<Menu> menuList = menuMapper.selectMenuByRoleId( role.getId() );
  33. for (Menu menu :menuList) {
  34. permsSet.add( menu.getResources() );
  35. }
  36. }
  37. //将查到的权限和角色分别传入authorizationInfo中
  38. authorizationInfo.setStringPermissions(permsSet);
  39. authorizationInfo.setRoles(rolesSet);
  40. log.info("--------------- 赋予角色和权限成功! ---------------");
  41. return authorizationInfo;
  42. }
  43.  
  44. /**
  45. * 身份认证 - 之后走上面的 授权
  46. */
  47. @Override
  48. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
  49. UsernamePasswordToken tokenInfo = (UsernamePasswordToken)authenticationToken;
  50. // 获取用户输入的账号
  51. String username = tokenInfo.getUsername();
  52. // 获取用户输入的密码
  53. String password = String.valueOf( tokenInfo.getPassword() );
  54.  
  55. // 通过username从数据库中查找 User对象,如果找到进行验证
  56. // 实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法
  57. User user = userMapper.selectUserByUsername(username);
  58. // 判断账号是否存在
  59. if (user == null) {
  60. //返回null -> shiro就会知道这是用户不存在的异常
  61. return null;
  62. }
  63. // 验证密码 【注:这里不采用shiro自身密码验证 , 采用的话会导致用户登录密码错误时,已登录的账号也会自动下线! 如果采用,移除下面的清除缓存到登录处 处理】
  64. if ( !password.equals( user.getPwd() ) ){
  65. throw new IncorrectCredentialsException("用户名或者密码错误");
  66. }
  67.  
  68. // 判断账号是否被冻结
  69. if (user.getFlag()==null|| "0".equals(user.getFlag())){
  70. throw new LockedAccountException();
  71. }
  72. /**
  73. * 进行验证 -> 注:shiro会自动验证密码
  74. * 参数1:principal -> 放对象就可以在页面任意地方拿到该对象里面的值
  75. * 参数2:hashedCredentials -> 密码
  76. * 参数3:credentialsSalt -> 设置盐值
  77. * 参数4:realmName -> 自定义的Realm
  78. */
  79. SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
  80. // 验证成功开始踢人(清除缓存和Session)
  81. ShiroUtils.deleteCache(username,true);
  82.  
  83. // 认证成功后更新token
  84. String token = ShiroUtils.getSession().getId().toString();
  85. user.setToken( token );
  86. userMapper.updateById(user);
  87. return authenticationInfo;
  88. }
  89.  
  90. }

3、Shiro配置类

  1. @Configuration
  2. public class ShiroConfig {
  3.  
  4. private final String CACHE_KEY = "shiro:cache:";
  5. private final String SESSION_KEY = "shiro:session:";
  6. /**
  7. * 默认过期时间30分钟,即在30分钟内不进行操作则清空缓存信息,页面即会提醒重新登录
  8. */
  9. private final int EXPIRE = 1800;
  10.  
  11. /**
  12. * Redis配置
  13. */
  14. @Value("${spring.redis.host}")
  15. private String host;
  16. @Value("${spring.redis.port}")
  17. private int port;
  18. @Value("${spring.redis.timeout}")
  19. private int timeout;
  20. // @Value("${spring.redis.password}")
  21. // private String password;
  22.  
  23. /**
  24. * 开启Shiro-aop注解支持:使用代理方式所以需要开启代码支持
  25. */
  26. @Bean
  27. public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
  28. AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
  29. authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
  30. return authorizationAttributeSourceAdvisor;
  31. }
  32.  
  33. /**
  34. * Shiro基础配置
  35. */
  36. @Bean
  37. public ShiroFilterFactoryBean shiroFilterFactory(SecurityManager securityManager, ShiroServiceImpl shiroConfig){
  38. ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
  39. shiroFilterFactoryBean.setSecurityManager(securityManager);
  40.  
  41. // 自定义过滤器
  42. Map<String, Filter> filtersMap = new LinkedHashMap<>();
  43. // 定义过滤器名称 【注:map里面key值对于的value要为authc才能使用自定义的过滤器】
  44. filtersMap.put( "zqPerms", new MyPermissionsAuthorizationFilter() );
  45. filtersMap.put( "zqRoles", new MyRolesAuthorizationFilter() );
  46. filtersMap.put( "token", new TokenCheckFilter() );
  47. shiroFilterFactoryBean.setFilters(filtersMap);
  48.  
  49. // 登录的路径: 如果你没有登录则会跳到这个页面中 - 如果没有设置值则会默认跳转到工程根目录下的"/login.jsp"页面 或 "/login" 映射
  50. shiroFilterFactoryBean.setLoginUrl("/api/auth/unLogin");
  51. // 登录成功后跳转的主页面 (这里没用,前端vue控制了跳转)
  52. // shiroFilterFactoryBean.setSuccessUrl("/index");
  53. // 设置没有权限时跳转的url
  54. shiroFilterFactoryBean.setUnauthorizedUrl("/api/auth/unauth");
  55.  
  56. shiroFilterFactoryBean.setFilterChainDefinitionMap( shiroConfig.loadFilterChainDefinitionMap() );
  57. return shiroFilterFactoryBean;
  58. }
  59.  
  60. /**
  61. * 安全管理器
  62. */
  63. @Bean
  64. public SecurityManager securityManager() {
  65. DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
  66. // 自定义session管理
  67. securityManager.setSessionManager(sessionManager());
  68. // 自定义Cache实现缓存管理
  69. securityManager.setCacheManager(cacheManager());
  70. // 自定义Realm验证
  71. securityManager.setRealm(shiroRealm());
  72. return securityManager;
  73. }
  74.  
  75. /**
  76. * 身份验证器
  77. */
  78. @Bean
  79. public ShiroRealm shiroRealm() {
  80. ShiroRealm shiroRealm = new ShiroRealm();
  81. shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
  82. return shiroRealm;
  83. }
  84.  
  85. /**
  86. * 自定义Realm的加密规则 -> 凭证匹配器:将密码校验交给Shiro的SimpleAuthenticationInfo进行处理,在这里做匹配配置
  87. */
  88. @Bean
  89. public HashedCredentialsMatcher hashedCredentialsMatcher() {
  90. HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
  91. // 散列算法:这里使用SHA256算法;
  92. shaCredentialsMatcher.setHashAlgorithmName(SHA256Util.HASH_ALGORITHM_NAME);
  93. // 散列的次数,比如散列两次,相当于 md5(md5(""));
  94. shaCredentialsMatcher.setHashIterations(SHA256Util.HASH_ITERATIONS);
  95. return shaCredentialsMatcher;
  96. }
  97.  
  98. /**
  99. * 配置Redis管理器:使用的是shiro-redis开源插件
  100. */
  101. @Bean
  102. public RedisManager redisManager() {
  103. RedisManager redisManager = new RedisManager();
  104. redisManager.setHost(host);
  105. redisManager.setPort(port);
  106. redisManager.setTimeout(timeout);
  107. // redisManager.setPassword(password);
  108. return redisManager;
  109. }
  110.  
  111. /**
  112. * 配置Cache管理器:用于往Redis存储权限和角色标识 (使用的是shiro-redis开源插件)
  113. */
  114. @Bean
  115. public RedisCacheManager cacheManager() {
  116. RedisCacheManager redisCacheManager = new RedisCacheManager();
  117. redisCacheManager.setRedisManager(redisManager());
  118. redisCacheManager.setKeyPrefix(CACHE_KEY);
  119. // 配置缓存的话要求放在session里面的实体类必须有个id标识 注:这里id为用户表中的主键,否-> 报:User must has getter for field: xx
  120. redisCacheManager.setPrincipalIdFieldName("id");
  121. return redisCacheManager;
  122. }
  123.  
  124. /**
  125. * SessionID生成器
  126. */
  127. @Bean
  128. public ShiroSessionIdGenerator sessionIdGenerator(){
  129. return new ShiroSessionIdGenerator();
  130. }
  131.  
  132. /**
  133. * 配置RedisSessionDAO (使用的是shiro-redis开源插件)
  134. */
  135. @Bean
  136. public RedisSessionDAO redisSessionDAO() {
  137. RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
  138. redisSessionDAO.setRedisManager(redisManager());
  139. redisSessionDAO.setSessionIdGenerator(sessionIdGenerator());
  140. redisSessionDAO.setKeyPrefix(SESSION_KEY);
  141. redisSessionDAO.setExpire(EXPIRE);
  142. return redisSessionDAO;
  143. }
  144.  
  145. /**
  146. * 配置Session管理器
  147. */
  148. @Bean
  149. public SessionManager sessionManager() {
  150. ShiroSessionManager shiroSessionManager = new ShiroSessionManager();
  151. shiroSessionManager.setSessionDAO(redisSessionDAO());
  152. return shiroSessionManager;
  153. }
  154.  
  155. }

三、shiro动态加载权限处理方法

  1. loadFilterChainDefinitionMap:初始化权限
    ex: 在上面Shiro配置类ShiroConfig中的Shiro基础配置shiroFilterFactory方法中我们就需要调用此方法将数据库中配置的所有uri权限全部加载进去,以及放行接口和配置权限过滤器等
    【注:过滤器配置顺序不能颠倒,多个过滤器用,分割】
    ex: filterChainDefinitionMap.put("/api/system/user/list", "authc,token,zqPerms[user1]")
  2. updatePermission:动态刷新加载数据库中的uri权限 -> 页面在新增uri路径到数据库中,也就是配置新的权限时就可以调用此方法实现动态加载uri权限
  3. updatePermissionByRoleId:shiro动态权限加载 -> 即分配指定用户权限时可调用此方法删除shiro缓存,重新执行doGetAuthorizationInfo方法授权角色和权限
  1. public interface ShiroService {
  2.  
  3. /**
  4. * 初始化权限 -> 拿全部权限
  5. *
  6. * @param :
  7. * @return: java.util.Map<java.lang.String,java.lang.String>
  8. */
  9. Map<String, String> loadFilterChainDefinitionMap();
  10.  
  11. /**
  12. * 在对uri权限进行增删改操作时,需要调用此方法进行动态刷新加载数据库中的uri权限
  13. *
  14. * @param shiroFilterFactoryBean
  15. * @param roleId
  16. * @param isRemoveSession:
  17. * @return: void
  18. */
  19. void updatePermission(ShiroFilterFactoryBean shiroFilterFactoryBean, Integer roleId, Boolean isRemoveSession);
  20.  
  21. /**
  22. * shiro动态权限加载 -> 原理:删除shiro缓存,重新执行doGetAuthorizationInfo方法授权角色和权限
  23. *
  24. * @param roleId
  25. * @param isRemoveSession:
  26. * @return: void
  27. */
  28. void updatePermissionByRoleId(Integer roleId, Boolean isRemoveSession);
  29.  
  30. }
  1. @Slf4j
  2. @Service
  3. public class ShiroServiceImpl implements ShiroService {
  4.  
  5. @Autowired
  6. private MenuMapper menuMapper;
  7. @Autowired
  8. private UserMapper userMapper;
  9. @Autowired
  10. private RoleMapper roleMapper;
  11.  
  12. @Override
  13. public Map<String, String> loadFilterChainDefinitionMap() {
  14. // 权限控制map
  15. Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
  16. // 配置过滤:不会被拦截的链接 -> 放行 start ----------------------------------------------------------
  17. // 放行Swagger2页面,需要放行这些
  18. filterChainDefinitionMap.put("/swagger-ui.html","anon");
  19. filterChainDefinitionMap.put("/swagger/**","anon");
  20. filterChainDefinitionMap.put("/webjars/**", "anon");
  21. filterChainDefinitionMap.put("/swagger-resources/**","anon");
  22. filterChainDefinitionMap.put("/v2/**","anon");
  23. filterChainDefinitionMap.put("/static/**", "anon");
  24.  
  25. // 登陆
  26. filterChainDefinitionMap.put("/api/auth/login/**", "anon");
  27. // 三方登录
  28. filterChainDefinitionMap.put("/api/auth/loginByQQ", "anon");
  29. filterChainDefinitionMap.put("/api/auth/afterlogin.do", "anon");
  30. // 退出
  31. filterChainDefinitionMap.put("/api/auth/logout", "anon");
  32. // 放行未授权接口,重定向使用
  33. filterChainDefinitionMap.put("/api/auth/unauth", "anon");
  34. // token过期接口
  35. filterChainDefinitionMap.put("/api/auth/tokenExpired", "anon");
  36. // 被挤下线
  37. filterChainDefinitionMap.put("/api/auth/downline", "anon");
  38. // 放行 end ----------------------------------------------------------
  39.  
  40. // 从数据库或缓存中查取出来的url与resources对应则不会被拦截 放行
  41. List<Menu> permissionList = menuMapper.selectList( null );
  42. if ( !CollectionUtils.isEmpty( permissionList ) ) {
  43. permissionList.forEach( e -> {
  44. if ( StringUtils.isNotBlank( e.getUrl() ) ) {
  45. // 根据url查询相关联的角色名,拼接自定义的角色权限
  46. List<Role> roleList = roleMapper.selectRoleByMenuId( e.getId() );
  47. StringJoiner zqRoles = new StringJoiner(",", "zqRoles[", "]");
  48. if ( !CollectionUtils.isEmpty( roleList ) ){
  49. roleList.forEach( f -> {
  50. zqRoles.add( f.getCode() );
  51. });
  52. }
  53.  
  54. // 注意过滤器配置顺序不能颠倒
  55. // ① 认证登录
  56. // ② 认证自定义的token过滤器 - 判断token是否有效
  57. // ③ 角色权限 zqRoles:自定义的只需要满足其中一个角色即可访问 ; roles[admin,guest] : 默认需要每个参数满足才算通过,相当于hasAllRoles()方法
  58. // ④ zqPerms:认证自定义的url过滤器拦截权限 【注:多个过滤器用 , 分割】
  59. // filterChainDefinitionMap.put( "/api" + e.getUrl(),"authc,token,roles[admin,guest],zqPerms[" + e.getResources() + "]" );
  60. filterChainDefinitionMap.put( "/api" + e.getUrl(),"authc,token,"+ zqRoles.toString() +",zqPerms[" + e.getResources() + "]" );
  61. // filterChainDefinitionMap.put("/api/system/user/listPage", "authc,token,zqPerms[user1]"); // 写死的一种用法
  62. }
  63. });
  64. }
  65. // ⑤ 认证登录 【注:map不能存放相同key】
  66. filterChainDefinitionMap.put("/**", "authc");
  67. return filterChainDefinitionMap;
  68. }
  69.  
  70. @Override
  71. public void updatePermission(ShiroFilterFactoryBean shiroFilterFactoryBean, Integer roleId, Boolean isRemoveSession) {
  72. synchronized (this) {
  73. AbstractShiroFilter shiroFilter;
  74. try {
  75. shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean.getObject();
  76. } catch (Exception e) {
  77. throw new MyException("get ShiroFilter from shiroFilterFactoryBean error!");
  78. }
  79. PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
  80. DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
  81.  
  82. // 清空拦截管理器中的存储
  83. manager.getFilterChains().clear();
  84. // 清空拦截工厂中的存储,如果不清空这里,还会把之前的带进去
  85. // ps:如果仅仅是更新的话,可以根据这里的 map 遍历数据修改,重新整理好权限再一起添加
  86. shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();
  87. // 动态查询数据库中所有权限
  88. shiroFilterFactoryBean.setFilterChainDefinitionMap(loadFilterChainDefinitionMap());
  89. // 重新构建生成拦截
  90. Map<String, String> chains = shiroFilterFactoryBean.getFilterChainDefinitionMap();
  91. for (Map.Entry<String, String> entry : chains.entrySet()) {
  92. manager.createChain(entry.getKey(), entry.getValue());
  93. }
  94. log.info("--------------- 动态生成url权限成功! ---------------");
  95.  
  96. // 动态更新该角色相关联的用户shiro权限
  97. if(roleId != null){
  98. updatePermissionByRoleId(roleId,isRemoveSession);
  99. }
  100. }
  101. }
  102.  
  103. @Override
  104. public void updatePermissionByRoleId(Integer roleId, Boolean isRemoveSession) {
  105. // 查询当前角色的用户shiro缓存信息 -> 实现动态权限
  106. List<User> userList = userMapper.selectUserByRoleId(roleId);
  107. // 删除当前角色关联的用户缓存信息,用户再次访问接口时会重新授权 ; isRemoveSession为true时删除Session -> 即强制用户退出
  108. if ( !CollectionUtils.isEmpty( userList ) ) {
  109. for (User user : userList) {
  110. ShiroUtils.deleteCache(user.getUsername(), isRemoveSession);
  111. }
  112. }
  113. log.info("--------------- 动态修改用户权限成功! ---------------");
  114. }
  115.  
  116. }

四、shiro中自定义角色、权限过滤器

1、自定义uri权限过滤器 zqPerms

  1. @Slf4j
  2. public class MyPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {
  3.  
  4. @Override
  5. protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
  6. HttpServletRequest httpRequest = (HttpServletRequest) request;
  7. HttpServletResponse httpResponse = (HttpServletResponse) response;
  8. String requestUrl = httpRequest.getServletPath();
  9. log.info("请求的url: " + requestUrl);
  10.  
  11. // 检查是否拥有访问权限
  12. Subject subject = this.getSubject(request, response);
  13. if (subject.getPrincipal() == null) {
  14. this.saveRequestAndRedirectToLogin(request, response);
  15. } else {
  16. // 转换成http的请求和响应
  17. HttpServletRequest req = (HttpServletRequest) request;
  18. HttpServletResponse resp = (HttpServletResponse) response;
  19.  
  20. // 获取请求头的值
  21. String header = req.getHeader("X-Requested-With");
  22. // ajax 的请求头里有X-Requested-With: XMLHttpRequest 正常请求没有
  23. if (header!=null && "XMLHttpRequest".equals(header)){
  24. resp.setContentType("text/json,charset=UTF-8");
  25. resp.getWriter().print("{\"success\":false,\"msg\":\"没有权限操作!\"}");
  26. }else { //正常请求
  27. String unauthorizedUrl = this.getUnauthorizedUrl();
  28. if (StringUtils.hasText(unauthorizedUrl)) {
  29. WebUtils.issueRedirect(request, response, unauthorizedUrl);
  30. } else {
  31. WebUtils.toHttp(response).sendError(401);
  32. }
  33. }
  34.  
  35. }
  36. return false;
  37. }
  38. }

2、自定义角色权限过滤器 zqRoles

shiro原生的角色过滤器RolesAuthorizationFilter 默认是必须同时满足roles[admin,guest]才有权限,而自定义的zqRoles 只满足其中一个即可访问

ex: zqRoles[admin,guest]

  1. public class MyRolesAuthorizationFilter extends AuthorizationFilter {
  2.  
  3. @Override
  4. protected boolean isAccessAllowed(ServletRequest req, ServletResponse resp, Object mappedValue) throws Exception {
  5. Subject subject = getSubject(req, resp);
  6. String[] rolesArray = (String[]) mappedValue;
  7. // 没有角色限制,有权限访问
  8. if (rolesArray == null || rolesArray.length == 0) {
  9. return true;
  10. }
  11. for (int i = 0; i < rolesArray.length; i++) {
  12. //若当前用户是rolesArray中的任何一个,则有权限访问
  13. if (subject.hasRole(rolesArray[i])) {
  14. return true;
  15. }
  16. }
  17. return false;
  18. }
  19.  
  20. }

3、自定义token过滤器 token -> 判断token是否过期失效等

  1. @Slf4j
  2. public class TokenCheckFilter extends UserFilter {
  3.  
  4. /**
  5. * token过期、失效
  6. */
  7. private static final String TOKEN_EXPIRED_URL = "/api/auth/tokenExpired";
  8.  
  9. /**
  10. * 判断是否拥有权限 true:认证成功 false:认证失败
  11. * mappedValue 访问该url时需要的权限
  12. * subject.isPermitted 判断访问的用户是否拥有mappedValue权限
  13. */
  14. @Override
  15. public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
  16. HttpServletRequest httpRequest = (HttpServletRequest) request;
  17. HttpServletResponse httpResponse = (HttpServletResponse) response;
  18. // 根据请求头拿到token
  19. String token = WebUtils.toHttp(request).getHeader(Constants.REQUEST_HEADER);
  20. log.info("浏览器token:" + token );
  21. User userInfo = ShiroUtils.getUserInfo();
  22. String userToken = userInfo.getToken();
  23. // 检查token是否过期
  24. if ( !token.equals(userToken) ){
  25. return false;
  26. }
  27. return true;
  28. }
  29.  
  30. /**
  31. * 认证失败回调的方法: 如果登录实体为null就保存请求和跳转登录页面,否则就跳转无权限配置页面
  32. */
  33. @Override
  34. protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
  35. User userInfo = ShiroUtils.getUserInfo();
  36. // 重定向错误提示处理 - 前后端分离情况下
  37. WebUtils.issueRedirect(request, response, TOKEN_EXPIRED_URL);
  38. return false;
  39. }
  40.  
  41. }

五、项目中会用到的一些工具类、常量等

温馨小提示:这里只是部分,详情可参考文章末尾给出的案例demo源码

1、Shiro工具类

  1. public class ShiroUtils {
  2.  
  3. /** 私有构造器 **/
  4. private ShiroUtils(){ }
  5.  
  6. private static RedisSessionDAO redisSessionDAO = SpringUtil.getBean(RedisSessionDAO.class);
  7.  
  8. /**
  9. * 获取当前用户Session
  10. * @Return SysUserEntity 用户信息
  11. */
  12. public static Session getSession() {
  13. return SecurityUtils.getSubject().getSession();
  14. }
  15.  
  16. /**
  17. * 用户登出
  18. */
  19. public static void logout() {
  20. SecurityUtils.getSubject().logout();
  21. }
  22.  
  23. /**
  24. * 获取当前用户信息
  25. * @Return SysUserEntity 用户信息
  26. */
  27. public static User getUserInfo() {
  28. return (User) SecurityUtils.getSubject().getPrincipal();
  29. }
  30.  
  31. /**
  32. * 删除用户缓存信息
  33. * @Param username 用户名称
  34. * @Param isRemoveSession 是否删除Session,删除后用户需重新登录
  35. */
  36. public static void deleteCache(String username, boolean isRemoveSession){
  37. //从缓存中获取Session
  38. Session session = null;
  39. // 获取当前已登录的用户session列表
  40. Collection<Session> sessions = redisSessionDAO.getActiveSessions();
  41. User sysUserEntity;
  42. Object attribute = null;
  43. // 遍历Session,找到该用户名称对应的Session
  44. for(Session sessionInfo : sessions){
  45. attribute = sessionInfo.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
  46. if (attribute == null) {
  47. continue;
  48. }
  49. sysUserEntity = (User) ((SimplePrincipalCollection) attribute).getPrimaryPrincipal();
  50. if (sysUserEntity == null) {
  51. continue;
  52. }
  53. if (Objects.equals(sysUserEntity.getUsername(), username)) {
  54. session=sessionInfo;
  55. // 清除该用户以前登录时保存的session,强制退出 -> 单用户登录处理
  56. if (isRemoveSession) {
  57. redisSessionDAO.delete(session);
  58. }
  59. }
  60. }
  61.  
  62. if (session == null||attribute == null) {
  63. return;
  64. }
  65. //删除session
  66. if (isRemoveSession) {
  67. redisSessionDAO.delete(session);
  68. }
  69. //删除Cache,再访问受限接口时会重新授权
  70. DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
  71. Authenticator authc = securityManager.getAuthenticator();
  72. ((LogoutAware) authc).onLogout((SimplePrincipalCollection) attribute);
  73. }
  74.  
  75. /**
  76. * 从缓存中获取指定用户名的Session
  77. * @param username
  78. */
  79. private static Session getSessionByUsername(String username){
  80. // 获取当前已登录的用户session列表
  81. Collection<Session> sessions = redisSessionDAO.getActiveSessions();
  82. User user;
  83. Object attribute;
  84. // 遍历Session,找到该用户名称对应的Session
  85. for(Session session : sessions){
  86. attribute = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
  87. if (attribute == null) {
  88. continue;
  89. }
  90. user = (User) ((SimplePrincipalCollection) attribute).getPrimaryPrincipal();
  91. if (user == null) {
  92. continue;
  93. }
  94. if (Objects.equals(user.getUsername(), username)) {
  95. return session;
  96. }
  97. }
  98. return null;
  99. }
  100.  
  101. }

2、Redis常量类

  1. public interface RedisConstant {
  2. /**
  3. * TOKEN前缀
  4. */
  5. String REDIS_PREFIX_LOGIN = "code-generator_token_%s";
  6. }

3、Spring上下文工具类

  1. @Component
  2. public class SpringUtil implements ApplicationContextAware {
  3. private static ApplicationContext context;
  4. /**
  5. * Spring在bean初始化后会判断是不是ApplicationContextAware的子类
  6. * 如果该类是,setApplicationContext()方法,会将容器中ApplicationContext作为参数传入进去
  7. */
  8. @Override
  9. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  10. context = applicationContext;
  11. }
  12. /**
  13. * 通过Name返回指定的Bean
  14. */
  15. public static <T> T getBean(Class<T> beanClass) {
  16. return context.getBean(beanClass);
  17. }
  18. }

六、案例demo源码

GitHub地址

https://github.com/zhengqingya/code-generator/tree/master/code-generator-api/src/main/java/com/zhengqing/modules/shiro

码云地址

https://gitee.com/zhengqingya/code-generator/blob/master/code-generator-api/src/main/java/com/zhengqing/modules/shiro

本地下载

https://pan.baidu.com/s/1I8JErz6oyddu1LI0RNousw(提取码: hdtw)

总结

以上就是我在处理客户端真实IP的方法,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对w3xue的支持。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号