经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring » 查看文章
Springboot-Shiro基本使用详情介绍
来源:jb51  时间:2022/1/3 16:47:28  对本文有异议

Apache Shiro官网:https://shiro.apache.org/spring-boot.html.

一、依据官网快速搭建Quickstart

在这里插入图片描述

1.1 配置pom.xml依赖

  1. ?<dependency>
  2. ? ? ? ? ? ? <groupId>org.apache.shiro</groupId>
  3. ? ? ? ? ? ? <artifactId>shiro-core</artifactId>
  4. ? ? ? ? ? ? <version>1.7.1</version>
  5. ? ? ? ? </dependency>
  6. ? ? ? ? <!-- configure logging-->
  7. ? ? ? ? <dependency>
  8. ? ? ? ? ? ? <groupId>org.slf4j</groupId>
  9. ? ? ? ? ? ? <artifactId>jcl-over-slf4j</artifactId>
  10. ? ? ? ? ? ? <version>1.7.21</version>
  11. ? ? ? ? </dependency>
  12. ? ? ? ? <!--调用日志框架-->
  13. ? ? ? ? <dependency>
  14. ? ? ? ? ? ? <groupId>org.slf4j</groupId>
  15. ? ? ? ? ? ? <artifactId>slf4j-log4j12</artifactId>
  16. ? ? ? ? ? ? <version>1.7.21</version>
  17. ? ? ? ? </dependency>
  18. ? ? ? ? <dependency>
  19. ? ? ? ? ? ? <groupId>log4j</groupId>
  20. ? ? ? ? ? ? <artifactId>log4j</artifactId>
  21. ? ? ? ? ? ? <version>1.2.17</version>
  22. ? ? ? ? </dependency>

1.2配置log4j.properties

  1. log4j.rootLogger=INFO, stdout
  2.  
  3. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  4. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  5. log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
  6.  
  7. # General Apache libraries
  8. log4j.logger.org.apache=WARN
  9.  
  10. # Spring
  11. log4j.logger.org.springframework=WARN
  12.  
  13. # Default Shiro logging
  14. log4j.logger.org.apache.shiro=INFO
  15.  
  16. # Disable verbose logging
  17. log4j.logger.org.apache.shiro.util.ThreadContext=WARN
  18. log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN

1.3 配置shiro.ini

  1. [users]
  2. # user 'root' with password 'secret' and the 'admin' role
  3. root = secret, admin
  4. # user 'guest' with the password 'guest' and the 'guest' role
  5. guest = guest, guest
  6. # user 'presidentskroob' with password '12345' ("That's the same combination on
  7. # my luggage!!!" ;)), and role 'president'
  8. presidentskroob = 12345, president
  9. # user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
  10. darkhelmet = ludicrousspeed, darklord, schwartz
  11. # user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
  12. lonestarr = vespa, goodguy, schwartz
  13.  
  14. # -----------------------------------------------------------------------------
  15. # Roles with assigned permissions
  16. #
  17. # Each line conforms to the format defined in the
  18. # org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
  19. # -----------------------------------------------------------------------------
  20. [roles]
  21. # 'admin' role has all permissions, indicated by the wildcard '*'
  22. admin = *
  23. # The 'schwartz' role can do anything (*) with any lightsaber:
  24. schwartz = lightsaber:*
  25. # The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
  26. # license plate 'eagle5' (instance specific id)
  27. goodguy = winnebago:drive:eagle5

1.4启动类

  1. import org.apache.shiro.SecurityUtils;
  2. import org.apache.shiro.authc.*;
  3. import org.apache.shiro.config.IniSecurityManagerFactory;
  4. import org.apache.shiro.mgt.SecurityManager;
  5. import org.apache.shiro.session.Session;
  6. import org.apache.shiro.subject.Subject;
  7. import org.apache.shiro.util.Factory;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10.  
  11.  
  12. import org.apache.shiro.SecurityUtils;
  13. import org.apache.shiro.authc.*;
  14. import org.apache.shiro.config.IniSecurityManagerFactory;
  15. import org.apache.shiro.mgt.SecurityManager;
  16. import org.apache.shiro.session.Session;
  17. import org.apache.shiro.subject.Subject;
  18. import org.apache.shiro.util.Factory;
  19. import org.slf4j.Logger;
  20. import org.slf4j.LoggerFactory;
  21.  
  22.  
  23. public class Quickstart {
  24.  
  25. ? ? private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
  26.  
  27.  
  28. ? ? public static void main(String[] args) {
  29. ? ? ? ??
  30. ? ? ? ? //使用shiro.ini文件在类路径的根目录
  31. ? ? ? ? // (file:和url:前缀分别从文件和url加载):
  32. ? ? ? ? Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
  33. ? ? ? ? SecurityManager securityManager = factory.getInstance();
  34.  
  35.  
  36. ? ? ? ? SecurityUtils.setSecurityManager(securityManager);
  37.  
  38. ? ? ? ? //获取当前的用户对象Subject
  39. ? ? ? ? Subject currentUser = SecurityUtils.getSubject();
  40. ? ? ? ??
  41. ? ? ? ? //通过当前用户拿到session
  42. ? ? ? ? Session session = currentUser.getSession();
  43. ? ? ? ? session.setAttribute("someKey", "aValue");
  44. ? ? ? ? String value = (String) session.getAttribute("someKey");
  45. ? ? ? ? if (value.equals("aValue")) {
  46. // ? ? ? ? ? ?log.info("Retrieved the correct value! [" + value + "]");
  47. ? ? ? ? ? ? log.info("Subject=>session [" + value + "]");
  48. ? ? ? ? }
  49. ? ? ? ??
  50. ? ? ? ? //判断当前的用户是否被认证
  51. ? ? ? ? if (!currentUser.isAuthenticated()) {
  52. ? ? ? ? ? ? //Token :令牌,没有获取,随机
  53. ? ? ? ? ? ? UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
  54. ? ? ? ? ? ? token.setRememberMe(true);//记住我
  55. ? ? ? ? ? ? try {
  56. ? ? ? ? ? ? ? ? currentUser.login(token);//执行登录操作~
  57. ? ? ? ? ? ? } catch (UnknownAccountException uae) {//用户名不存在
  58. ? ? ? ? ? ? ? ? log.info("There is no user with username of " + token.getPrincipal());
  59. ? ? ? ? ? ? } catch (IncorrectCredentialsException ice) {//密码不对
  60. ? ? ? ? ? ? ? ? log.info("Password for account " + token.getPrincipal() + " was incorrect!");
  61. ? ? ? ? ? ? } catch (LockedAccountException lae) {//用户被锁定的
  62. ? ? ? ? ? ? ? ? log.info("The account for username " + token.getPrincipal() + " is locked. ?" +
  63. ? ? ? ? ? ? ? ? ? ? ? ? "Please contact your administrator to unlock it.");
  64. ? ? ? ? ? ? }
  65. ? ? ? ? ? ? // ... catch more exceptions here (maybe custom ones specific to your application?
  66. ? ? ? ? ? ? catch (AuthenticationException ae) {//认证异常
  67. ? ? ? ? ? ? ? ? //unexpected condition? ?error?
  68. ? ? ? ? ? ? }
  69. ? ? ? ? }
  70.  
  71. ? ? ? ? //say who they are:
  72. ? ? ? ? //print their identifying principal (in this case, a username):
  73. ? ? ? ? log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
  74.  
  75. ? ? ? ? //test a role:
  76. ? ? ? ? if (currentUser.hasRole("schwartz")) {
  77. ? ? ? ? ? ? log.info("May the Schwartz be with you!");
  78. ? ? ? ? } else {
  79. ? ? ? ? ? ? log.info("Hello, mere mortal.");
  80. ? ? ? ? }
  81. //粗粒度
  82. ? ? ? ? //test a typed permission (not instance-level)
  83. ? ? ? ? if (currentUser.isPermitted("lightsaber:wield")) {
  84. ? ? ? ? ? ? log.info("You may use a lightsaber ring. ?Use it wisely.");
  85. ? ? ? ? } else {
  86. ? ? ? ? ? ? log.info("Sorry, lightsaber rings are for schwartz masters only.");
  87. ? ? ? ? }
  88. //细粒度
  89. ? ? ? ? //a (very powerful) Instance Level permission:
  90. ? ? ? ? if (currentUser.isPermitted("winnebago:drive:eagle5")) {
  91. ? ? ? ? ? ? log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. ?" +
  92. ? ? ? ? ? ? ? ? ? ? "Here are the keys - have fun!");
  93. ? ? ? ? } else {
  94. ? ? ? ? ? ? log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
  95. ? ? ? ? }
  96.  
  97. ? ? ? ? //all done - log out!
  98. ? ? ? ? currentUser.logout();
  99.  
  100. ? ? ? ? System.exit(0);
  101. ? ? }
  102. }

二、springboot结合shiro使用

2.1准备数据库

在这里插入图片描述

pom.xml添加依赖:

  1. ? <dependencies>
  2. ? ? ? ? <!--
  3. ? ? ? ? Subject 用户
  4. ? ? ? ? SecurityManager 管理所有用户
  5. ? ? ? ? Realm 连接数据
  6. ? ? ? ? -->
  7. ? ? ? ? <dependency>
  8. ? ? ? ? ? ? <groupId>org.apache.shiro</groupId>
  9. ? ? ? ? ? ? <artifactId>shiro-core</artifactId>
  10. ? ? ? ? ? ? <version>1.7.1</version>
  11. ? ? ? ? </dependency>
  12. ? ? ? ? <!-- configure logging-->
  13. ? ? ? ? <dependency>
  14. ? ? ? ? ? ? <groupId>org.slf4j</groupId>
  15. ? ? ? ? ? ? <artifactId>jcl-over-slf4j</artifactId>
  16. ? ? ? ? ? ? <version>1.7.21</version>
  17. ? ? ? ? </dependency>
  18. ? ? ? ? <!--调用日志框架-->
  19. ? ? ? ? <dependency>
  20. ? ? ? ? ? ? <groupId>org.slf4j</groupId>
  21. ? ? ? ? ? ? <artifactId>slf4j-log4j12</artifactId>
  22. ? ? ? ? ? ? <version>1.7.21</version>
  23. ? ? ? ? </dependency>
  24. ? ? ? ? <dependency>
  25. ? ? ? ? ? ? <groupId>log4j</groupId>
  26. ? ? ? ? ? ? <artifactId>log4j</artifactId>
  27. ? ? ? ? ? ? <version>1.2.17</version>
  28. ? ? ? ? </dependency>
  29. ? ? ? ? <dependency>
  30. ? ? ? ? ? ? <groupId>com.github.theborakompanioni</groupId>
  31. ? ? ? ? ? ? <artifactId>thymeleaf-extras-shiro</artifactId>
  32. ? ? ? ? ? ? <version>2.0.0</version>
  33. ? ? ? ? </dependency>
  34. ? ? ? ? <!--连接数据-->
  35. ? ? ? ? <dependency>
  36. ? ? ? ? ? ? <groupId>mysql</groupId>
  37. ? ? ? ? ? ? <artifactId>mysql-connector-java</artifactId>
  38. ? ? ? ? </dependency>
  39. ? ? ? ? <dependency>
  40. ? ? ? ? ? ? <groupId>com.alibaba</groupId>
  41. ? ? ? ? ? ? <artifactId>druid</artifactId>
  42. ? ? ? ? ? ? <version>1.2.5</version>
  43. ? ? ? ? </dependency>
  44. ? ? ? ? <dependency>
  45. ? ? ? ? ? ? <groupId>org.mybatis.spring.boot</groupId>
  46. ? ? ? ? ? ? <artifactId>mybatis-spring-boot-starter</artifactId>
  47. ? ? ? ? ? ? <version>2.2.0</version>
  48. ? ? ? ? </dependency>
  49. ? ? ? ? <!--shiro整合spring的包-->
  50. ? ? ? ? <!--https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring-->
  51. ? ? ? ? <dependency>
  52. ? ? ? ? ? ? <groupId>org.apache.shiro</groupId>
  53. ? ? ? ? ? ? <artifactId>shiro-spring</artifactId>
  54. ? ? ? ? ? ? <version>1.7.1</version>
  55. ? ? ? ? </dependency>
  56. ? ? ? ? <dependency>
  57. ? ? ? ? ? ? <groupId>org.springframework.boot</groupId>
  58. ? ? ? ? ? ? <artifactId>spring-boot-starter-web</artifactId>
  59. ? ? ? ? </dependency>
  60. ? ? ? ? <dependency>
  61. ? ? ? ? ? ? <groupId>org.thymeleaf</groupId>
  62. ? ? ? ? ? ? <artifactId>thymeleaf-spring5</artifactId>
  63. ? ? ? ? </dependency>
  64. ? ? ? ? <dependency>
  65. ? ? ? ? ? ? <groupId>org.thymeleaf.extras</groupId>
  66. ? ? ? ? ? ? <artifactId>thymeleaf-extras-java8time</artifactId>
  67. ? ? ? ? </dependency>
  68. ? ? ? ? <dependency>
  69. ? ? ? ? ? ? <groupId>org.projectlombok</groupId>
  70. ? ? ? ? ? ? <artifactId>lombok</artifactId>
  71. ? ? ? ? ? ? <version>1.18.16</version>
  72. ? ? ? ? </dependency>
  73. ? ? </dependencies>

2.2配置yaml

  1. spring:
  2. ? datasource:
  3. ? ? username: root
  4. ? ? password: 123456
  5. ? ? #假如时区报错了就增减一个时区的配置就ok了:servletTimezone=UTC
  6. ? ? url: jdbc:mysql://localhost:3306/security?servletTimezone=UTC&useUnicode=true&characterEncodeing=utf-8
  7. ? ? driver-class-name: com.mysql.cj.jdbc.Driver
  8. ? ? type: com.alibaba.druid.pool.DruidDataSource
  9.  
  10. ? ? #Spring Boot 默认是不注入这些属性值的,需要自己绑定
  11. ? ? #druid 数据源专有配置
  12. ? ? initialSize: 5
  13. ? ? minIdle: 5
  14. ? ? maxActive: 20
  15. ? ? maxWait: 60000
  16. ? ? timeBetweenEvictionRunsMillis: 60000
  17. ? ? minEvictableIdleTimeMillis: 300000
  18. ? ? validationQuery: SELECT 1 FROM DUAL
  19. ? ? testWhileIdle: true
  20. ? ? testOnBorrow: false
  21. ? ? testOnReturn: false
  22. ? ? poolPreparedStatements: true
  23.  
  24. ? ? #配置监控统计拦截的filters,stat:监控日志,log4j:日志记录,wall,预防sql注入
  25. ? ? #如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
  26. ? ? #则导入log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
  27.  
  28. ? ? filters: stat,wall,log4j
  29. ? ? maxPoolPreparedStatementPerConnectionSize: 20
  30. ? ? useGlobalDataSourceStat: true
  31. ? ? connectionProperties: durid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
  32. mybatis:
  33. ? mapper-locations: classpath:mapper/*.xml

使用thymeleaf写几个页面:

在这里插入图片描述

index.html

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org"
  3. ?xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
  4.  
  5. <head>
  6. ? ? <meta charset="UTF-8">
  7. ? ? <title>首页</title>
  8. </head>
  9. <body>
  10. <h1>首页</h1>
  11. <p>[[${msg}]]</p>
  12.  
  13. <div th:if="session.LoginUser==null"><a th:href="@{toLogin}" rel="external nofollow" >登录</a></div>
  14. <hr>
  15. ? ? <div shiro:hasPermission="user:add">
  16. <a th:href="@{/user/add}" rel="external nofollow" >add.html</a></div>
  17. ? ? <div shiro:hasPermission="user:update">
  18. <a th:href="@{/user/update}" rel="external nofollow" >update.html</a>
  19. </div>
  20. </body>
  21. </html>

login.html

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <head>
  5. ? ? <meta charset="UTF-8">
  6. ? ? <title>Title</title>
  7. </head>
  8. <body>
  9. <h1>登录</h1>
  10. <hr>
  11. <p th:text="${msg}" style="color:red"></p>
  12. <form th:action="@{/login}">
  13. ? ? <p>用户名<input type="text" name="username"></p>
  14. ? ? <p>密码<input type="text" name="password"></p>
  15. ? ? <p><input type="submit" value="登录"></p>
  16. </form>
  17. </body>
  18. </html>

add.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. ? ? <meta charset="UTF-8">
  5. ? ? <title>Title</title>
  6. </head>
  7. <body>
  8. <h4>add</h4>
  9. </body>
  10. </html>

update.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. ? ? <meta charset="UTF-8">
  5. ? ? <title>Title</title>
  6. </head>
  7. <body>
  8. <h4>update</h4>
  9. </body>
  10. </html>

三、实体类

  1. package com.jsxl.pojo;
  2.  
  3. import lombok.AllArgsConstructor;
  4. import lombok.Data;
  5. import lombok.NoArgsConstructor;
  6.  
  7. @Data
  8. @AllArgsConstructor
  9. @NoArgsConstructor
  10. public class User {
  11. ? ? private int id;
  12. ? ? private String name;
  13. ? ? private String password;
  14. ? ? private String auth;
  15. }

3.1UserMapper即UserMapper.xml

  1. package com.jsxl.mapper;
  2.  
  3. import com.jsxl.pojo.User;
  4. import org.apache.ibatis.annotations.Mapper;
  5. import org.springframework.stereotype.Repository;
  6.  
  7. @Repository
  8. @Mapper
  9. public interface UserMapper {
  10. ? ? public User queryUserByName(String name);
  11. }
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. ? ? ? ? PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. ? ? ? ? "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  5. <mapper namespace="com.jsxl.mapper.UserMapper" >
  6. ? ? <select id="queryUserByName" parameterType="String" resultType="com.jsxl.pojo.User">
  7. ? ? ? ? select * from security.user where name=#{name}
  8. ? ? </select>
  9.  
  10. </mapper>

UserController(简单使用这里直接调用Mapper):

  1. package com.jsxl.controller;
  2.  
  3. import org.apache.shiro.SecurityUtils;
  4. import org.apache.shiro.authc.IncorrectCredentialsException;
  5. import org.apache.shiro.authc.UnknownAccountException;
  6. import org.apache.shiro.authc.UsernamePasswordToken;
  7. import org.apache.shiro.subject.Subject;
  8. import org.springframework.stereotype.Controller;
  9. import org.springframework.ui.Model;
  10. import org.springframework.ui.ModelMap;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.ResponseBody;
  13.  
  14. @Controller
  15. public class UserController {
  16.  
  17. ? ? @RequestMapping({"/","/index"})
  18. ? ? public String toIndex(ModelMap map){
  19. ? ? ? ? map.put("msg","hello shiro");
  20. ? ? ? ? return "index";
  21. ? ? }
  22. ? ? @RequestMapping("user/add")
  23. ? ? public String add(){
  24. ? ? ? ? return "user/add";
  25. ? ? }
  26.  
  27. ? ? @RequestMapping("user/update")
  28. ? ? public String update(){
  29. ? ? ? ? return "user/update";
  30. ? ? }
  31.  
  32. ? ? @RequestMapping("/toLogin")
  33. ? ? public String toLogin(){
  34. ? ? ? ? return "login";
  35. ? ? }
  36.  
  37. ? ? @RequestMapping("/login")
  38. ? ? public String login(String username, String password, Model model){
  39. ? ? ? ? //获取当前用户
  40. ? ? ? ? Subject subject = SecurityUtils.getSubject();
  41. ? ? ? ? //封装用户的登录数据
  42. ? ? ? ? UsernamePasswordToken token = new UsernamePasswordToken(username, password);
  43. ? ? ? ? //这边用了会存在整个的类里面
  44. ? ? ? ? try{
  45. ? ? ? ? ? ? subject.login(token);//执行登录的方法,如果没有异常就说明ok了
  46. ? ? ? ? ? ? return "index";
  47. ? ? ? ? }catch(UnknownAccountException e){//用户名不存在
  48. ? ? ? ? ? ? model.addAttribute("msg","用户名不存在");
  49. ? ? ? ? ? ? return "login";
  50. ? ? ? ? }catch(IncorrectCredentialsException e){//密码不对
  51. ? ? ? ? ? ? model.addAttribute("msg","密码错误");
  52. ? ? ? ? ? ? return "login";
  53. ? ? ? ? }
  54. ? ? }
  55. ? ? @RequestMapping("/noauth")
  56. ? ? @ResponseBody
  57. ? ? ? ? public String unauthorized(){
  58. ? ? ? ? ? ? return "未经授权无法访问此页面";
  59. ? ? ? ? }
  60. }

四、shiro的配置类

  1. package com.jsxl.config;
  2.  
  3. import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
  4. import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
  5. import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
  6. import org.springframework.beans.factory.annotation.Qualifier;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9.  
  10. import java.util.LinkedHashMap;
  11. import java.util.Map;
  12.  
  13. @Configuration
  14. public class ShiroConfig {
  15. ? ? //ShiroFilterFactoryBean
  16. ? ? @Bean
  17. ? ? public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")
  18. ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? DefaultWebSecurityManager defaultWebSecurityManager){
  19. ? ? ? ? ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
  20. ? ? ? ? //设置安全管理器
  21. ? ? ? ? bean.setSecurityManager(defaultWebSecurityManager);
  22. ? ? ? ? //添加shiro内置过滤器
  23. ? ? ? ? /*
  24. ? ? ? ? anon :无需认证就可以访问
  25. ? ? ? ? autho:必须认证了才能访问
  26. ? ? ? ? user:必须拥有 记住我 功能才能用
  27. ? ? ? ? perms:拥有对某个资源的权限才能访问
  28. ? ? ? ? role: 拥有某个角色权限才能访问
  29. ? ? ? ? ?*/
  30.  
  31. ? ? ? ? //设置一个过滤器链 点击源码看需要什么参数,由于是链表用LinkedHashMap ? ?拦截
  32. ? ? ? ? Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
  33.  
  34.  
  35. ? ? ? ? //授权 ?正常情况下 没有授权会跳到未授权的页面
  36. ? ? ? ? filterChainDefinitionMap.put("/user/add","perms[user:add]");
  37. ? ? ? ? filterChainDefinitionMap.put("/user/update","perms[user:update]");
  38. // ? ? ? ?filterChainDefinitionMap.put("/user/add","authc");
  39. // ? ? ? ?filterChainDefinitionMap.put("/user/update","authc");
  40. ? ? ? ? filterChainDefinitionMap.put("/user/*","authc");
  41. ? ? ? ? bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
  42.  
  43. ? ? ? ? //设置登录请求
  44. ? ? ? ? bean.setLoginUrl("/toLogin");
  45. ? ? ? ? //未授权页面
  46. ? ? ? ? bean.setUnauthorizedUrl("/noauth");
  47. ? ? ? ? return bean;
  48.  
  49. ? ? }
  50. ? ? //DefaultWebSecurityManager 2
  51. ? ? @Bean(name = "securityManager")
  52. ? ? public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
  53. ? ? ? ? DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
  54. ? ? ? ? //关联UserRealm
  55. ? ? ? ? ?securityManager.setRealm(userRealm);
  56. ? ? ? ? ?return securityManager;
  57. ? ? }
  58.  
  59. ? ? //创建realm 对象 ,需要自定义类 1
  60. ? ? @Bean(name = "userRealm")//正常情况下我们的方法名就是他
  61. ? ? public UserRealm userRealm(){
  62. ? ? ? ? return new UserRealm();
  63. ? ? }
  64.  
  65. ? ? @Bean
  66. ? ? public ShiroDialect getShiroDialect(){
  67. ? ? ? ? return new ShiroDialect();
  68. ? ? }
  69. }
  1. package com.jsxl.config;
  2.  
  3. import com.jsxl.mapper.UserMapper;
  4. import com.jsxl.pojo.User;
  5. import com.jsxl.service.UserServiceImpl;
  6. import org.apache.shiro.SecurityUtils;
  7. import org.apache.shiro.authc.*;
  8. import org.apache.shiro.authz.AuthorizationInfo;
  9. import org.apache.shiro.authz.SimpleAuthorizationInfo;
  10. import org.apache.shiro.realm.AuthorizingRealm;
  11. import org.apache.shiro.session.Session;
  12. import org.apache.shiro.subject.PrincipalCollection;
  13. import org.apache.shiro.subject.Subject;
  14. import org.springframework.beans.factory.annotation.Autowired;
  15.  
  16. //自定义的UserRealm
  17. public class UserRealm extends AuthorizingRealm {
  18.  
  19. ? ? @Autowired
  20. ? ? UserMapper userMapper;
  21.  
  22. ? ? @Override//授权
  23. ? ? protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
  24. ? ? ? ? System.out.println("执行了=>授权doGrtAuthorizationInfo");
  25. ? ? ? ? SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
  26. // ? ? ? ?info.addStringPermission("user:add");
  27. ? ? ? ? //拿到当前登录的这个对象
  28. ? ? ? ? Subject subject = SecurityUtils.getSubject();
  29. ? ? ? ? User currentUser = (User)subject.getPrincipal();//拿到user对象
  30. ? ? ? ? //设置当前登录的用户的权限
  31. ? ? ? ? info.addStringPermission(currentUser.getAuth());
  32.  
  33. ? ? ? ? return info;//授权不能return null
  34. ? ? }
  35.  
  36. ? ? @Override//认证
  37. ? ? protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
  38. ? ? ? ? System.out.println("执行了=>认证doGrtAuthorizationInfo");
  39.  
  40.  
  41. ? ? ? ? UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;//获取信息 全局关系
  42.  
  43. ? ? ? ? User user = userMapper.queryUserByName(userToken.getUsername());
  44. ? ? ? ? Subject currentSubject = SecurityUtils.getSubject();
  45. ? ? ? ? Session session = currentSubject.getSession();
  46. ? ? ? ? session.setAttribute("LoginUser",user);
  47.  
  48. ? ? ? ? if(user==null){
  49. ? ? ? ? ? ? return null;//抛出异常 UnknownAccountException
  50. ? ? ? ? }
  51. ? ? ? ? //密码验证 ?shiro做 有可能会泄露 加密了
  52. ? ? ? ? return new SimpleAuthenticationInfo(user,user.getPassword(),"");
  53. ? ? }
  54. }

五、启动类

  1. package com.jsxl;
  2.  
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5.  
  6. @SpringBootApplication
  7. public class ShiroSpringbootApplication {
  8.  
  9. ? ? public static void main(String[] args) {
  10. ? ? ? ? SpringApplication.run(ShiroSpringbootApplication.class, args);
  11. ? ? }
  12.  
  13. }

测试:

root用户

在这里插入图片描述

test用户

在这里插入图片描述

5.1SecurityUtils. getSubject()

SecurityUtils. getSubject(),可以获得当前正在执行的Subject. 一个Subject就是一个应用程序的用户的安全。实际上称它为“User”,但太多的应用程序拥有已经拥有自己的 User 类/框架的现有 API,我们不想与它们发生冲突。此外,在安全领域,该术语Subject实际上是公认的术语。

getSubject()独立应用程序中的调用可能会Subject在特定于应用程序的位置返回基于用户数据的 ,并且在服务器环境(例如 Web 应用程序)中,它Subject根据与当前线程或传入请求关联的用户数据获取。

  1. Session session = currentUser.getSession();
  2. session.setAttribute( "someKey", "aValue" );

Session是一个特定于 Shiro 的实例,它提供了您习惯于使用常规 HttpSessions 的大部分内容,但还有一些额外的好处和一个很大的区别:它不需要 HTTP 环境!

到此这篇关于Springboot-Shiro基本使用详情介绍的文章就介绍到这了,更多相关Springboot-Shiro使用 内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持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号