写一个不花里胡哨的纯粹的Springboot+Shiro的入门小栗子

效果如图:

首页:有登录注册

先注册一个,然后登陆

登录,成功自动跳转到home页

home页:通过认证之后才可以进


代码部分:

依赖:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5.  
  6. <groupId>com.example</groupId>
  7. <artifactId>demo</artifactId>
  8. <version>0.0.1-SNAPSHOT</version>
  9. <packaging>jar</packaging>
  10.  
  11. <name>demo</name>
  12. <description>Demo project for Spring Boot</description>
  13.  
  14. <parent>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-parent</artifactId>
  17. <version>2.0.3.RELEASE</version>
  18. <relativePath/> <!-- lookup parent from repository -->
  19. </parent>
  20.  
  21. <properties>
  22. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  23. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  24. <java.version>1.8</java.version>
  25. </properties>
  26.  
  27. <dependencies>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-data-redis</artifactId>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.springframework.boot</groupId>
  38. <artifactId>spring-boot-starter-web</artifactId>
  39. </dependency>
  40. <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-all -->
  41. <dependency>
  42. <groupId>org.apache.shiro</groupId>
  43. <artifactId>shiro-all</artifactId>
  44. <version>1.3.2</version>
  45. </dependency>
  46. <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
  47. <dependency>
  48. <groupId>com.alibaba</groupId>
  49. <artifactId>fastjson</artifactId>
  50. <version>1.2.47</version>
  51. </dependency>
  52. <!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
  53. <dependency>
  54. <groupId>net.sf.ehcache</groupId>
  55. <artifactId>ehcache</artifactId>
  56. <version>2.10.5</version>
  57. </dependency>
  58.  
  59. <dependency>
  60. <groupId>org.springframework.boot</groupId>
  61. <artifactId>spring-boot-devtools</artifactId>
  62. <scope>runtime</scope>
  63. </dependency>
  64. <dependency>
  65. <groupId>org.springframework.boot</groupId>
  66. <artifactId>spring-boot-starter-test</artifactId>
  67. <scope>test</scope>
  68. </dependency>
  69. </dependencies>
  70.  
  71. <build>
  72. <plugins>
  73. <plugin>
  74. <groupId>org.springframework.boot</groupId>
  75. <artifactId>spring-boot-maven-plugin</artifactId>
  76. </plugin>
  77. </plugins>
  78. </build>
  79.  
  80. </project>

Java配置类:

  1. package com.example.demo.conf;
  2.  
  3. import com.example.demo.auth.PermissionRealm;
  4. import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
  5. import org.apache.shiro.cache.CacheManager;
  6. import org.apache.shiro.cache.ehcache.EhCacheManager;
  7. import org.apache.shiro.realm.AuthorizingRealm;
  8. import org.apache.shiro.spring.LifecycleBeanPostProcessor;
  9. import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
  10. import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
  11. import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
  12. import org.springframework.context.annotation.Bean;
  13. import org.springframework.context.annotation.Configuration;
  14. import org.springframework.context.annotation.DependsOn;
  15.  
  16. import java.util.LinkedHashMap;
  17.  
  18. /**
  19. * @program: boot-shiro
  20. * @description:
  21. * @author: 001977
  22. * @create: 2018-07-17 18:22
  23. */
  24. @Configuration
  25. public class ShiroConfig {
  26.  
  27. /**
  28. * 1. 配置SecurityManager
  29. * @return
  30. */
  31. @Bean
  32. public DefaultWebSecurityManager securityManager(){
  33. DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
  34. securityManager.setRealm(realm());
  35. return securityManager;
  36. }
  37.  
  38. /**
  39. * 2. 配置缓存
  40. * @return
  41. */
  42. @Bean
  43. public CacheManager cacheManager(){
  44. EhCacheManager ehCacheManager = new EhCacheManager();
  45. ehCacheManager.setCacheManagerConfigFile("classpath:ehcache.xml");
  46. return ehCacheManager;
  47. }
  48.  
  49. /**
  50. * 3. 配置Realm
  51. * @return
  52. */
  53. @Bean
  54. public AuthorizingRealm realm(){
  55. PermissionRealm realm = new PermissionRealm();
  56. HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
  57. // 指定加密算法
  58. matcher.setHashAlgorithmName("MD5");
  59. // 指定加密次数
  60. matcher.setHashIterations(10);
  61. // 指定这个就不会报错
  62. matcher.setStoredCredentialsHexEncoded(true);
  63. realm.setCredentialsMatcher(matcher);
  64. return realm;
  65. }
  66.  
  67. /**
  68. * 4. 配置LifecycleBeanPostProcessor,可以来自动的调用配置在Spring IOC容器中 Shiro Bean 的生命周期方法
  69. * @return
  70. */
  71. @Bean
  72. public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
  73. return new LifecycleBeanPostProcessor();
  74. }
  75.  
  76. /**
  77. * 5. 启用IOC容器中使用Shiro的注解,但是必须配置第四步才可以使用
  78. * @return
  79. */
  80. @Bean
  81. @DependsOn("lifecycleBeanPostProcessor")
  82. public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
  83. return new DefaultAdvisorAutoProxyCreator();
  84. }
  85.  
  86. /**
  87. * 6. 配置ShiroFilter
  88. * @return
  89. */
  90. @Bean
  91. public ShiroFilterFactoryBean shiroFilterFactoryBean(){
  92. LinkedHashMap<String, String> map = new LinkedHashMap<>();
  93. // 静态资源
  94. map.put("/css/**", "anon");
  95. map.put("/js/**", "anon");
  96.  
  97. // 公共路径
  98. map.put("/login", "anon");
  99. map.put("/register", "anon");
  100. //map.put("/*", "anon");
  101.  
  102. // 登出,项目中没有/logout路径,因为shiro是过滤器,而SpringMVC是Servlet,Shiro会先执行
  103. map.put("/logout", "logout");
  104.  
  105. // 授权
  106. map.put("/user/**", "authc,roles[user]");
  107. map.put("/admin/**", "authc,roles[admin]");
  108.  
  109. // everything else requires authentication:
  110. map.put("/**", "authc");
  111.  
  112. ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
  113. // 配置SecurityManager
  114. factoryBean.setSecurityManager(securityManager());
  115. // 配置权限路径
  116. factoryBean.setFilterChainDefinitionMap(map);
  117. // 配置登录url
  118. factoryBean.setLoginUrl("/");
  119. // 配置无权限路径
  120. factoryBean.setUnauthorizedUrl("/unauthorized");
  121. return factoryBean;
  122. }
  123.  
  124. }

Realm类:

  1. package com.example.demo.auth;
  2.  
  3. import com.example.demo.common.entity.User;
  4. import com.example.demo.service.UserService;
  5. import org.apache.shiro.authc.*;
  6. import org.apache.shiro.authz.AuthorizationInfo;
  7. import org.apache.shiro.authz.SimpleAuthorizationInfo;
  8. import org.apache.shiro.realm.AuthorizingRealm;
  9. import org.apache.shiro.subject.PrincipalCollection;
  10. import org.apache.shiro.util.ByteSource;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12.  
  13. import java.util.HashSet;
  14. import java.util.Set;
  15.  
  16. /**
  17. * @program: boot-shiro
  18. * @description:
  19. * @author: 001977
  20. * @create: 2018-07-12 13:03
  21. */
  22. public class PermissionRealm extends AuthorizingRealm {
  23.  
  24. @Autowired
  25. private UserService userService;
  26.  
  27. @Override
  28. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
  29. Object principal = principalCollection.getPrimaryPrincipal();
  30. User user = (User) principal;
  31. Set<String> roles = new HashSet<>();
  32. roles.add("user");
  33. SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
  34. return info;
  35. }
  36.  
  37. @Override
  38. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
  39. UsernamePasswordToken uToken = (UsernamePasswordToken) authenticationToken;
  40.  
  41. String username = uToken.getUsername();
  42. String password = String.valueOf(uToken.getPassword());
  43.  
  44. User user = userService.login(new User(username,password));
  45.  
  46. if(user == null){
  47. throw new AuthenticationException("用户名密码不存在");
  48. }
  49. //认证的实体信息
  50. Object principal = user;
  51. //从数据库获取的密码
  52. Object hashedCredentials = user.getPassword();
  53. //盐值
  54. ByteSource credentialsSalt = ByteSource.Util.bytes(user.getUsername());
  55. //当前Realm对象的name,调用父类的getName方法
  56. String realmName = getName();
  57.  
  58. SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, hashedCredentials, credentialsSalt, realmName);
  59.  
  60. return info;
  61. }
  62. }

Controller:

  1. package com.example.demo.controller;
  2.  
  3. import com.example.demo.common.TempStorage;
  4. import com.example.demo.common.entity.User;
  5. import com.example.demo.common.response.BaseResponse;
  6. import com.example.demo.service.UserService;
  7. import org.apache.shiro.SecurityUtils;
  8. import org.apache.shiro.authc.UsernamePasswordToken;
  9. import org.apache.shiro.subject.Subject;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.web.bind.annotation.RequestBody;
  12. import org.springframework.web.bind.annotation.RequestMapping;
  13. import org.springframework.web.bind.annotation.RestController;
  14. import org.springframework.web.servlet.ModelAndView;
  15.  
  16. /**
  17. * @program: boot-shiro
  18. * @description:
  19. * @author: 001977
  20. * @create: 2018-07-12 13:02
  21. */
  22. @RestController
  23. public class SimpleController {
  24.  
  25. @Autowired
  26. private UserService userService;
  27.  
  28. @RequestMapping("/")
  29. public ModelAndView index(){
  30. return new ModelAndView("index");
  31. }
  32.  
  33. @RequestMapping("/login")
  34. public BaseResponse<String> login(@RequestBody User user){
  35. BaseResponse<String> response = new BaseResponse<>(0,"登陆成功");
  36. Subject subject = SecurityUtils.getSubject();
  37. UsernamePasswordToken token = new UsernamePasswordToken(
  38. user.getUsername(), user.getPassword());
  39. subject.login(token);
  40. response.setData("/home");
  41. return response;
  42. }
  43.  
  44. @RequestMapping("/register")
  45. public BaseResponse register(@RequestBody User user){
  46. userService.addUser(user);
  47. return new BaseResponse(0,"注册成功");
  48. }
  49.  
  50. @RequestMapping("/home")
  51. public ModelAndView home(){
  52. ModelAndView mv = new ModelAndView("home");
  53. mv.addObject("users", TempStorage.getInstance().getMap());
  54. return mv;
  55. }
  56. }

其余代码参见GitHub

SpringBoot+Shiro入门小栗子的更多相关文章

  1. SpringBoot+Shiro+Redis共享Session入门小栗子

    在单机版的Springboot+Shiro的基础上,这次实现共享Session. 这里没有自己写RedisManager.SessionDAO.用的 crazycake 写的开源插件 pom.xml ...

  2. Java IO 与 NIO 服务器&客户端通信小栗子

    本篇包含了入门小栗子以及一些问题的思考 BIO package com.demo.bio; import java.io.*; import java.net.ServerSocket; import ...

  3. SpringBoot介绍,快速入门小例子,目录结构,不同的启动方式,SpringBoot常用注解

    SpringBoot介绍 引言 为了使用ssm框架去开发,准备ssm框架的模板配置 为了Spring整合第三方框架,单独的去编写xml文件 导致ssm项目后期xml文件特别多,维护xml文件的成本也是 ...

  4. springboot+shiro

    作者:纯洁的微笑 出处:http://www.ityouknow.com/ 这篇文章我们来学习如何使用Spring Boot集成Apache Shiro.安全应该是互联网公司的一道生命线,几乎任何的公 ...

  5. Spring Cloud之路:(七)SpringBoot+Shiro实现登录认证和权限管理

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/sage_wang/article/details/79592269一.Shiro介绍1.Shiro是 ...

  6. Shiro入门指引

    最近项目中用到Shiro,专门对其研究了一番,颇有收获,以下是笔者最近写的博客,希望对大家入门有所帮助. Shiro入门资源整理 Shiro在SpringBoot中的使用 Shiro源码解析-登录篇 ...

  7. 前端基于vue,后台采用springboot+shiro的方式搭建的一个移动端商品展示平台

    基于vue实现的移动端商品展示页,可以web-view的方式嵌入到小程序中,布局简约.大气,减少初学者或开发者不必要的工作量.后台维护采用的springboot+shiro的方式,为广大爱好者提供展示 ...

  8. SpringBoot+Shiro学习(七):Filter过滤器管理

    SpringBoot+Shiro学习(七):Filter过滤器管理 Hiwayz 关注  0.5 2018.09.06 19:09* 字数 1070 阅读 5922评论 1喜欢 20 先从我们写的一个 ...

  9. SpringBoot&Shiro实现权限管理

    SpringBoot&Shiro实现权限管理 引言 相信大家前来看这篇文章的时候,是有SpringBoot和Shiro基础的,所以本文只介绍整合的步骤,如果哪里写的不好,恳请大家能指出错误,谢 ...

随机推荐

  1. Python:matplotlib绘制直方图

    使用hist方法来绘制直方图:     绘制直方图,最主要的是一个数据集data和需要划分的区间数量bins,另外你也可以设置一些颜色.类型参数: plt.hist(np.random.randn(1 ...

  2. linux 地址解析协议 arp

    随便转载,保留出处:http://www.cnblogs.com/aaron-agu/ arp –na #查看 arp –s 123.253.68.209 00:19:56:6F:87:D4 #添加

  3. LODOP字体不识别 英文字母连起来 引号不正常

    打印超文本的时候,有时候会发现html中设置的css样式显示不正常,字体根本不是设置的字体,这种情况有可能是:1.该操作系统没有安装自己指定的那种字体,那么没有安装自然就不能显示设置的字体.2.该操作 ...

  4. react用class关键字来创建组件

    创建组件之前,首先学习一个ES6的写法,叫做展开运算符. 比如我这里有两个数组.如何将第二个数组o2中的所有属性导入到数组o1中呢?一个个输太麻烦,所以就用到了展开运算符. var o2={ age: ...

  5. nodejs zip 安装配置

    1.下载 下载地址:https://nodejs.org/zh-cn/download/ 选择相应的版本下载 2.解压缩 将文件解压到要安装的位置,并新建两个目录 node-global :npm全局 ...

  6. 实验吧 WEB 猫抓老鼠

    人生的第一道CTF题目哇,鸡冻 其实只是学了一下HTTP抓包得到的都是什么,就开始上手胡搞了 题目名字叫猫抓老鼠,还疯狂暗示catch!catch!catch!catch!,就想到要用抓包其实我是因为 ...

  7. .net core 2.0 MVC区域

    区域 创建对应的目录结构 Areas System Controllers Views 在Startup.cs 注册路由 在控制器上方加上`[Area("system")]` // ...

  8. Let's Encrypt免费泛域名证书申请

    一. 下载acme.sh,以下四条命令任选一条即可 curl https://get.acme.sh | shwget -O - https://get.acme.sh | sh curl https ...

  9. linux shell系列10 判断某个月中的星期六和星期天

    #!/bin/bashread -p "请输入月份:" month #输入要查找的月份 mon=`date -d "0 month ago" +%m` #计算本 ...

  10. Dirichlet's Theorem on Arithmetic Progressions POJ - 3006 线性欧拉筛

    题意 给出a d n    给出数列 a,a+d,a+2d,a+3d......a+kd 问第n个数是几 保证答案不溢出 直接线性筛模拟即可 #include<cstdio> #inclu ...