pom依赖

springboot相关

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-test</artifactId>
  8. <scope>test</scope>
  9. </dependency>
  10. <!-- devtools -->
  11. <dependency>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-devtools</artifactId>
  14. <optional>true</optional>
  15. </dependency>
  16. <!-- 实现自定义的state缓存 -->
  17. <dependency>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter-data-redis</artifactId>
  20. </dependency>
  21. <!-- thymeleaf -->
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  25. </dependency>

hutool相关

  1. <dependency>
  2. <groupId>cn.hutool</groupId>
  3. <artifactId>hutool-http</artifactId>
  4. <version>5.1.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>cn.hutool</groupId>
  8. <artifactId>hutool-crypto</artifactId>
  9. <version>5.1.0</version>
  10. <scope>provided</scope>
  11. </dependency>

JustAuth

  1. <!-- JustAuth1.9.4版本后,如果需要使用支付宝登录,需要单独引用该依赖 -->
  2. <dependency>
  3. <groupId>com.alipay.sdk</groupId>
  4. <artifactId>alipay-sdk-java</artifactId>
  5. <version>3.7.4.ALL</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>me.zhyd.oauth</groupId>
  9. <artifactId>JustAuth</artifactId>
  10. <version>1.16.4</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>cn.hutool</groupId>
  14. <artifactId>hutool-http</artifactId>
  15. <version>5.1.0</version>
  16. </dependency>
  17. <dependency>
  18. <groupId>com.squareup.okhttp3</groupId>
  19. <artifactId>okhttp</artifactId>
  20. <version>4.2.2</version>
  21. <scope>provided</scope>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.apache.httpcomponents</groupId>
  25. <artifactId>httpclient</artifactId>
  26. <version>4.5.10</version>
  27. <scope>provided</scope>
  28. </dependency>
  29. <build>
  30. <plugins>
  31. <plugin>
  32. <groupId>org.springframework.boot</groupId>
  33. <artifactId>spring-boot-maven-plugin</artifactId>
  34. <version>2.2.2.RELEASE</version>
  35. <configuration>
  36. <mainClass>me.zhyd.justauth.JustauthDemoApplication</mainClass>
  37. <includeSystemScope>true</includeSystemScope>
  38. </configuration>
  39. <executions>
  40. <execution>
  41. <goals>
  42. <goal>repackage</goal>
  43. </goals>
  44. </execution>
  45. </executions>
  46. </plugin>
  47. </plugins>
  48. </build>
  1. server.port=8443
  2. spring.thymeleaf.cache=false
  3. spring.devtools.restart.additional-paths=src/main/java
  4. spring.devtools.restart.exclude=static/**,public/**
  5. # \u96C6\u6210redis\u5B9E\u73B0\u81EA\u5B9A\u4E49\u7684state\u7F13\u5B58
  6. spring.redis.database=0
  7. spring.redis.host=localhost
  8. spring.redis.port=6379
  9. spring.redis.password=123456

redis相关

JustAuth 里的redis类

AuthStateRedisCache.java
RedisConfig.java

若依摘录

  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. <groupId>com.ruoyi</groupId>
  6. <artifactId>ruoyi</artifactId>
  7. <version>3.8.1</version>
  8. <packaging>jar</packaging>
  9. <name>ruoyi</name>
  10. <url>http://www.ruoyi.vip</url>
  11. <description>若依管理系统</description>
  12. <parent>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-parent</artifactId>
  15. <version>2.5.9</version>
  16. <relativePath />
  17. </parent>
  18. <properties>
  19. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  20. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  21. <java.version>1.8</java.version>
  22. <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
  23. <mybatis.spring.boot.starter.version>2.2.0</mybatis.spring.boot.starter.version>
  24. <pagehelper.spring.boot.starter.version>1.4.0</pagehelper.spring.boot.starter.version>
  25. <fastjson.version>1.2.79</fastjson.version>
  26. <druid.version>1.2.8</druid.version>
  27. <commons.io.version>2.11.0</commons.io.version>
  28. <commons.fileupload.version>1.4</commons.fileupload.version>
  29. <commons.collections.version>3.2.2</commons.collections.version>
  30. <bitwalker.version>1.21</bitwalker.version>
  31. <jwt.version>0.9.1</jwt.version>
  32. <kaptcha.version>2.3.2</kaptcha.version>
  33. <swagger.version>3.0.0</swagger.version>
  34. <poi.version>4.1.2</poi.version>
  35. <oshi.version>5.8.6</oshi.version>
  36. <jna.version>5.10.0</jna.version>
  37. <velocity.version>2.3</velocity.version>
  38. </properties>
  39. <dependencies>
  40. <!-- SpringBoot 核心包 -->
  41. <dependency>
  42. <groupId>org.springframework.boot</groupId>
  43. <artifactId>spring-boot-starter</artifactId>
  44. </dependency>
  45. <!-- SpringBoot 测试 -->
  46. <dependency>
  47. <groupId>org.springframework.boot</groupId>
  48. <artifactId>spring-boot-starter-test</artifactId>
  49. <scope>test</scope>
  50. </dependency>
  51. <!-- SpringBoot 拦截器 -->
  52. <dependency>
  53. <groupId>org.springframework.boot</groupId>
  54. <artifactId>spring-boot-starter-aop</artifactId>
  55. </dependency>
  56. <!-- SpringBoot Web容器 -->
  57. <dependency>
  58. <groupId>org.springframework.boot</groupId>
  59. <artifactId>spring-boot-starter-web</artifactId>
  60. </dependency>
  61. <!-- spring-boot-devtools -->
  62. <dependency>
  63. <groupId>org.springframework.boot</groupId>
  64. <artifactId>spring-boot-devtools</artifactId>
  65. <optional>true</optional> <!-- 表示依赖不会传递 -->
  66. </dependency>
  67. <!-- spring security 安全认证 -->
  68. <dependency>
  69. <groupId>org.springframework.boot</groupId>
  70. <artifactId>spring-boot-starter-security</artifactId>
  71. </dependency>
  72. <!-- redis 缓存操作 -->
  73. <dependency>
  74. <groupId>org.springframework.boot</groupId>
  75. <artifactId>spring-boot-starter-data-redis</artifactId>
  76. </dependency>
  77. <!-- pool 对象池 -->
  78. <dependency>
  79. <groupId>org.apache.commons</groupId>
  80. <artifactId>commons-pool2</artifactId>
  81. </dependency>
  82. <!-- Mysql驱动包 -->
  83. <dependency>
  84. <groupId>mysql</groupId>
  85. <artifactId>mysql-connector-java</artifactId>
  86. <scope>runtime</scope>
  87. </dependency>
  88. <!-- SpringBoot集成mybatis框架 -->
  89. <dependency>
  90. <groupId>org.mybatis.spring.boot</groupId>
  91. <artifactId>mybatis-spring-boot-starter</artifactId>
  92. <version>${mybatis.spring.boot.starter.version}</version>
  93. </dependency>
  94. <!-- pagehelper 分页插件 -->
  95. <dependency>
  96. <groupId>com.github.pagehelper</groupId>
  97. <artifactId>pagehelper-spring-boot-starter</artifactId>
  98. <version>${pagehelper.spring.boot.starter.version}</version>
  99. </dependency>
  100. <!-- 阿里数据库连接池 -->
  101. <dependency>
  102. <groupId>com.alibaba</groupId>
  103. <artifactId>druid-spring-boot-starter</artifactId>
  104. <version>${druid.version}</version>
  105. </dependency>
  106. <!-- 自定义验证注解 -->
  107. <dependency>
  108. <groupId>org.springframework.boot</groupId>
  109. <artifactId>spring-boot-starter-validation</artifactId>
  110. </dependency>
  111. <!-- 常用工具类 -->
  112. <dependency>
  113. <groupId>org.apache.commons</groupId>
  114. <artifactId>commons-lang3</artifactId>
  115. </dependency>
  116. <!-- io常用工具类 -->
  117. <dependency>
  118. <groupId>commons-io</groupId>
  119. <artifactId>commons-io</artifactId>
  120. <version>${commons.io.version}</version>
  121. </dependency>
  122. <!-- 文件上传工具类 -->
  123. <dependency>
  124. <groupId>commons-fileupload</groupId>
  125. <artifactId>commons-fileupload</artifactId>
  126. <version>${commons.fileupload.version}</version>
  127. </dependency>
  128. <!-- 解析客户端操作系统、浏览器等 -->
  129. <dependency>
  130. <groupId>eu.bitwalker</groupId>
  131. <artifactId>UserAgentUtils</artifactId>
  132. <version>${bitwalker.version}</version>
  133. </dependency>
  134. <!-- 阿里JSON解析器 -->
  135. <dependency>
  136. <groupId>com.alibaba</groupId>
  137. <artifactId>fastjson</artifactId>
  138. <version>${fastjson.version}</version>
  139. </dependency>
  140. <!-- Spring框架基本的核心工具-->
  141. <dependency>
  142. <groupId>org.springframework</groupId>
  143. <artifactId>spring-context-support</artifactId>
  144. </dependency>
  145. <!-- Token生成与解析-->
  146. <dependency>
  147. <groupId>io.jsonwebtoken</groupId>
  148. <artifactId>jjwt</artifactId>
  149. <version>${jwt.version}</version>
  150. </dependency>
  151. <!-- Jaxb -->
  152. <dependency>
  153. <groupId>javax.xml.bind</groupId>
  154. <artifactId>jaxb-api</artifactId>
  155. </dependency>
  156. <!-- Swagger3依赖 -->
  157. <dependency>
  158. <groupId>io.springfox</groupId>
  159. <artifactId>springfox-boot-starter</artifactId>
  160. <version>${swagger.version}</version>
  161. <exclusions>
  162. <exclusion>
  163. <groupId>io.swagger</groupId>
  164. <artifactId>swagger-models</artifactId>
  165. </exclusion>
  166. </exclusions>
  167. </dependency>
  168. <!-- 防止进入swagger页面报类型转换错误,排除3.0.0中的引用,手动增加1.6.2版本 -->
  169. <dependency>
  170. <groupId>io.swagger</groupId>
  171. <artifactId>swagger-models</artifactId>
  172. <version>1.6.2</version>
  173. </dependency>
  174. <!-- 获取系统信息 -->
  175. <dependency>
  176. <groupId>com.github.oshi</groupId>
  177. <artifactId>oshi-core</artifactId>
  178. <version>${oshi.version}</version>
  179. </dependency>
  180. <!-- excel工具 -->
  181. <dependency>
  182. <groupId>org.apache.poi</groupId>
  183. <artifactId>poi-ooxml</artifactId>
  184. <version>${poi.version}</version>
  185. </dependency>
  186. <!-- velocity代码生成使用模板 -->
  187. <dependency>
  188. <groupId>org.apache.velocity</groupId>
  189. <artifactId>velocity-engine-core</artifactId>
  190. <version>${velocity.version}</version>
  191. </dependency>
  192. <!-- collections工具类 -->
  193. <dependency>
  194. <groupId>commons-collections</groupId>
  195. <artifactId>commons-collections</artifactId>
  196. <version>${commons.collections.version}</version>
  197. </dependency>
  198. <!-- 定时任务 -->
  199. <dependency>
  200. <groupId>org.quartz-scheduler</groupId>
  201. <artifactId>quartz</artifactId>
  202. <exclusions>
  203. <exclusion>
  204. <groupId>com.mchange</groupId>
  205. <artifactId>c3p0</artifactId>
  206. </exclusion>
  207. </exclusions>
  208. </dependency>
  209. <!-- 验证码 -->
  210. <dependency>
  211. <groupId>com.github.penggle</groupId>
  212. <artifactId>kaptcha</artifactId>
  213. <version>${kaptcha.version}</version>
  214. <exclusions>
  215. <exclusion>
  216. <artifactId>javax.servlet-api</artifactId>
  217. <groupId>javax.servlet</groupId>
  218. </exclusion>
  219. </exclusions>
  220. </dependency>
  221. </dependencies>
  222. <build>
  223. <finalName>${project.artifactId}</finalName>
  224. <plugins>
  225. <plugin>
  226. <groupId>org.springframework.boot</groupId>
  227. <artifactId>spring-boot-maven-plugin</artifactId>
  228. <configuration>
  229. <fork>true</fork> <!-- 如果没有该配置,devtools不会生效 -->
  230. </configuration>
  231. </plugin>
  232. </plugins>
  233. </build>
  234. <repositories>
  235. <repository>
  236. <id>public</id>
  237. <name>aliyun nexus</name>
  238. <url>https://maven.aliyun.com/repository/public</url>
  239. <releases>
  240. <enabled>true</enabled>
  241. </releases>
  242. </repository>
  243. </repositories>
  244. <pluginRepositories>
  245. <pluginRepository>
  246. <id>public</id>
  247. <name>aliyun nexus</name>
  248. <url>https://maven.aliyun.com/repository/public</url>
  249. <releases>
  250. <enabled>true</enabled>
  251. </releases>
  252. <snapshots>
  253. <enabled>false</enabled>
  254. </snapshots>
  255. </pluginRepository>
  256. </pluginRepositories>
  257. </project>
  1. # 项目相关配置
  2. ruoyi:
  3. # 名称
  4. name: RuoYi
  5. # 版本
  6. version: 3.8.1
  7. # 版权年份
  8. copyrightYear: 2022
  9. # 实例演示开关
  10. demoEnabled: true
  11. # 文件路径 示例( Windows配置D:/ruoyi/uploadPath,Linux配置 /home/ruoyi/uploadPath)
  12. profile: D:/ruoyi/uploadPath
  13. # 获取ip地址开关
  14. addressEnabled: false
  15. # 验证码类型 math 数组计算 char 字符验证
  16. captchaType: math
  17. # 开发环境配置
  18. server:
  19. # 服务器的HTTP端口,默认为8080
  20. port: 8080
  21. servlet:
  22. # 应用的访问路径
  23. context-path: /
  24. tomcat:
  25. # tomcat的URI编码
  26. uri-encoding: UTF-8
  27. # 连接数满后的排队数,默认为100
  28. accept-count: 1000
  29. threads:
  30. # tomcat最大线程数,默认为200
  31. max: 800
  32. # Tomcat启动初始化的线程数,默认值10
  33. min-spare: 100
  34. # 日志配置
  35. logging:
  36. level:
  37. com.ruoyi: debug
  38. org.springframework: warn
  39. # Spring配置
  40. spring:
  41. # 资源信息
  42. messages:
  43. # 国际化资源文件路径
  44. basename: i18n/messages
  45. profiles:
  46. active: druid
  47. # 文件上传
  48. servlet:
  49. multipart:
  50. # 单个文件大小
  51. max-file-size: 10MB
  52. # 设置总上传的文件大小
  53. max-request-size: 20MB
  54. # 服务模块
  55. devtools:
  56. restart:
  57. # 热部署开关
  58. enabled: true
  59. # redis 配置
  60. redis:
  61. # 地址
  62. host: localhost
  63. # 端口,默认为6379
  64. port: 6379
  65. # 数据库索引
  66. database: 0
  67. # 密码
  68. password:
  69. # 连接超时时间
  70. timeout: 10s
  71. lettuce:
  72. pool:
  73. # 连接池中的最小空闲连接
  74. min-idle: 0
  75. # 连接池中的最大空闲连接
  76. max-idle: 8
  77. # 连接池的最大数据库连接数
  78. max-active: 8
  79. # #连接池最大阻塞等待时间(使用负值表示没有限制)
  80. max-wait: -1ms
  81. # token配置
  82. token:
  83. # 令牌自定义标识
  84. header: Authorization
  85. # 令牌密钥
  86. secret: abcdefghijklmnopqrstuvwxyz
  87. # 令牌有效期(默认30分钟)
  88. expireTime: 30
  89. # MyBatis配置
  90. mybatis:
  91. # 搜索指定包别名
  92. typeAliasesPackage: com.ruoyi.project.**.domain
  93. # 配置mapper的扫描,找到所有的mapper.xml映射文件
  94. mapperLocations: classpath*:mybatis/**/*Mapper.xml
  95. # 加载全局的配置文件
  96. configLocation: classpath:mybatis/mybatis-config.xml
  97. # PageHelper分页插件
  98. pagehelper:
  99. helperDialect: mysql
  100. supportMethodsArguments: true
  101. params: count=countSql
  102. # Swagger配置
  103. swagger:
  104. # 是否开启swagger
  105. enabled: true
  106. # 请求前缀
  107. pathMapping: /dev-api
  108. # 防止XSS攻击
  109. xss:
  110. # 过滤开关
  111. enabled: true
  112. # 排除链接(多个用逗号分隔)
  113. excludes: /system/notice
  114. # 匹配链接
  115. urlPatterns: /system/*,/monitor/*,/tool/*
  116. # 代码生成
  117. gen:
  118. # 作者
  119. author: ruoyi
  120. # 默认生成包路径 system 需改成自己的模块名称 如 system monitor tool
  121. packageName: com.ruoyi.project.system
  122. # 自动去除表前缀,默认是true
  123. autoRemovePre: false
  124. # 表前缀(生成类名不会包含表前缀,多个用逗号分隔)
  125. tablePrefix: sys_
  1. # 数据源配置
  2. spring:
  3. datasource:
  4. type: com.alibaba.druid.pool.DruidDataSource
  5. driverClassName: com.mysql.cj.jdbc.Driver
  6. druid:
  7. # 主库数据源
  8. master:
  9. url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
  10. username: root
  11. password: root
  12. # 从库数据源
  13. slave:
  14. # 从数据源开关/默认关闭
  15. enabled: false
  16. url:
  17. username:
  18. password:
  19. # 初始连接数
  20. initialSize: 5
  21. # 最小连接池数量
  22. minIdle: 10
  23. # 最大连接池数量
  24. maxActive: 20
  25. # 配置获取连接等待超时的时间
  26. maxWait: 60000
  27. # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
  28. timeBetweenEvictionRunsMillis: 60000
  29. # 配置一个连接在池中最小生存的时间,单位是毫秒
  30. minEvictableIdleTimeMillis: 300000
  31. # 配置一个连接在池中最大生存的时间,单位是毫秒
  32. maxEvictableIdleTimeMillis: 900000
  33. # 配置检测连接是否有效
  34. validationQuery: SELECT 1 FROM DUAL
  35. testWhileIdle: true
  36. testOnBorrow: false
  37. testOnReturn: false
  38. webStatFilter:
  39. enabled: true
  40. statViewServlet:
  41. enabled: true
  42. # 设置白名单,不填则允许所有访问
  43. allow:
  44. url-pattern: /druid/*
  45. # 控制台管理用户名和密码
  46. login-username: ruoyi
  47. login-password: 123456
  48. filter:
  49. stat:
  50. enabled: true
  51. # 慢SQL记录
  52. log-slow-sql: true
  53. slow-sql-millis: 1000
  54. merge-sql: true
  55. wall:
  56. config:
  57. multi-statement-allow: true

Application Version: ${ruoyi.version} Spring Boot Version: ${spring-boot.version} //////////////////////////////////////////////////////////////////// // .____ .___ // // | | ___________ __| _/ // // | | / _ \_ __ \/ __ | // // | |__( <_> ) | \/ /_/ | // // |_______ \____/|__| \____ | // // \/ \/ // ////////////////////////////////////////////////////////////////////

单应用

认证授权分析

  1. package com.ruoyi.framework.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.http.HttpMethod;
  5. import org.springframework.security.authentication.AuthenticationManager;
  6. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  7. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
  8. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  9. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  10. import org.springframework.security.config.http.SessionCreationPolicy;
  11. import org.springframework.security.core.userdetails.UserDetailsService;
  12. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  13. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
  14. import org.springframework.security.web.authentication.logout.LogoutFilter;
  15. import org.springframework.web.filter.CorsFilter;
  16. import com.ruoyi.framework.security.filter.JwtAuthenticationTokenFilter;
  17. import com.ruoyi.framework.security.handle.AuthenticationEntryPointImpl;
  18. import com.ruoyi.framework.security.handle.LogoutSuccessHandlerImpl;
  19. /**
  20. * spring security配置
  21. *
  22. * @author ruoyi
  23. */
  24. @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
  25. public class SecurityConfig extends WebSecurityConfigurerAdapter
  26. {
  27. /**
  28. * 自定义用户认证逻辑
  29. */
  30. @Autowired
  31. private UserDetailsService userDetailsService;
  32. /**
  33. * 认证失败处理类
  34. */
  35. @Autowired
  36. private AuthenticationEntryPointImpl unauthorizedHandler;
  37. /**
  38. * 退出处理类
  39. */
  40. @Autowired
  41. private LogoutSuccessHandlerImpl logoutSuccessHandler;
  42. /**
  43. * token认证过滤器
  44. */
  45. @Autowired
  46. private JwtAuthenticationTokenFilter authenticationTokenFilter;
  47. /**
  48. * 跨域过滤器
  49. */
  50. @Autowired
  51. private CorsFilter corsFilter;
  52. /**
  53. * 解决 无法直接注入 AuthenticationManager
  54. *
  55. * @return
  56. * @throws Exception
  57. */
  58. @Bean
  59. @Override
  60. public AuthenticationManager authenticationManagerBean() throws Exception
  61. {
  62. return super.authenticationManagerBean();
  63. }
  64. /**
  65. * anyRequest | 匹配所有请求路径
  66. * access | SpringEl表达式结果为true时可以访问
  67. * anonymous | 匿名可以访问
  68. * denyAll | 用户不能访问
  69. * fullyAuthenticated | 用户完全认证可以访问(非remember-me下自动登录)
  70. * hasAnyAuthority | 如果有参数,参数表示权限,则其中任何一个权限可以访问
  71. * hasAnyRole | 如果有参数,参数表示角色,则其中任何一个角色可以访问
  72. * hasAuthority | 如果有参数,参数表示权限,则其权限可以访问
  73. * hasIpAddress | 如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问
  74. * hasRole | 如果有参数,参数表示角色,则其角色可以访问
  75. * permitAll | 用户可以任意访问
  76. * rememberMe | 允许通过remember-me登录的用户访问
  77. * authenticated | 用户登录后可访问
  78. */
  79. @Override
  80. protected void configure(HttpSecurity httpSecurity) throws Exception
  81. {
  82. httpSecurity
  83. // CSRF禁用,因为不使用session
  84. .csrf().disable()
  85. // 认证失败处理类
  86. .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
  87. // 基于token,所以不需要session
  88. .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
  89. // 过滤请求
  90. .authorizeRequests()
  91. // 对于登录login 注册register 验证码captchaImage 允许匿名访问
  92. .antMatchers("/login", "/register", "/captchaImage").anonymous()
  93. .antMatchers(
  94. HttpMethod.GET,
  95. "/",
  96. "/*.html",
  97. "/**/*.html",
  98. "/**/*.css",
  99. "/**/*.js",
  100. "/profile/**"
  101. ).permitAll()
  102. .antMatchers("/swagger-ui.html").anonymous()
  103. .antMatchers("/swagger-resources/**").anonymous()
  104. .antMatchers("/webjars/**").anonymous()
  105. .antMatchers("/*/api-docs").anonymous()
  106. .antMatchers("/druid/**").anonymous()
  107. // 除上面外的所有请求全部需要鉴权认证
  108. .anyRequest().authenticated()
  109. .and()
  110. .headers().frameOptions().disable();
  111. httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
  112. // 添加JWT filter
  113. httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
  114. // 添加CORS filter
  115. httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
  116. httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);
  117. }
  118. /**
  119. * 强散列哈希加密实现
  120. */
  121. @Bean
  122. public BCryptPasswordEncoder bCryptPasswordEncoder()
  123. {
  124. return new BCryptPasswordEncoder();
  125. }
  126. /**
  127. * 身份认证接口
  128. */
  129. @Override
  130. protected void configure(AuthenticationManagerBuilder auth) throws Exception
  131. {
  132. auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
  133. }
  134. }
  1. package com.ruoyi.framework.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.web.cors.CorsConfiguration;
  6. import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
  7. import org.springframework.web.filter.CorsFilter;
  8. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
  9. import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
  10. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  11. import com.ruoyi.common.constant.Constants;
  12. import com.ruoyi.framework.interceptor.RepeatSubmitInterceptor;
  13. /**
  14. * 通用配置
  15. *
  16. * @author ruoyi
  17. */
  18. @Configuration
  19. public class ResourcesConfig implements WebMvcConfigurer
  20. {
  21. @Autowired
  22. private RepeatSubmitInterceptor repeatSubmitInterceptor;
  23. @Override
  24. public void addResourceHandlers(ResourceHandlerRegistry registry)
  25. {
  26. /** 本地文件上传路径 */
  27. registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**")
  28. .addResourceLocations("file:" + RuoYiConfig.getProfile() + "/");
  29. /** swagger配置 */
  30. registry.addResourceHandler("/swagger-ui/**")
  31. .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
  32. }
  33. /**
  34. * 自定义拦截规则
  35. */
  36. @Override
  37. public void addInterceptors(InterceptorRegistry registry)
  38. {
  39. registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");
  40. }
  41. /**
  42. * 跨域配置
  43. */
  44. @Bean
  45. public CorsFilter corsFilter()
  46. {
  47. CorsConfiguration config = new CorsConfiguration();
  48. config.setAllowCredentials(true);
  49. // 设置访问源地址
  50. config.addAllowedOriginPattern("*");
  51. // 设置访问源请求头
  52. config.addAllowedHeader("*");
  53. // 设置访问源请求方法
  54. config.addAllowedMethod("*");
  55. // 有效期 1800秒 // 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
  56. config.setMaxAge(1800L);
  57. // 添加映射路径,拦截一切请求
  58. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  59. source.registerCorsConfiguration("/**", config);
  60. // 返回新的CorsFilter
  61. return new CorsFilter(source);
  62. }
  63. }

从登录来看

  1. /** SysLoginController
  2. * 登录方法
  3. *
  4. * @param loginBody 登录信息
  5. * @return 结果
  6. */
  7. @PostMapping("/login")
  8. public AjaxResult login(@RequestBody LoginBody loginBody)
  9. {
  10. AjaxResult ajax = AjaxResult.success();
  11. // 生成令牌
  12. String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
  13. loginBody.getUuid());
  14. ajax.put(Constants.TOKEN, token);
  15. return ajax;
  16. }
  17. /** SysLoginService
  18. * 登录验证
  19. *
  20. * @param username 用户名
  21. * @param password 密码
  22. * @param code 验证码
  23. * @param uuid 唯一标识
  24. * @return 结果
  25. */
  26. public String login(String username, String password, String code, String uuid)
  27. {
  28. boolean captchaOnOff = configService.selectCaptchaOnOff();
  29. // 验证码开关
  30. if (captchaOnOff)
  31. {
  32. validateCaptcha(username, code, uuid);
  33. }
  34. // 用户验证
  35. Authentication authentication = null;
  36. try
  37. {
  38. // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
  39. authentication = authenticationManager
  40. .authenticate(new UsernamePasswordAuthenticationToken(username, password));
  41. }
  42. catch (Exception e)
  43. {
  44. if (e instanceof BadCredentialsException)
  45. {
  46. AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
  47. throw new UserPasswordNotMatchException();
  48. }
  49. else
  50. {
  51. AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
  52. throw new ServiceException(e.getMessage());
  53. }
  54. }
  55. AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
  56. LoginUser loginUser = (LoginUser) authentication.getPrincipal();
  57. recordLoginInfo(loginUser.getUserId());
  58. // 生成token
  59. return tokenService.createToken(loginUser);
  60. }

黑马畅购小程序

json 树形结构与 树表互转

json转表

  1. @PostMapping("list/tree")
  2. public RShop list(@RequestBody List<CatVO> catvo) {
  3. setchildren(catvo);
  4. System.out.println("==============");
  5. return RShop.ok();
  6. }
  7. private List<CatVO> setchildren (List<CatVO> all){
  8. List<CatVO> collect = all.stream().map((catvo -> {
  9. Cat cat = new Cat();
  10. BeanUtils.copyProperties(catvo, cat);
  11. System.out.println(cat);
  12. boolean save = catService.save(cat);
  13. System.out.println("========");
  14. List<CatVO> children = catvo.getChildren();
  15. setchildren(children);
  16. return catvo;
  17. })).collect(Collectors.toList());
  18. return collect;
  19. }
  20. 其他版本的递归方式
  21. /* @PostMapping("list/tree")
  22. public RShop list(@RequestBody List<CatVO> catvo) {
  23. List<CatVO> collect = catvo.stream().map((m) -> {
  24. Cat cat = new Cat();
  25. BeanUtils.copyProperties(m,cat);
  26. boolean save = catService.save(cat);
  27. System.out.println(save);
  28. System.out.println("========");
  29. List<CatVO> children = m.getChildren();
  30. setchildren(children);
  31. return m;
  32. }).collect(Collectors.toList());
  33. //List<Cat> catlist = catService.listWithTree();
  34. return RShop.ok();
  35. }*/

从表中查询三级分类

  1. //CatController
  2. @ApiOperation("获取分类数据")
  3. @GetMapping("categories")
  4. public RShop getCategories(){
  5. List<Cat> entities = catService.listWithTree();
  6. return RShop.ok().message(entities);
  7. }
  8. //entity 添加了children
  9. @TableField(exist=false)
  10. private List<Cat> children;
  11. //CatServiceImpl
  12. package com.shop.wxshop.service.impl;
  13. import com.shop.wxshop.entity.Cat;
  14. import com.shop.wxshop.entity.CatVO;
  15. import com.shop.wxshop.mapper.CatMapper;
  16. import com.shop.wxshop.service.CatService;
  17. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  18. import org.springframework.stereotype.Service;
  19. import java.util.List;
  20. import java.util.stream.Collectors;
  21. /**
  22. * <p>
  23. * 服务实现类
  24. * </p>
  25. *
  26. * @author xiaoyuan
  27. * @since 2022-03-16
  28. */
  29. @Service
  30. public class CatServiceImpl extends ServiceImpl<CatMapper, Cat> implements CatService {
  31. @Override
  32. public List<Cat> listWithTree() {
  33. // 1.查出所有分类
  34. List<Cat> cats = baseMapper.selectList(null);
  35. // 2.组装父子的树形结构
  36. // 2.1 找到所有的一级分类
  37. List<Cat> level1Menus = cats.stream().filter(c ->
  38. c.getCat_pid() == 0
  39. ).map((menu)->{
  40. menu.setChildren(getChildren(menu,cats));
  41. return menu;
  42. }).collect(Collectors.toList());
  43. return level1Menus;
  44. }
  45. //递归查找所有菜单的子菜单
  46. private List<Cat> getChildren(Cat root,List<Cat> all){
  47. List<Cat> children = all.stream().filter(c -> {
  48. return c.getCat_pid().equals(root.getCat_id());
  49. }).map(c -> {
  50. // 1.找到子菜单
  51. c.setChildren(getChildren(c,all));
  52. return c;
  53. }).collect(Collectors.toList());
  54. return children;
  55. }
  56. }

mybatisplus 查询指定列

  1. // 分页方式
  2. @Test
  3. public void test4() {
  4. Page<Map<String,Object>> page = new Page<>(1, 20);
  5. QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
  6. goodsQueryWrapper.like("goods_name","手机").select("goods_id","goods_name");
  7. Page<Map<String, Object>> pageParam = goodsService.pageMaps(page, goodsQueryWrapper);
  8. List<Map<String, Object>> records = pageParam.getRecords();
  9. records.forEach(System.out::println);
  10. }
  11. //stream流方式
  12. @GetMapping("goods/qsearch")
  13. public RShop getByGoodsName(@RequestParam(name = "query",required = true) String query){
  14. QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
  15. goodsQueryWrapper.like("goods_name","手机").select("goods_id","goods_name");
  16. List<Goods> list = goodsService.list(goodsQueryWrapper);
  17. List<GoodsVO> goodsVOlist = list.stream().map(item -> {
  18. GoodsVO goodsVO = new GoodsVO();
  19. BeanUtils.copyProperties(item,goodsVO);
  20. return goodsVO;
  21. }).collect(Collectors.toList());
  22. goodsVOlist.forEach(System.out::println);
  23. return RShop.ok().message(goodsVOlist);
  24. }