一、引入maven配置

  1. <dependency>
  2.     <groupId>org.apache.shiro</groupId>
  3.     <artifactId>shiro-spring</artifactId>
  4.     <version>1.4.0</version>
  5. </dependency>

二、建表

用户表、角色表、权限表、用户角色表、角色权限表。

用户表:

角色表:

权限表:news:* 表示有新闻的所有权限(包括增删改查),而news:add,只有新闻的新增权限。

用户角色表:用户拥有哪些角色。

角色权限表:角色拥有哪些权限。

三、自定义Realm

自定义realm主要用于用户的权限验证以及登录验证。

自定义realm继承AuthorizingRealm类,并重写doGetAuthorizationInfo和doGetAuthenticationInfo方法,doGetAuthorizationInfo方法主要校验用户的权限,即该用户拥有什么角色以及权限。doGetAuthenticationInfo用于校验登录验证,即用户的用户名或者密码是否正确。

  1. /**
  2.  * 类名 : shiro的Realm
  3.  * 用法 :
  4.  * 创建人 : shyroke
  5.  * 时间:2018/12/12 17:29
  6.  */
  7. public class MyRealm extends AuthorizingRealm {
  8.  
  9.     @Autowired
  10.     private UserMapper userMapper;
  11.  
  12.     @Autowired
  13.     private PermissionMapper permissionMapper;
  14.  
  15.     /**
  16.      * 授权,即该用户拥有什么角色以及权限
  17.      * 步骤:根据用户名获取角色以及权限,然后设置到验证信息类并返回。
  18.      * @param principalCollection
  19.      * @return
  20.      */
  21.     @Override
  22.     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
  23.  
  24.         SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
  25.  
  26.         String userName = principalCollection.getPrimaryPrincipal().toString();
  27.  
  28. //        获取该用户的角色
  29.         List<Role> roles = userMapper.getRolesByUserName(userName);
  30.         Set<String> roleSets = new HashSet<>();
  31.  
  32. //        获取该用户的权限集
  33.         List<Permission> permissions = new ArrayList<>();
  34.         Set<String> permissoinSet = new HashSet<>();
  35.  
  36.         //将List转为Set
  37.         if(roles !=null && roles.size()>0){
  38.             for(Role role:roles){
  39.                 roleSets.add(role.getName());
  40.                 permissions.addAll(permissionMapper.getPermissionByRoleId(role.getId()));
  41.             }
  42.         }
  43.  
  44.         //将List转为Set
  45.         if(permissions!=null & permissoinSet.size()>0){
  46.             for(Permission p :permissions){
  47.                 permissoinSet.add(p.getName());
  48.             }
  49.         }
  50.  
  51.         info.addRoles(roleSets);
  52.         info.addStringPermissions(permissoinSet);
  53.  
  54.         return info;
  55.     }
  56.  
  57.     /**
  58.      * 认证,即用户账号密码是否正确
  59.      * @param token
  60.      * @return
  61.      * @throws AuthenticationException
  62.      */
  63.     @Override
  64.     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  65. //        获取用户名和密码
  66.         String userName = (String)token.getPrincipal();
  67.         String passWord = new String((char[]) token.getCredentials());
  68.  
  69. //        根据用户名查找该用户
  70.         User user =  userMapper.getUserByName(userName);
  71.  
  72.         if(user == null){
  73.             throw new UnknownAccountException("用户名不存在");
  74.         }
  75.  
  76.         if(!user.getPassword().equals(passWord)){
  77.             throw new IncorrectCredentialsException("密码错误");
  78.         }
  79.  
  80.         SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getName(),user.getPassword(),getName());
  81.  
  82.         return info;
  83.     }
  84. }

四、shiro配置类

  1. /**
  2.  * 类名 :shiro的核心配置类
  3.  * 用法 :
  4.  * 创建人 : shyroke
  5.  * 时间:2018/12/14 15:20
  6.  */
  7. @Configuration
  8. public class ShiroConfigration {
  9.  
  10. //    设置自定义Realm
  11.     @Bean
  12.     public MyRealm myRealm(){
  13.         return new MyRealm();
  14.     }
  15.  
  16. //    权限管理,配置主要是Realm的管理认证
  17.     @Bean
  18.     public SecurityManager securityManager(){
  19.         DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
  20.         manager.setRealm(myRealm());
  21.         return manager;
  22.     }
  23.  
  24.     /**
  25.      * 设置过滤条件和跳转条件
  26.      * anon 不生效的原因:1、map的类型必须是LinkedHashMap 2、anon必须定义在authc之前
  27.      *
  28.      * @param securityManager
  29.      * @return
  30.      */
  31.     @Bean
  32.         public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
  33.             ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
  34.             factoryBean.setSecurityManager(securityManager);
  35.  
  36. //            设置登录跳转
  37.             factoryBean.setLoginUrl("/admin");
  38.             factoryBean.setSuccessUrl("/admin/index");
  39.  
  40.             //必须为LinkedHashMap 否则anon不生效
  41.             Map<String,String> map = new LinkedHashMap<>();
  42.  
  43.             //退出
  44.             map.put("/admin/logout","logout");
  45.  
  46.             //登录页面和登录验证不要拦截
  47.             map.put("/admin/login.html","anon");
  48.             map.put("/admin/tologin","anon");
  49.  
  50.             //设置需要过滤的链接
  51.             map.put("/admin/**","authc");
  52.  
  53.             factoryBean.setFilterChainDefinitionMap(map);
  54.  
  55.             return factoryBean;
  56.         }
  57.  
  58.     /**
  59.      *  开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证
  60.      * 配置以下两个bean(DefaultAdvisorAutoProxyCreator和AuthorizationAttributeSourceAdvisor)即可实现此功能
  61.      * @return
  62.      */
  63.     @Bean
  64.     public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator(){
  65.         DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
  66.         advisorAutoProxyCreator.setProxyTargetClass(true);
  67.         return advisorAutoProxyCreator;
  68.     }
  69.  
  70.     /**
  71.      * 开启aop注解支持
  72.      * @param securityManager
  73.      * @return
  74.      */
  75.     @Bean
  76.     public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
  77.         AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
  78.         authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
  79.         return authorizationAttributeSourceAdvisor;
  80.     }
  81.  
  82. }

五、调用

代码如下,当调用Subject.login方法后,会调用自定义Realm的doGetAuthenticationInfo方法校验用户名密码是否正确,如果不正确则抛出对应异常,controller层捕获并处理异常。

  1. AuthenticationToken usernamePasswordToken = new UsernamePasswordToken(user.getName(),user.getPassword());
  2.  
  3. Subject subject = SecurityUtils.getSubject();
  4.  
  5. try {
  6.     subject.login(usernamePasswordToken);
  7. }catch (UnknownAccountException ex) {
  8.     logger.info("用户名错误!");
  9.     return R.error("用户名错误!");
  10. } catch (IncorrectCredentialsException ex) {
  11.     logger.info("密码错误!");
  12.     return R.error("密码错误!");
  13. } catch (AuthenticationException ex) {
  14.     logger.info(ex.getMessage());
  15.     return R.error("系统错误,请查看日志");
  16. } catch (Exception ex) {
  17.     logger.info(ex.getMessage());
  18.     return R.error("系统错误,请查看日志");
  19. }

(十二)springboot中shiro的使用的更多相关文章

  1. (转)SpringMVC学习(十二)——SpringMVC中的拦截器

    http://blog.csdn.net/yerenyuan_pku/article/details/72567761 SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter, ...

  2. OpenJDK源码研究笔记(十二):JDBC中的元数据,数据库元数据(DatabaseMetaData),参数元数据(ParameterMetaData),结果集元数据(ResultSetMetaDa

    元数据最本质.最抽象的定义为:data about data (关于数据的数据).它是一种广泛存在的现象,在许多领域有其具体的定义和应用. JDBC中的元数据,有数据库元数据(DatabaseMeta ...

  3. SpringBoot中Shiro缓存使用Redis、Ehcache

    在SpringBoot中Shiro缓存使用Redis.Ehcache实现的两种方式实例 SpringBoot 中配置redis作为session 缓存器. 让shiro引用 本文是建立在你是使用这sh ...

  4. SpringBoot中Shiro使用Pac4j集成CAS认证

    SpringBoot中Shiro使用Pac4j集成CAS认证 Pac4j 简介 Pac4j与Shiro,Spring Security一样都是权限框架,并且提供了OAuth - SAML - CAS ...

  5. springboot系列(十)springboot整合shiro实现登录认证

    关于shiro的概念和知识本篇不做详细介绍,但是shiro的概念还是需要做做功课的要不无法理解它的运作原理就无法理解使用shiro: 本篇主要讲解如何使用shiro实现登录认证,下篇讲解使用shiro ...

  6. (十二)整合 Shiro 框架,实现用户权限管理

    整合 Shiro 框架,实现用户权限管理 1.Shiro简介 1.1 基础概念 1.2 核心角色 1.3 核心理念 2.SpringBoot整合Shiro 2.1 核心依赖 2.2 Shiro核心配置 ...

  7. [十二]SpringBoot 之 servlet

    Web开发使用 Controller 基本上可以完成大部分需求,但是我们还可能会用到 Servlet.Filter.Listener.Interceptor 等等. 当使用spring-Boot时,嵌 ...

  8. 十二.spring-boot使用spring-boot-freemarker

    ①.在springMVC中:它代表着view层组件 ②.为什么使用freemarker:简单容易学.逻辑分明 ③.freemarker优点:它不依赖servlet.网络或者web环境 一.创建一个ma ...

  9. Expo大作战(十二)--expo中的自定义样式Custom font,以及expo中的路由Route&Navigation

    简要:本系列文章讲会对expo进行全面的介绍,本人从2017年6月份接触expo以来,对expo的研究断断续续,一路走来将近10个月,废话不多说,接下来你看到内容,讲全部来与官网 我猜去全部机翻+个人 ...

随机推荐

  1. 推荐系统(recommender systems):预测电影评分--问题描述

    推荐系统很重要的原因:1>它是机器学习的一个重要应用2>对于机器学习来说,特征是非常重要的,对于一些问题,存在一些算法能自动帮我选择一些优良的features,推荐系统就可以帮助我们做这样 ...

  2. 珠峰培训node 珠峰爬虫| cron 定时任务

    1.cron 定时任务 CronJob var CronJob = require('cron').CronJob; // 秒 分钟 时 天

  3. 题解 LA2911

    题目大意 多组数据,每组数据给定整数 \(m,p,a,b\),满足 \(a>0\),\(2\leq p\leq12\) 且 \(p\) 为偶数.要求求出一列数 \(x_1,x_2,\cdots, ...

  4. 自定义枚举 --- Swagger文档展示

    在其它两篇文章中,已经解决的自定义枚举在MyBatis以及Rest接口的转换,但是在Springfox中还存在问题,不能使用code来作为api.本文通过扩展Springfox,实现了对自定义枚举的良 ...

  5. springdata--xml配置

    <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.spr ...

  6. [RN] React Native 图片懒加载库 animated-lazy-image

    React Native 图片懒加载库 animated-lazy-image 官方Github地址: https://github.com/danijelgrabez/lazy-image 使用效果 ...

  7. 第03组 Alpha冲刺

    队名:不等式方程组 组长博客 作业博客 团队项目进度 组员一:张逸杰(组长) 过去两天完成的任务: 文字/口头描述: 制定了初步的项目计划,并开始学习一些推荐.搜索类算法 GitHub签入纪录: 暂无 ...

  8. 启动hadoop报does not contain a valid host:port authority:node2_1:9000

    报错:启动hadoop报does not contain a valid host:port authority:node2_1:9000 原因:主机的hostname不合法,修改为不包含着‘.’ ' ...

  9. c语言用指针定义一个类型进行输入输出

    1 整型数组 // #include "stdafx.h" #include "stdlib.h" int _tmain(int argc, _TCHAR* a ...

  10. XMLHttpRequest用法介绍

    前言: 传统的Web应用请求服务器返回的一般是是完整的HTML页面,这样往往就需要页面进行刷新操作,不仅耗时而且用户体验度也不好.最典型的代表就是form表单登录操作了.如果登录失败往往是跳转到原网页 ...