Merge branch 'dev'

This commit is contained in:
zlt2000
2023-12-17 20:57:35 +08:00
416 changed files with 5265 additions and 7586 deletions
+23 -20
View File
@@ -1,18 +1,14 @@
# zlt-microservices-platform
<p align="center">
<img src="https://img.shields.io/badge/Version-5.5.0-critical" alt="Downloads"/>
<img src="https://img.shields.io/badge/Spring%20Boot-2.5.14-blue" alt="Downloads"/>
<img src="https://img.shields.io/badge/Spring%20Cloud-2020.0.6-blue" alt="Downloads"/>
<img src="https://img.shields.io/badge/Spring%20Cloud%20Alibaba-2021.1-blue" alt="Downloads"/>
<img src="https://img.shields.io/badge/Elasticsearch-7.x-brightgreen" alt="Downloads"/>
<img src="https://img.shields.io/badge/Version-6.0.0-critical" alt="Downloads"/>
<img src="https://img.shields.io/badge/JDK-17-8A2BE2" alt="Downloads"/>
<img src="https://img.shields.io/badge/Spring Authorization Server-1.1.3-40A24E" alt="Downloads"/>
<img src="https://img.shields.io/badge/Spring%20Boot-3.1.6-blue" alt="Downloads"/>
<img src="https://img.shields.io/badge/Spring%20Cloud-2022.0.4-blue" alt="Downloads"/>
<img src="https://img.shields.io/badge/Spring%20Cloud%20Alibaba-2022.0.0.0-blue" alt="Downloads"/>
<img src="https://img.shields.io/badge/Elasticsearch-7.x-34A2AE" alt="Downloads"/>
<img src="https://img.shields.io/badge/Ant%20Design-pro-9cf" alt="Downloads"/>
<a target="_blank" href='https://gitee.com/zlt2000/microservices-platform'>
<img src='https://gitee.com/zlt2000/microservices-platform/badge/star.svg' alt='star'/>
</a>
<a target="_blank" href='https://github.com/zlt2000/microservices-platform'>
<img src="https://img.shields.io/github/stars/zlt2000/microservices-platform.svg?style=social" alt="github star"/>
</a>
</p>
@@ -46,15 +42,13 @@
* **[文档更新日志](https://www.kancloud.cn/zlt2000/microservices-platform/936236)**
* **演示环境地址**: [http://zlt2000.cn](http://zlt2000.cn/)
* 账号密码:admin/admin
* APM监控账号密码:admin/admin
* Grafana账号:zlt/zlt123
* 任务管理账号密码:admin/123456
* **演示环境有全方位的监控示例:日志系统 + APM系统 + GPE系统**
* Gitee地址:https://gitee.com/zlt2000/microservices-platform
* Github地址:https://github.com/zlt2000/microservices-platform
* 前后端分离的企业级微服务架构
* 主要针对解决微服务和业务开发时常见的**非功能性需求**
* 深度定制`Spring Security`真正实现了基于`RBAC`、`jwt`和`oauth2`的无状态统一权限认证的解决方案
* 基于 `Spring Authorization Server` 深度定制`Spring Security`真正实现了基于`RBAC`、`jwt`和`oauth2`的无状态统一权限认证的解决方案
* 提供应用管理,方便第三方系统接入,**支持多租户(应用隔离)**
* 引入组件化的思想实现高内聚低耦合并且高度可配置化
* 注重代码规范,严格控制包依赖,每个工程基本都是最小依赖
@@ -62,7 +56,15 @@
>重构于开源项目OCP&cp:https://gitee.com/owenwangwen/open-capacity-platform
&nbsp;
## 4. 模块说明
## 4. 分支说明
| 分支名 | JDK | Spring Boot | Spring Cloud | Spring Security |
| --- | --- | --- | --- |---|
| master | 17 | 3.x | 2022.x | Spring Authorization Server |
| 5.x | 1.8 | 2.5.x | 2020.x | Spring Security OAuth |
| 4.x | 1.8 | 2.3.x | 2.2.x | Spring Security OAuth |
&nbsp;
## 5. 模块说明
```lua
central-platform -- 父项目,公共依赖
│ ├─zlt-business -- 业务模块一级工程
@@ -81,7 +83,6 @@ central-platform -- 父项目,公共依赖
│ │ ├─zlt-redis-spring-boot-starter -- 封装Redis通用操作逻辑
│ │ ├─zlt-loadbalancer-spring-boot-starter -- 封装Loadbalancer和Feign的通用操作逻辑
│ │ ├─zlt-sentinel-spring-boot-starter -- 封装Sentinel的通用操作逻辑
│ │ ├─zlt-swagger2-spring-boot-starter -- 封装Swagger通用操作逻辑
│ │ ├─zlt-elasticsearch-spring-boot-starter -- 封装Elasticsearch通用操作逻辑
│ │ ├─zlt-oss-spring-boot-starter -- 封装对象存储通用操作逻辑
│ │ ├─zlt-zookeeper-spring-boot-starter -- 封装Zookeeper通用操作逻辑
@@ -98,11 +99,13 @@ central-platform -- 父项目,公共依赖
│ │ ├─layui-web -- layui前端[8066]
│ │ ├─react-web -- react前端[8066]
│ ├─zlt-demo -- demo一级工程
│ │ ├─txlcn-demo -- txlcn分布式事务demo
│ │ ├─dubbo-demo -- dubbo服务demo
│ │ ├─resource-server-demo -- 资源服务器demo
│ │ ├─seata-demo -- seata分布式事务demo
│ │ ├─sharding-jdbc-demo -- sharding-jdbc分库分表demo
│ │ ├─rocketmq-demo -- rocketmq和mq事务demo
│ │ ├─sso-demo -- 单点登录demo
│ │ ├─websocket-demo -- websocket demo
```
<table>
@@ -113,20 +116,20 @@ central-platform -- 父项目,公共依赖
</table>
## 5. 交流反馈
## 6. 交流反馈
* 有问题先看看 [F&Q](https://www.kancloud.cn/zlt2000/microservices-platform/981382) 中有没有相关的回答
* 欢迎提交`ISSUS`,请写清楚问题的具体原因,重现步骤和环境(上下文)
* 项目/微服务交流请进群:
* 一群:[250883130(已满)](https://shang.qq.com/wpa/qunwpa?idkey=17544199255998bda0d938fb72b08d076c40c52c9904520b76eb5eb0585da71e)
* 二群:[1041797659(已满)](https://shang.qq.com/wpa/qunwpa?idkey=41988facbc02f678942a7ee7ae03122f2ef0a10c948b3d07319f070bfb0d3a98)
* 三群:[512637767](https://qm.qq.com/cgi-bin/qm/qr?k=HntAHTirZwCEjF8PQpjDYkw37Zx5rJg8&jump_from=webapi)
* 个人博客:[https://zlt2000.gitee.io](https://zlt2000.gitee.io)
* 个人博客:[http://zlt2000.gitee.io](http://zlt2000.gitee.io)
* 个人邮箱:zltdiablo@163.com
* 个人公众号:[陶陶技术笔记](http://qiniu.zlt2000.cn/blog/20190902/M56cWjw7uNsc.png?imageslim)
* GitChat:[https://gitbook.cn/gitchat/author/5b2362320398d50d7b7ab29e](https://gitbook.cn/gitchat/author/5b2362320398d50d7b7ab29e)
&nbsp;
## 6. 截图(点击可大图预览)
## 7. 截图(点击可大图预览)
<table>
<tr>
<td><img alt="首页" src="https://gitee.com/zlt2000/images/raw/master/%E9%A6%96%E9%A1%B5.png"/></td>
+71 -100
View File
@@ -5,64 +5,61 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.zlt</groupId>
<artifactId>central-platform</artifactId>
<version>5.6.0</version>
<version>6.0.0</version>
<packaging>pom</packaging>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>8</java.version>
<spring-cloud-alibaba-dependencies.version>2021.1</spring-cloud-alibaba-dependencies.version>
<spring-boot-dependencies.version>2.5.14</spring-boot-dependencies.version>
<spring-cloud-dependencies.version>2020.0.6</spring-cloud-dependencies.version>
<java.version>17</java.version>
<spring-cloud-alibaba-dependencies.version>2022.0.0.0</spring-cloud-alibaba-dependencies.version>
<spring-boot-dependencies.version>3.1.6</spring-boot-dependencies.version>
<spring-cloud-dependencies.version>2022.0.4</spring-cloud-dependencies.version>
<commons-collections4.version>4.4</commons-collections4.version>
<swagger.butler.version>2.0.1</swagger.butler.version>
<jjwt.version>0.9.1</jjwt.version>
<druid-starter>1.2.6</druid-starter>
<druid-starter>1.2.18</druid-starter>
<jasypt.version>1.14</jasypt.version>
<sharding-sphere.version>3.1.0</sharding-sphere.version>
<security-oauth2.version>2.3.8.RELEASE</security-oauth2.version>
<security-jwt.version>1.1.0.RELEASE</security-jwt.version>
<redisson-starter.version>3.16.1</redisson-starter.version>
<easyCaptcha.version>1.6.2</easyCaptcha.version>
<hutool.version>5.7.20</hutool.version>
<mybatis-plus-boot-starter.version>3.5.1</mybatis-plus-boot-starter.version>
<redisson-starter.version>3.25.0</redisson-starter.version>
<mybatis-plus-boot-starter.version>3.5.4.1</mybatis-plus-boot-starter.version>
<aliyun-sdk-oss>3.8.1</aliyun-sdk-oss>
<qiniu-java-sdk>7.2.28</qiniu-java-sdk>
<easypoi.version>4.1.3</easypoi.version>
<poi.version>4.1.1</poi.version>
<spring-boot-admin.version>2.5.6</spring-boot-admin.version>
<spring-boot-admin.version>3.1.8</spring-boot-admin.version>
<velocity.version>1.7</velocity.version>
<commons-configuration2.version>2.7</commons-configuration2.version>
<txlcn.version>5.0.2.RELEASE</txlcn.version>
<fastdfs-client.version>1.27.2</fastdfs-client.version>
<userAgent.version>1.21</userAgent.version>
<transmittable.version>2.12.1</transmittable.version>
<transmittable.version>2.14.4</transmittable.version>
<banner.version>1.0.2</banner.version>
<commons-beanutils.version>1.9.4</commons-beanutils.version>
<spring-social-security.version>1.1.6.RELEASE</spring-social-security.version>
<commons-io.version>2.7</commons-io.version>
<servlet-api.version>4.0.1</servlet-api.version>
<spring-data-elasticsearch.version>4.2.3</spring-data-elasticsearch.version>
<elasticsearch.version>7.13.4</elasticsearch.version>
<knife4j.version>2.0.5</knife4j.version>
<hibernate-validator.version>6.2.0.Final</hibernate-validator.version>
<knife4j.version>4.3.0</knife4j.version>
<hibernate-validator.version>8.0.1.Final</hibernate-validator.version>
<dubbo.version>2.7.8</dubbo.version>
<curator.version>5.1.0</curator.version>
<jackson-databind.version>2.13.4</jackson-databind.version>
<commons-configuration.version>1.10</commons-configuration.version>
<zuul.version>2.2.9.RELEASE</zuul.version>
<aws-java-sdk-s3.version>1.12.40</aws-java-sdk-s3.version>
<spring-cloud-starter-oauth2.version>2.2.5.RELEASE</spring-cloud-starter-oauth2.version>
<docker-maven-plugin.version>1.2.2</docker-maven-plugin.version>
<sonar.exclusions>zlt-job/**/*, zlt-register/**/*, zlt-web/**/*</sonar.exclusions>
<docker.baseImage>openjdk:8-jre-alpine</docker.baseImage>
<docker.volumes>/tmp</docker.volumes>
<docker.image.prefix>hub.zlt.com:8080/microservices-platform</docker.image.prefix>
<docker.java.security.egd>-Djava.security.egd=file:/dev/./urandom</docker.java.security.egd>
<docker.java.opts>-Xms128m -Xmx128m</docker.java.opts>
<guava.version>20.0</guava.version>
<maven-compiler-plugin.version>3.11.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>3.1.2</maven-surefire-plugin.version>
<mysql-connector-java.version>8.0.33</mysql-connector-java.version>
<javax.annotation-api.version>1.3.2</javax.annotation-api.version>
<tomcat-embed-core.version>10.1.11</tomcat-embed-core.version>
<httpclient.version>5.2.1</httpclient.version>
<oauth2-oidc-sdk.version>11.7</oauth2-oidc-sdk.version>
</properties>
<dependencies>
@@ -95,6 +92,16 @@
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>${javax.annotation-api.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>${tomcat-embed-core.version}</version>
</dependency>
</dependencies>
<dependencyManagement>
@@ -120,11 +127,6 @@
<artifactId>zlt-redis-spring-boot-starter</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-swagger2-spring-boot-starter</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-loadbalancer-spring-boot-starter</artifactId>
@@ -182,12 +184,6 @@
<artifactId>mybatis-plus</artifactId>
<version>${mybatis-plus-boot-starter.version}</version>
</dependency>
<!-- 加入spring security spring security oauth2的处理 -->
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>${security-oauth2.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
@@ -199,24 +195,7 @@
<artifactId>redisson-spring-boot-starter</artifactId>
<version>${redisson-starter.version}</version>
</dependency>
<!-- swagger -->
<dependency>
<groupId>com.github.zlt2000</groupId>
<artifactId>swagger-butler-core</artifactId>
<version>${swagger.butler.version}</version>
</dependency>
<!-- 验证码生成工具 -->
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>${easyCaptcha.version}</version>
</dependency>
<!-- hutool java工具类库 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
@@ -259,21 +238,6 @@
<artifactId>commons-configuration2</artifactId>
<version>${commons-configuration2.version}</version>
</dependency>
<dependency>
<groupId>com.codingapi.txlcn</groupId>
<artifactId>txlcn-tm</artifactId>
<version>${txlcn.version}</version>
</dependency>
<dependency>
<groupId>com.codingapi.txlcn</groupId>
<artifactId>txlcn-tc</artifactId>
<version>${txlcn.version}</version>
</dependency>
<dependency>
<groupId>com.codingapi.txlcn</groupId>
<artifactId>txlcn-txmsg-netty</artifactId>
<version>${txlcn.version}</version>
</dependency>
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
@@ -304,21 +268,11 @@
<artifactId>banner</artifactId>
<version>${banner.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-security</artifactId>
<version>${spring-social-security.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet-api.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
@@ -344,16 +298,6 @@
<artifactId>elasticsearch</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>${knife4j.version}</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-micro-spring-boot-starter</artifactId>
<version>${knife4j.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
@@ -384,11 +328,6 @@
<artifactId>curator-framework</artifactId>
<version>${curator.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-databind.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
@@ -399,16 +338,16 @@
<artifactId>aws-java-sdk-s3</artifactId>
<version>${aws-java-sdk-s3.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
<version>${zuul.version}</version>
</dependency>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>${commons-configuration.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@@ -437,9 +376,21 @@
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson-databind.version}</version>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-dependencies</artifactId>
<version>${knife4j.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>oauth2-oidc-sdk</artifactId>
<version>${oauth2-oidc-sdk.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
@@ -452,6 +403,26 @@
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot-dependencies.version}</version>
</plugin>
<!-- 指定jdk版本,和指定编码 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- maven 打包时跳过测试 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
+3 -3
View File
@@ -4,7 +4,7 @@
<parent>
<groupId>com.zlt</groupId>
<artifactId>zlt-business</artifactId>
<version>5.6.0</version>
<version>6.0.0</version>
</parent>
<artifactId>code-generator</artifactId>
@@ -26,8 +26,8 @@
<artifactId>zlt-db-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-swagger2-spring-boot-starter</artifactId>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
@@ -3,7 +3,8 @@ package com.central.generator.controller;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import com.central.common.model.PageResult;
import com.central.generator.service.SysGeneratorService;
@@ -11,13 +12,11 @@ import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
/**
* @Author: zlt
*/
@RestController
@Api(tags = "代码生成器")
@Tag(name = "代码生成器")
@RequestMapping("/generator")
public class SysGeneratorController {
@Autowired
@@ -8,4 +8,15 @@ spring:
mybatis-plus:
mapper-locations: classpath:/mapper/*Mapper.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.central.generator.model
typeAliasesPackage: com.central.generator.model
springdoc:
group-configs:
- group: 'code'
paths-to-match: '/**'
packages-to-scan: com.central.generator.controller
knife4j:
enable: true
setting:
swagger-model-name: 代码生成器接口文档
@@ -2,12 +2,13 @@ package ${package}.${moduleName}.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import lombok.extern.slf4j.Slf4j;
import ${package}.${moduleName}.model.${className};
@@ -24,18 +25,18 @@ import com.central.common.model.Result;
@Slf4j
@RestController
@RequestMapping("/${pathName}")
@Api(tags = "${comments}")
@Tag(name = "${comments}")
@RequiredArgsConstructor
public class ${className}Controller {
@Autowired
private I${className}Service ${classname}Service;
private final I${className}Service ${classname}Service;
/**
* 列表
*/
@ApiOperation(value = "查询列表")
@ApiImplicitParams({
@ApiImplicitParam(name = "page", value = "分页起始位置", required = true, dataType = "Integer"),
@ApiImplicitParam(name = "limit", value = "分页结束位置", required = true, dataType = "Integer")
@Operation(summary = "查询列表")
@Parameters({
@Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY),
@Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY)
})
@GetMapping
public PageResult list(@RequestParam Map<String, Object> params) {
@@ -45,7 +46,7 @@ public class ${className}Controller {
/**
* 查询
*/
@ApiOperation(value = "查询")
@Operation(summary = "查询")
@GetMapping("/{${pk.attrname}}")
public Result findUserById(@PathVariable Long ${pk.attrname}) {
${className} model = ${classname}Service.getById(${pk.attrname});
@@ -55,7 +56,7 @@ public class ${className}Controller {
/**
* 新增or更新
*/
@ApiOperation(value = "保存")
@Operation(summary = "保存")
@PostMapping
public Result save(@RequestBody ${className} ${classname}) {
${classname}Service.saveOrUpdate(${classname});
@@ -65,7 +66,8 @@ public class ${className}Controller {
/**
* 删除
*/
@ApiOperation(value = "删除")
@Operation(summary = "删除")
@Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true)
@DeleteMapping("/{id}")
public Result delete(@PathVariable Long ${pk.attrname}) {
${classname}Service.removeById(${pk.attrname});
+3 -3
View File
@@ -4,7 +4,7 @@
<parent>
<groupId>com.zlt</groupId>
<artifactId>zlt-business</artifactId>
<version>5.6.0</version>
<version>6.0.0</version>
</parent>
<artifactId>file-center</artifactId>
<description>文件中心</description>
@@ -55,8 +55,8 @@
<!-- swagger -->
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-swagger2-spring-boot-starter</artifactId>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
</dependency>
<dependency>
@@ -1,12 +0,0 @@
package com.central.file.config;
import com.central.common.config.DefaultWebMvcConfig;
import org.springframework.context.annotation.Configuration;
/**
* @author zlt
* @date 2019/8/5
*/
@Configuration
public class WebMvcConfig extends DefaultWebMvcConfig {
}
@@ -14,7 +14,7 @@ import java.io.OutputStream;
* @author zlt
* @date 2021/2/13
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Service
@@ -19,7 +19,7 @@ import java.io.OutputStream;
* @author zlt
* @date 2021/2/13
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Service
@@ -13,6 +13,17 @@ mybatis-plus:
db-config:
id-type: INPUT
springdoc:
group-configs:
- group: 'default'
paths-to-match: '/**'
packages-to-scan: com.central.file.controller
knife4j:
enable: true
setting:
swagger-model-name: 文件中心接口文档
zlt:
file-server:
type: s3
@@ -23,12 +34,6 @@ zlt:
accessKeySecret: ${zlt.s3.accessKeySecret}
endpoint: ${zlt.s3.endpoint}
bucketName: ${zlt.s3.bucketName}
swagger:
enabled: true
title: 文件中心
description: 文件中心接口文档
version: 1.0
base-package: com.central.file.controller
#多租户配置
tenant:
enable: true
+1 -1
View File
@@ -4,7 +4,7 @@
<parent>
<groupId>com.zlt</groupId>
<artifactId>central-platform</artifactId>
<version>5.6.0</version>
<version>6.0.0</version>
</parent>
<artifactId>zlt-business</artifactId>
<description>业务中心</description>
+1 -1
View File
@@ -4,7 +4,7 @@
<parent>
<groupId>com.zlt</groupId>
<artifactId>zlt-business</artifactId>
<version>5.6.0</version>
<version>6.0.0</version>
</parent>
<artifactId>search-center</artifactId>
<description>搜索中心</description>
@@ -4,7 +4,7 @@
<parent>
<groupId>com.zlt</groupId>
<artifactId>search-center</artifactId>
<version>5.6.0</version>
<version>6.0.0</version>
</parent>
<artifactId>search-client</artifactId>
<description>搜索中心客户端</description>
@@ -11,7 +11,7 @@ import java.util.Map;
/**
* @author zlt
*/
@FeignClient(name = ServiceNameConstants.SEARCH_SERVICE, fallbackFactory = SearchServiceFallbackFactory.class, decode404 = true)
@FeignClient(name = ServiceNameConstants.SEARCH_SERVICE, fallbackFactory = SearchServiceFallbackFactory.class, dismiss404 = true)
public interface AggregationService {
/**
* 查询文档列表
@@ -11,7 +11,7 @@ import org.springframework.web.bind.annotation.*;
/**
* @author zlt
*/
@FeignClient(name = ServiceNameConstants.SEARCH_SERVICE, fallbackFactory = SearchServiceFallbackFactory.class, decode404 = true)
@FeignClient(name = ServiceNameConstants.SEARCH_SERVICE, fallbackFactory = SearchServiceFallbackFactory.class, dismiss404 = true)
public interface SearchService {
/**
* 查询文档列表
@@ -5,6 +5,7 @@ import com.central.search.client.feign.SearchService;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.cloud.openfeign.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* searchService降级工场
@@ -12,6 +13,7 @@ import lombok.extern.slf4j.Slf4j;
* @author zlt
*/
@Slf4j
@Component
public class SearchServiceFallbackFactory implements FallbackFactory<SearchService> {
@Override
public SearchService create(Throwable throwable) {
@@ -4,7 +4,7 @@
<parent>
<groupId>com.zlt</groupId>
<artifactId>search-center</artifactId>
<version>5.6.0</version>
<version>6.0.0</version>
</parent>
<artifactId>search-server</artifactId>
<description>搜索中心服务端</description>
@@ -51,10 +51,9 @@
<!-- swagger -->
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-swagger2-spring-boot-starter</artifactId>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
@@ -5,7 +5,7 @@ import com.central.admin.properties.IndexProperties;
import com.central.admin.service.IIndexService;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@@ -20,7 +20,7 @@ import java.util.*;
*/
@Slf4j
@RestController
@Api(tags = "索引管理api")
@Tag(name = "索引管理api")
@RequestMapping("/admin")
public class IndexController {
@Autowired
@@ -33,7 +33,7 @@ import java.util.*;
* @author zlt
* @date 2019/4/23
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Service
@@ -1,11 +0,0 @@
package com.central.common.config;
import org.springframework.context.annotation.Configuration;
/**
* @author zlt
* @date 2019/8/5
*/
@Configuration
public class WebMvcConfig extends DefaultWebMvcConfig {
}
@@ -1,7 +1,7 @@
package com.central.search.controller;
import com.central.search.service.IAggregationService;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
@@ -16,7 +16,7 @@ import java.util.Map;
*/
@Slf4j
@RestController
@Api(tags = "搜索模块api")
@Tag(name = "搜索模块api")
@RequestMapping("/agg")
public class AggregationController {
private final IAggregationService aggregationService;
@@ -5,9 +5,9 @@ import com.central.common.model.*;
import com.central.search.model.SearchDto;
import com.central.search.service.ISearchService;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
@@ -19,7 +19,7 @@ import java.io.IOException;
*/
@Slf4j
@RestController
@Api(tags = "搜索模块api")
@Tag(name = "搜索模块api")
@RequestMapping("/search")
public class SearchController {
private final ISearchService searchService;
@@ -35,7 +35,7 @@ import java.util.Map;
* @author zlt
* @date 2019/5/7
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Service
@@ -1,16 +1,20 @@
spring:
elasticsearch:
rest:
uris: ${zlt.elasticsearch.uris}
username: ${zlt.elasticsearch.username}
password: ${zlt.elasticsearch.password}
uris: ${zlt.elasticsearch.uris}
username: ${zlt.elasticsearch.username}
password: ${zlt.elasticsearch.password}
springdoc:
group-configs:
- group: 'search'
paths-to-match: '/**'
packages-to-scan: com.central.search.controller
knife4j:
enable: true
setting:
swagger-model-name: 搜索中心接口文档
zlt:
indices:
show: sys-log-*,mysql-slowlog-*,sys_user,point-log-*,audit-log-*
swagger:
enabled: true
title: 搜索中心
description: 搜索中心接口文档
version: 1.0
base-package: com.central.search.controller
show: sys-log-*,mysql-slowlog-*,sys_user,point-log-*,audit-log-*
+3 -3
View File
@@ -4,7 +4,7 @@
<parent>
<groupId>com.zlt</groupId>
<artifactId>zlt-business</artifactId>
<version>5.6.0</version>
<version>6.0.0</version>
</parent>
<artifactId>user-center</artifactId>
<description>用户中心</description>
@@ -40,8 +40,8 @@
</dependency>
<!-- swagger -->
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-swagger2-spring-boot-starter</artifactId>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
@@ -1,12 +0,0 @@
package com.central.user.config;
import com.central.common.config.DefaultWebMvcConfig;
import org.springframework.context.annotation.Configuration;
/**
* @author zlt
* @date 2019/8/5
*/
@Configuration
public class WebMvcConfig extends DefaultWebMvcConfig {
}
@@ -3,13 +3,13 @@ package com.central.user.controller;
import java.util.*;
import java.util.stream.Collectors;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.central.common.annotation.LoginUser;
import com.central.common.constant.CommonConstant;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.model.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
@@ -18,14 +18,11 @@ import org.springframework.web.bind.annotation.*;
import com.central.user.service.ISysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
* @author 作者 owen E-mail: 624191343@qq.com
*/
@RestController
@Api(tags = "菜单模块api")
@Tag(name = "菜单模块api")
@Slf4j
@RequestMapping("/menus")
public class SysMenuController {
@@ -61,7 +58,7 @@ public class SysMenuController {
*
* @param id
*/
@ApiOperation(value = "删除菜单")
@Operation(summary = "删除菜单")
@DeleteMapping("/{id}")
public Result delete(@PathVariable Long id) {
try {
@@ -73,7 +70,7 @@ public class SysMenuController {
}
}
@ApiOperation(value = "根据roleId获取对应的菜单")
@Operation(summary = "根据roleId获取对应的菜单")
@GetMapping("/{roleId}/menus")
public List<Map<String, Object>> findMenusByRoleId(@PathVariable Long roleId) {
Set<Long> roleIds = new HashSet<>();
@@ -101,7 +98,7 @@ public class SysMenuController {
return authTrees;
}
@ApiOperation(value = "根据roleCodes获取对应的权限")
@Operation(summary = "根据roleCodes获取对应的权限")
@SuppressWarnings("unchecked")
@Cacheable(value = "menu", key ="#roleCodes")
@GetMapping("/{roleCodes}")
@@ -117,21 +114,21 @@ public class SysMenuController {
/**
* 给角色分配菜单
*/
@ApiOperation(value = "角色分配菜单")
@Operation(summary = "角色分配菜单")
@PostMapping("/granted")
public Result setMenuToRole(@RequestBody SysMenu sysMenu) {
menuService.setMenuToRole(sysMenu.getRoleId(), sysMenu.getMenuIds());
return Result.succeed("操作成功");
}
@ApiOperation(value = "查询所有菜单")
@Operation(summary = "查询所有菜单")
@GetMapping("/findAlls")
public PageResult<SysMenu> findAlls() {
List<SysMenu> list = menuService.findAll();
return PageResult.<SysMenu>builder().data(list).code(0).count((long) list.size()).build();
}
@ApiOperation(value = "获取菜单以及顶级菜单")
@Operation(summary = "获取菜单以及顶级菜单")
@GetMapping("/findOnes")
public PageResult<SysMenu> findOnes() {
List<SysMenu> list = menuService.findOnes();
@@ -144,7 +141,7 @@ public class SysMenuController {
* @param menu
* @return
*/
@ApiOperation(value = "新增菜单")
@Operation(summary = "新增菜单")
@PostMapping("saveOrUpdate")
public Result saveOrUpdate(@RequestBody SysMenu menu) {
try {
@@ -165,13 +162,10 @@ public class SysMenuController {
* @return
*/
@GetMapping("/current")
@ApiOperation(value = "查询当前用户菜单")
public List<SysMenu> findMyMenu(@LoginUser SysUser user) {
List<SysRole> roles = user.getRoles();
if (CollectionUtil.isEmpty(roles)) {
return Collections.emptyList();
}
List<SysMenu> menus = menuService.findByRoleCodes(roles.stream().map(SysRole::getCode).collect(Collectors.toSet()), CommonConstant.MENU);
@Operation(summary = "查询当前用户菜单")
public List<SysMenu> findMyMenu() {
LoginAppUser user = LoginUserContextHolder.getUser();
List<SysMenu> menus = menuService.findByUserId(user.getId(), CommonConstant.MENU);
return treeBuilder(menus);
}
}
@@ -3,6 +3,8 @@ package com.central.user.controller;
import java.util.List;
import java.util.Map;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
@@ -18,16 +20,13 @@ import com.central.common.model.Result;
import com.central.common.model.SysRole;
import com.central.user.service.ISysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
* @author 作者 owen E-mail: 624191343@qq.com
* 角色管理
*/
@Slf4j
@RestController
@Api(tags = "角色模块api")
@Tag(name = "角色模块api")
public class SysRoleController {
@Autowired
private ISysRoleService sysRoleService;
@@ -37,7 +36,7 @@ public class SysRoleController {
* @param params
* @return
*/
@ApiOperation(value = "后台管理查询角色")
@Operation(summary = "后台管理查询角色")
@GetMapping("/roles")
public PageResult<SysRole> findRoles(@RequestParam Map<String, Object> params) {
return sysRoleService.findRoles(params);
@@ -47,7 +46,7 @@ public class SysRoleController {
* 用户管理查询所有角色
* @return
*/
@ApiOperation(value = "后台管理查询角色")
@Operation(summary = "后台管理查询角色")
@GetMapping("/allRoles")
public Result<List<SysRole>> findAll() {
List<SysRole> result = sysRoleService.findAll();
@@ -71,7 +70,7 @@ public class SysRoleController {
*
* @param id
*/
@ApiOperation(value = "后台管理删除角色")
@Operation(summary = "后台管理删除角色")
@DeleteMapping("/roles/{id}")
public Result deleteRole(@PathVariable Long id) {
try {
@@ -8,16 +8,21 @@ import java.util.Set;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.central.common.annotation.LoginUser;
import com.central.common.constant.CommonConstant;
import com.central.common.model.*;
import com.central.common.utils.ExcelUtil;
import com.central.common.utils.LoginUserUtils;
import com.central.log.annotation.AuditLog;
import com.central.search.client.service.IQueryService;
import com.central.search.model.LogicDelDto;
import com.central.search.model.SearchDto;
import com.central.user.model.SysUserExcel;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
@@ -27,14 +32,10 @@ import org.springframework.web.bind.annotation.*;
import com.central.user.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author 作者 owen E-mail: 624191343@qq.com
@@ -42,7 +43,7 @@ import javax.servlet.http.HttpServletResponse;
*/
@Slf4j
@RestController
@Api(tags = "用户模块api")
@Tag(name = "用户模块api")
public class SysUserController {
private static final String ADMIN_CHANGE_MSG = "超级管理员不给予修改";
@@ -62,17 +63,17 @@ public class SysUserController {
*
* @return
*/
@ApiOperation(value = "根据access_token当前登录用户")
@Operation(summary = "根据access_token当前登录用户")
@GetMapping("/users/current")
public Result<LoginAppUser> getLoginAppUser(@LoginUser(isFull = true) SysUser user) {
return Result.succeed(appUserService.getLoginAppUser(user));
public Result<SysUser> getLoginAppUser() {
return Result.succeed(LoginUserUtils.getCurrentSysUser());
}
/**
* 查询用户实体对象SysUser
*/
@GetMapping(value = "/users/name/{username}")
@ApiOperation(value = "根据用户名查询用户实体")
@Operation(summary = "根据用户名查询用户实体")
@Cacheable(value = "user", key = "#username")
public SysUser selectByUsername(@PathVariable String username) {
return appUserService.selectByUsername(username);
@@ -82,8 +83,8 @@ public class SysUserController {
* 查询用户登录对象LoginAppUser
*/
@GetMapping(value = "/users-anon/login", params = "username")
@ApiOperation(value = "根据用户名查询用户")
public LoginAppUser findByUsername(String username) {
@Operation(summary = "根据用户名查询用户")
public SysUser findByUsername(String username) {
return appUserService.findByUsername(username);
}
@@ -93,7 +94,7 @@ public class SysUserController {
* @param mobile 手机号
*/
@GetMapping(value = "/users-anon/mobile", params = "mobile")
@ApiOperation(value = "根据手机号查询用户")
@Operation(summary = "根据手机号查询用户")
public SysUser findByMobile(String mobile) {
return appUserService.findByMobile(mobile);
}
@@ -104,7 +105,7 @@ public class SysUserController {
* @param openId openId
*/
@GetMapping(value = "/users-anon/openId", params = "openId")
@ApiOperation(value = "根据OpenId查询用户")
@Operation(summary = "根据OpenId查询用户")
public SysUser findByOpenId(String openId) {
return appUserService.findByOpenId(openId);
}
@@ -154,10 +155,10 @@ public class SysUserController {
* @param params
* @return
*/
@ApiOperation(value = "用户查询列表")
@ApiImplicitParams({
@ApiImplicitParam(name = "page", value = "分页起始位置", required = true, dataType = "Integer"),
@ApiImplicitParam(name = "limit", value = "分页结束位置", required = true, dataType = "Integer")
@Operation(summary = "用户查询列表")
@Parameters({
@Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY),
@Parameter(name = "limit",description = "分页结束位置",required = true,in= ParameterIn.QUERY)
})
@GetMapping("/users")
public PageResult<SysUser> findUsers(@RequestParam Map<String, Object> params) {
@@ -170,11 +171,11 @@ public class SysUserController {
* @param params
* @return
*/
@ApiOperation(value = "修改用户状态")
@Operation(summary = "修改用户状态")
@GetMapping("/users/updateEnabled")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Integer"),
@ApiImplicitParam(name = "enabled", value = "是否启用", required = true, dataType = "Boolean")
@Parameters({
@Parameter(name = "id",description = "用户id",required = true,in=ParameterIn.QUERY),
@Parameter(name = "enabled",description = "是否启用",required = true,in= ParameterIn.QUERY)
})
public Result updateEnabled(@RequestParam Map<String, Object> params) {
Long id = MapUtils.getLong(params, "id");
@@ -273,11 +274,11 @@ public class SysUserController {
return Result.succeed("导入数据成功,一共【"+rowNum+"】行");
}
@ApiOperation(value = "用户全文搜索列表")
@ApiImplicitParams({
@ApiImplicitParam(name = "page", value = "分页起始位置", required = true, dataType = "Integer"),
@ApiImplicitParam(name = "limit", value = "分页结束位置", required = true, dataType = "Integer"),
@ApiImplicitParam(name = "queryStr", value = "搜索关键字", dataType = "String")
@Operation(summary = "用户全文搜索列表")
@Parameters({
@Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY),
@Parameter(name = "limit",description = "分页结束位置",required = true,in= ParameterIn.QUERY),
@Parameter(name = "queryStr",description = "搜索关键字",in= ParameterIn.QUERY)
})
@GetMapping("/users/search")
public PageResult<JsonNode> search(SearchDto searchDto) {
@@ -292,7 +293,7 @@ public class SysUserController {
* @return
*/
@GetMapping(value = "/users/roleUser/{username}")
@ApiOperation(value = "查询用户-带角色信息")
@Operation(summary = "查询用户-带角色信息")
@Cacheable(value = "userRoles", key = "#username")
public SysUser selectRoleUser(@PathVariable("username") String username){
SysUser sysUser = selectByUsername(username);
@@ -3,6 +3,9 @@ package com.central.user.mapper;
import com.central.db.mapper.SuperMapper;
import com.central.common.model.SysMenu;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 菜单
@@ -11,5 +14,5 @@ import org.apache.ibatis.annotations.Mapper;
*/
@Mapper
public interface SysMenuMapper extends SuperMapper<SysMenu> {
List<SysMenu> findByUserId(@Param("userId") Long userId, @Param("type") Integer type);
}
@@ -34,6 +34,8 @@ public interface ISysMenuService extends ISuperService<SysMenu> {
*/
List<SysMenu> findByRoles(Set<Long> roleIds);
List<SysMenu> findByUserId(Long userId, Integer type);
/**
* 角色菜单列表
* @param roleIds 角色ids
@@ -11,7 +11,7 @@ import com.central.common.service.ISuperService;
/**
* @author zlt
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public interface ISysRoleService extends ISuperService<SysRole> {
@@ -8,14 +8,13 @@ import com.central.common.service.ISuperService;
import com.central.user.model.SysUserExcel;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.common.model.LoginAppUser;
import com.central.common.model.SysRole;
import com.central.common.model.SysUser;
/**
* @author zlt
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public interface ISysUserService extends ISuperService<SysUser> {
@@ -24,18 +23,18 @@ public interface ISysUserService extends ISuperService<SysUser> {
* @param username
* @return
*/
LoginAppUser findByUsername(String username);
SysUser findByUsername(String username);
LoginAppUser findByOpenId(String username);
SysUser findByOpenId(String username);
LoginAppUser findByMobile(String username);
SysUser findByMobile(String username);
/**
* 通过SysUser 转换为 LoginAppUser,把roles和permissions也查询出来
* 通过SysUser 把roles和permissions也查询出来
* @param sysUser
* @return
*/
LoginAppUser getLoginAppUser(SysUser sysUser);
void setUserPermission(SysUser sysUser);
/**
* 根据用户名查询用户
@@ -66,6 +66,10 @@ public class SysMenuServiceImpl extends SuperServiceImpl<SysMenuMapper, SysMenu>
public List<SysMenu> findByRoleCodes(Set<String> roleCodes, Integer type) {
return roleMenuService.findMenusByRoleCodes(roleCodes, type);
}
@Override
public List<SysMenu> findByUserId(Long userId, Integer type) {
return baseMapper.findByUserId(userId, type);
}
/**
* 查询所有菜单
@@ -53,46 +53,43 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
private DistributedLock lock;
@Override
public LoginAppUser findByUsername(String username) {
public SysUser findByUsername(String username) {
SysUser sysUser = this.selectByUsername(username);
return getLoginAppUser(sysUser);
setUserPermission(sysUser);
return sysUser;
}
@Override
public LoginAppUser findByOpenId(String username) {
public SysUser findByOpenId(String username) {
SysUser sysUser = this.selectByOpenId(username);
return getLoginAppUser(sysUser);
setUserPermission(sysUser);
return sysUser;
}
@Override
public LoginAppUser findByMobile(String username) {
public SysUser findByMobile(String username) {
SysUser sysUser = this.selectByMobile(username);
return getLoginAppUser(sysUser);
setUserPermission(sysUser);
return sysUser;
}
@Override
public LoginAppUser getLoginAppUser(SysUser sysUser) {
public void setUserPermission(SysUser sysUser) {
if (sysUser != null) {
LoginAppUser loginAppUser = new LoginAppUser();
BeanUtils.copyProperties(sysUser, loginAppUser);
List<SysRole> sysRoles = roleUserService.findRolesByUserId(sysUser.getId());
// 设置角色
loginAppUser.setRoles(sysRoles);
sysUser.setRoles(sysRoles);
Set<String> permissions;
if (!CollectionUtils.isEmpty(sysRoles)) {
Set<Long> roleIds = sysRoles.stream().map(SuperEntity::getId).collect(Collectors.toSet());
List<SysMenu> menus = roleMenuMapper.findMenusByRoleIds(roleIds, CommonConstant.PERMISSION);
if (!CollectionUtils.isEmpty(menus)) {
Set<String> permissions = menus.stream().map(p -> p.getPath())
permissions = menus.stream().map(p -> p.getPath())
.collect(Collectors.toSet());
// 设置权限集合
loginAppUser.setPermissions(permissions);
sysUser.setPermissions(permissions);
}
}
return loginAppUser;
}
return null;
}
/**
@@ -13,13 +13,18 @@ mybatis-plus:
db-config:
id-type: auto
springdoc:
group-configs:
- group: 'default'
paths-to-match: '/**'
packages-to-scan: com.central.user.controller
knife4j:
enable: true
setting:
swagger-model-name: 用户中心接口文档
zlt:
swagger:
enabled: true
title: 用户中心
description: 用户中心接口文档
version: 1.0
base-package: com.central.user.controller
cache-manager:
configs:
- key: menu
@@ -2,5 +2,15 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.central.user.mapper.SysMenuMapper">
<select id="findByUserId" resultType="com.central.common.model.SysMenu">
select distinct t.* from sys_menu t
inner join sys_role_menu r on r.menu_id = t.id
inner join sys_role_user ru on ru.role_id = r.role_id
where ru.user_id = #{userId}
<if test="type != null">
and t.type = #{type}
</if>
and t.hidden = 0
ORDER BY sort ASC
</select>
</mapper>
@@ -1,6 +1,5 @@
package com.central.user.service;
import com.central.common.model.LoginAppUser;
import static org.assertj.core.api.Assertions.*;
import com.central.common.model.PageResult;
@@ -27,8 +26,8 @@ public class SysUserServiceTest {
@Test
public void testFindByUsername() {
LoginAppUser loginAppUser = sysUserService.findByUsername("admin");
assertThat(loginAppUser).isNotNull();
SysUser sysUser = sysUserService.findByUsername("admin");
assertThat(sysUser).isNotNull();
}
@Test
+1 -2
View File
@@ -4,7 +4,7 @@
<parent>
<groupId>com.zlt</groupId>
<artifactId>central-platform</artifactId>
<version>5.6.0</version>
<version>6.0.0</version>
</parent>
<artifactId>zlt-commons</artifactId>
<description>通用组件</description>
@@ -14,7 +14,6 @@
<module>zlt-redis-spring-boot-starter</module>
<module>zlt-common-spring-boot-starter</module>
<module>zlt-db-spring-boot-starter</module>
<module>zlt-swagger2-spring-boot-starter</module>
<module>zlt-log-spring-boot-starter</module>
<module>zlt-loadbalancer-spring-boot-starter</module>
<module>zlt-auth-client-spring-boot-starter</module>
@@ -5,7 +5,7 @@
<parent>
<groupId>com.zlt</groupId>
<artifactId>zlt-commons</artifactId>
<version>5.6.0</version>
<version>6.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
@@ -13,8 +13,16 @@
<description>认证客户端通用组件</description>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-authorization-server</artifactId>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-common-core</artifactId>
</dependency>
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>oauth2-oidc-sdk</artifactId>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
@@ -37,11 +45,6 @@
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-websocket</artifactId>
@@ -1,7 +1,6 @@
package com.central.oauth2.common;
import com.central.oauth2.common.properties.SecurityProperties;
import com.central.oauth2.common.properties.TokenStoreProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
@@ -12,10 +11,10 @@ import org.springframework.context.annotation.ComponentScan;
* @version 1.0
* @date 2021/7/24
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@EnableConfigurationProperties({SecurityProperties.class, TokenStoreProperties.class})
@EnableConfigurationProperties({SecurityProperties.class})
@ComponentScan
public class AuthClientAutoConfiguration {
}
@@ -0,0 +1,55 @@
package com.central.oauth2.common.component;
import com.central.common.constant.SecurityConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;
import java.security.Principal;
import java.util.Objects;
/**
* 内省 token 解析器
*
* @author: zlt
* @date: 2023/12/5
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@RequiredArgsConstructor
public class CustomAuthorizationServiceIntrospector implements OpaqueTokenIntrospector {
private final OAuth2AuthorizationService authorizationService;
@Override
public OAuth2AuthenticatedPrincipal introspect(String token) {
OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
if (Objects.isNull(authorization)) {
throw new InvalidBearerTokenException("invalid_token: " + token);
}
// 客户端模式默认返回
if (AuthorizationGrantType.CLIENT_CREDENTIALS.equals(authorization.getAuthorizationGrantType())) {
return new DefaultOAuth2AuthenticatedPrincipal(authorization.getPrincipalName()
, authorization.getAttributes(), AuthorityUtils.NO_AUTHORITIES);
}
String accountType = (String)authorization.getAttributes().get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
Authentication authentication = (Authentication)authorization.getAttributes().get(Principal.class.getName());
OAuth2AuthenticatedPrincipal principal = (OAuth2AuthenticatedPrincipal)authentication.getPrincipal();
principal.getAttributes().put(SecurityConstants.CLIENT_ID, authorization.getRegisteredClientId());
principal.getAttributes().put(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, accountType);
return principal;
}
}
@@ -0,0 +1,94 @@
package com.central.oauth2.common.component;
import com.central.oauth2.common.properties.PermitProperties;
import com.central.oauth2.common.properties.SecurityProperties;
import com.central.oauth2.common.util.AuthUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.server.resource.BearerTokenError;
import org.springframework.security.oauth2.server.resource.BearerTokenErrors;
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import java.util.Arrays;
/**
* @author: zlt
* @date: 2023/11/8
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@ConditionalOnClass(HttpServletRequest.class)
@Component
public class CustomBearerTokenResolver implements BearerTokenResolver {
private final boolean allowFormEncodedBodyParameter = false;
private final boolean allowUriQueryParameter = true;
private final String bearerTokenHeaderName = HttpHeaders.AUTHORIZATION;
private final PathMatcher pathMatcher = new AntPathMatcher();
private final PermitProperties permitProperties;
public CustomBearerTokenResolver(SecurityProperties securityProperties) {
this.permitProperties = securityProperties.getIgnore();
}
@Override
public String resolve(HttpServletRequest request) {
boolean match = Arrays.stream(permitProperties.getUrls())
.anyMatch(url -> pathMatcher.match(url, request.getRequestURI()));
if (match) {
return null;
}
final String authorizationHeaderToken = AuthUtils.extractHeaderToken(request);
final String parameterToken = isParameterTokenSupportedForRequest(request)
? resolveFromRequestParameters(request) : null;
if (authorizationHeaderToken != null) {
if (parameterToken != null) {
final BearerTokenError error = BearerTokenErrors
.invalidRequest("Found multiple bearer tokens in the request");
throw new OAuth2AuthenticationException(error);
}
return authorizationHeaderToken;
}
if (parameterToken != null && isParameterTokenEnabledForRequest(request)) {
return parameterToken;
}
return null;
}
private static String resolveFromRequestParameters(HttpServletRequest request) {
String[] values = request.getParameterValues("access_token");
if (values == null || values.length == 0) {
return null;
}
if (values.length == 1) {
return values[0];
}
BearerTokenError error = BearerTokenErrors.invalidRequest("Found multiple bearer tokens in the request");
throw new OAuth2AuthenticationException(error);
}
private boolean isParameterTokenSupportedForRequest(final HttpServletRequest request) {
return (("POST".equals(request.getMethod())
&& MediaType.APPLICATION_FORM_URLENCODED_VALUE.equals(request.getContentType()))
|| "GET".equals(request.getMethod()));
}
private boolean isParameterTokenEnabledForRequest(final HttpServletRequest request) {
return ((this.allowFormEncodedBodyParameter && "POST".equals(request.getMethod())
&& MediaType.APPLICATION_FORM_URLENCODED_VALUE.equals(request.getContentType()))
|| (this.allowUriQueryParameter && "GET".equals(request.getMethod())));
}
}
@@ -0,0 +1,56 @@
package com.central.oauth2.common.component;
import com.central.common.constant.SecurityConstants;
import com.central.oauth2.common.util.AuthUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal;
import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionException;
import org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector;
import reactor.core.publisher.Mono;
import java.security.Principal;
import java.util.*;
/**
* webFlux 内省 token 解析器
*
* @author zlt
* @version 1.0
* @date 2023/12/4
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
public class CustomReactiveAuthorizationServiceIntrospector implements ReactiveOpaqueTokenIntrospector {
@Override
public Mono<OAuth2AuthenticatedPrincipal> introspect(String accessTokenValue) {
return Mono.just(accessTokenValue)
.map(AuthUtils::checkAccessTokenToAuth)
.map(this::convertClaimsSet)
.onErrorMap((e) -> !(e instanceof OAuth2IntrospectionException), this::onError);
}
private OAuth2AuthenticatedPrincipal convertClaimsSet(OAuth2Authorization authorization) {
Map<String, Object> claims = new HashMap<>();
Collection<GrantedAuthority> authorities = new ArrayList<>();
claims.put(SecurityConstants.CLIENT_ID, authorization.getRegisteredClientId());
claims.putAll(authorization.getAttributes());
Authentication authentication = (Authentication)authorization.getAttributes().get(Principal.class.getName());
if (authentication != null) {
authorities.addAll(authentication.getAuthorities());
}
return new OAuth2IntrospectionAuthenticatedPrincipal(authorization.getPrincipalName(), claims, authorities);
}
private OAuth2IntrospectionException onError(Throwable ex) {
return new OAuth2IntrospectionException(ex.getMessage(), ex);
}
}
@@ -0,0 +1,147 @@
package com.central.oauth2.common.component;
import com.central.oauth2.common.properties.PermitProperties;
import com.central.oauth2.common.properties.SecurityProperties;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.server.resource.BearerTokenError;
import org.springframework.security.oauth2.server.resource.BearerTokenErrors;
import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthenticationToken;
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 实现排除鉴权的地址即使参数带 access_token 也不会进行鉴权
*
* @author zlt
* @version 1.0
* @date 2023/12/5
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class CustomServerBearerTokenAuthConverter implements ServerAuthenticationConverter {
private final PathMatcher pathMatcher = new AntPathMatcher();
private static final Pattern authorizationPattern = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-._~+/]+=*)$",
Pattern.CASE_INSENSITIVE);
private boolean allowUriQueryParameter = false;
private String bearerTokenHeaderName = HttpHeaders.AUTHORIZATION;
private final PermitProperties permitProperties;
public CustomServerBearerTokenAuthConverter(SecurityProperties securityProperties) {
this.permitProperties = securityProperties.getIgnore();
}
@Override
public Mono<Authentication> convert(ServerWebExchange exchange) {
return Mono.fromCallable(() -> token(exchange.getRequest())).map((token) -> {
if (token.isEmpty()) {
BearerTokenError error = invalidTokenError();
throw new OAuth2AuthenticationException(error);
}
return new BearerTokenAuthenticationToken(token);
});
}
private String token(ServerHttpRequest request) {
boolean match = Arrays.stream(permitProperties.getUrls())
.anyMatch(url -> pathMatcher.match(url, request.getURI().getPath()));
if (match) {
return null;
}
String authorizationHeaderToken = resolveFromAuthorizationHeader(request.getHeaders());
String parameterToken = resolveAccessTokenFromRequest(request);
if (authorizationHeaderToken != null) {
if (parameterToken != null) {
BearerTokenError error = BearerTokenErrors
.invalidRequest("Found multiple bearer tokens in the request");
throw new OAuth2AuthenticationException(error);
}
return authorizationHeaderToken;
}
if (parameterToken != null && isParameterTokenSupportedForRequest(request)) {
return parameterToken;
}
return null;
}
private static String resolveAccessTokenFromRequest(ServerHttpRequest request) {
List<String> parameterTokens = request.getQueryParams().get("access_token");
if (CollectionUtils.isEmpty(parameterTokens)) {
return null;
}
if (parameterTokens.size() == 1) {
return parameterTokens.get(0);
}
BearerTokenError error = BearerTokenErrors.invalidRequest("Found multiple bearer tokens in the request");
throw new OAuth2AuthenticationException(error);
}
/**
* Set if transport of access token using URI query parameter is supported. Defaults
* to {@code false}.
*
* The spec recommends against using this mechanism for sending bearer tokens, and
* even goes as far as stating that it was only included for completeness.
* @param allowUriQueryParameter if the URI query parameter is supported
*/
public void setAllowUriQueryParameter(boolean allowUriQueryParameter) {
this.allowUriQueryParameter = allowUriQueryParameter;
}
/**
* Set this value to configure what header is checked when resolving a Bearer Token.
* This value is defaulted to {@link HttpHeaders#AUTHORIZATION}.
*
* This allows other headers to be used as the Bearer Token source such as
* {@link HttpHeaders#PROXY_AUTHORIZATION}
* @param bearerTokenHeaderName the header to check when retrieving the Bearer Token.
* @since 5.4
*/
public void setBearerTokenHeaderName(String bearerTokenHeaderName) {
this.bearerTokenHeaderName = bearerTokenHeaderName;
}
private String resolveFromAuthorizationHeader(HttpHeaders headers) {
String authorization = headers.getFirst(this.bearerTokenHeaderName);
if (!StringUtils.startsWithIgnoreCase(authorization, "bearer")) {
return null;
}
Matcher matcher = authorizationPattern.matcher(authorization);
if (!matcher.matches()) {
BearerTokenError error = invalidTokenError();
throw new OAuth2AuthenticationException(error);
}
return matcher.group("token");
}
private static BearerTokenError invalidTokenError() {
return BearerTokenErrors.invalidToken("Bearer token is malformed");
}
private boolean isParameterTokenSupportedForRequest(ServerHttpRequest request) {
return this.allowUriQueryParameter && HttpMethod.GET.equals(request.getMethod());
}
}
@@ -0,0 +1,134 @@
package com.central.oauth2.common.config;
import cn.hutool.core.util.StrUtil;
import com.central.common.constant.SecurityConstants;
import com.central.common.utils.ResponseUtil;
import com.central.common.utils.WebfluxResponseUtil;
import com.central.oauth2.common.enums.TokenType;
import com.central.oauth2.common.properties.SecurityProperties;
import com.central.oauth2.common.service.impl.RedisOAuth2AuthorizationService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth2.server.authorization.InMemoryOAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.text.ParseException;
import java.util.UUID;
/**
* @author zlt
* @date: 2023/11/25
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class BaseSecurityConfig {
@Bean
public OAuth2AuthorizationService oAuth2AuthorizationService(SecurityProperties securityProperties, RedissonClient redisson) {
String tokenType = securityProperties.getResourceServer().getTokenType();
if (TokenType.MEMORY.getName().equals(tokenType)) {
return new InMemoryOAuth2AuthorizationService();
}
return new RedisOAuth2AuthorizationService(securityProperties, redisson);
}
/**
* 鉴权错误处理
*/
@Bean
public AuthenticationEntryPoint authenticationEntryPoint(ObjectMapper objectMapper) {
return (request, response, authException) -> ResponseUtil.responseFailed(objectMapper, response, authException.getMessage());
}
@Bean
public ServerAuthenticationEntryPoint serverAuthenticationEntryPoint() {
return (exchange, e) -> WebfluxResponseUtil.responseFailed(exchange, HttpStatus.UNAUTHORIZED.value(), e.getMessage());
}
/**
* 越权错误处理
*/
@Bean
public AccessDeniedHandler oAuth2AccessDeniedHandler(ObjectMapper objectMapper) {
return (request, response, authException) -> ResponseUtil.responseFailed(objectMapper, response, authException.getMessage());
}
@Bean
public ServerAccessDeniedHandler serverAccessDeniedHandler() {
return (exchange, e) -> WebfluxResponseUtil.responseFailed(exchange, HttpStatus.FORBIDDEN.value(), e.getMessage());
}
/**
* 配置jwk源,使用非对称加密,公开用于检索匹配指定选择器的JWK的方法
*/
@Bean
public JWKSource<SecurityContext> jwkSource(RedissonClient redisson) throws ParseException {
RBucket<String> rBucket = redisson.getBucket(SecurityConstants.AUTHORIZATION_JWS_PREFIX_KEY);
String jwkSetCache = rBucket.get();
JWKSet jwkSet;
// 多个服务共用同一个 jwkSource 对象
if (StrUtil.isEmpty(jwkSetCache)) {
KeyPair keyPair = generateRsaKey();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAKey rsaKey = new RSAKey.Builder(publicKey)
.privateKey(privateKey)
.keyID(UUID.randomUUID().toString())
.build();
jwkSet = new JWKSet(rsaKey);
String jwkSetString = jwkSet.toString(Boolean.FALSE);
// 缓存
boolean success = rBucket.setIfAbsent(jwkSetString);
if (!success) {// 防止同时启动服务时创建了多个jwks
jwkSetCache = rBucket.get();
jwkSet = JWKSet.parse(jwkSetCache);
}
} else {
// 解析存储的jws
jwkSet = JWKSet.parse(jwkSetCache);
}
return new ImmutableJWKSet<>(jwkSet);
}
private static KeyPair generateRsaKey() {
KeyPair keyPair;
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
keyPair = keyPairGenerator.generateKeyPair();
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
return keyPair;
}
@Bean
public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
}
@Bean
public JwtEncoder jwtEncoder(JWKSource<SecurityContext> jwkSource) {
return new NimbusJwtEncoder(jwkSource);
}
}
@@ -1,86 +1,85 @@
package com.central.oauth2.common.config;
import com.central.oauth2.common.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.authentication.TokenExtractor;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.annotation.Resource;
/**
* @author zlt
*/
@Import(DefaultSecurityHandlerConfig.class)
public class DefaultResourceServerConf extends ResourceServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Resource
private AuthenticationEntryPoint authenticationEntryPoint;
@Resource
private OAuth2WebSecurityExpressionHandler expressionHandler;
@Resource
private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
@Autowired
private SecurityProperties securityProperties;
@Resource
private TokenExtractor tokenExtractor;
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.tokenStore(tokenStore)
.stateless(true)
.authenticationEntryPoint(authenticationEntryPoint)
.expressionHandler(expressionHandler)
.accessDeniedHandler(oAuth2AccessDeniedHandler)
.tokenExtractor(tokenExtractor);
}
@Override
public void configure(HttpSecurity http) throws Exception {
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.AuthorizedUrl authorizedUrl = setHttp(http)
.authorizeRequests()
.antMatchers(securityProperties.getIgnore().getUrls()).permitAll()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.anyRequest();
setAuthenticate(authorizedUrl);
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.httpBasic().disable()
.headers()
.frameOptions().disable()
.and()
.csrf().disable();
}
/**
* url权限控制,默认是认证就通过,可以重写实现个性化
* @param authorizedUrl
*/
public HttpSecurity setAuthenticate(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.AuthorizedUrl authorizedUrl) {
return authorizedUrl.authenticated().and();
}
/**
* 留给子类重写扩展功能
* @param http
*/
public HttpSecurity setHttp(HttpSecurity http) {
return http;
}
}
package com.central.oauth2.common.config;
import cn.hutool.extra.spring.SpringUtil;
import com.central.oauth2.common.component.CustomAuthorizationServiceIntrospector;
import com.central.oauth2.common.component.CustomBearerTokenResolver;
import com.central.oauth2.common.properties.SecurityProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import javax.annotation.Resource;
/**
* @author zlt
* @version 1.0
* @date 2023/12/5
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@EnableWebSecurity
@Import(BaseSecurityConfig.class)
public class DefaultResourceServerConf {
@Resource
private SecurityProperties securityProperties;
@Resource
private AuthenticationEntryPoint authenticationEntryPoint;
@Resource
private CustomBearerTokenResolver customBearerTokenResolver;
@Resource
private AccessDeniedHandler oAuth2AccessDeniedHandler;
@Bean
public SecurityFilterChain springSecurityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(authorizeRequests -> {
AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizedUrl authorizedUrl = authorizeRequests
.requestMatchers(HttpMethod.OPTIONS).permitAll()
.requestMatchers(securityProperties.getIgnore().getUrls()).permitAll()
.anyRequest();
this.setAuthenticate(authorizedUrl);
}).headers(header -> header
// 避免iframe同源无法登录许iframe
.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)
).csrf(AbstractHttpConfigurer::disable)
.cors(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED));
// 资源服务配置
http.oauth2ResourceServer(oauth2 -> {
oauth2.authenticationEntryPoint(authenticationEntryPoint)
.bearerTokenResolver(customBearerTokenResolver)
.accessDeniedHandler(oAuth2AccessDeniedHandler)
.opaqueToken(token -> token.introspector(this.getOpaqueTokenIntrospector()));
});
return http.build();
}
protected OpaqueTokenIntrospector getOpaqueTokenIntrospector() {
OAuth2AuthorizationService authorizationService = SpringUtil.getBean(OAuth2AuthorizationService.class);
return new CustomAuthorizationServiceIntrospector(authorizationService);
}
/**
* url权限控制,默认是认证就通过,可以重写实现个性化
*/
protected void setAuthenticate(AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizedUrl authorizedUrl) {
authorizedUrl.authenticated();
}
}
@@ -1,55 +0,0 @@
package com.central.oauth2.common.config;
import com.central.common.utils.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author zlt
*/
public class DefaultSecurityHandlerConfig {
@Resource
private ObjectMapper objectMapper;
/**
* 未登录,返回401
*
* @return
*/
@Bean
public AuthenticationEntryPoint authenticationEntryPoint() {
return (request, response, authException) -> ResponseUtil.responseFailed(objectMapper, response, authException.getMessage());
}
@Bean
public OAuth2WebSecurityExpressionHandler oAuth2WebSecurityExpressionHandler(ApplicationContext applicationContext) {
OAuth2WebSecurityExpressionHandler expressionHandler = new OAuth2WebSecurityExpressionHandler();
expressionHandler.setApplicationContext(applicationContext);
return expressionHandler;
}
/**
* 处理spring security oauth 处理失败返回消息格式
*/
@Bean
public OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler() {
return new OAuth2AccessDeniedHandler() {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException {
ResponseUtil.responseFailed(objectMapper, response, authException.getMessage());
}
};
}
}
@@ -0,0 +1,116 @@
package com.central.oauth2.common.config;
import com.central.oauth2.common.component.CustomReactiveAuthorizationServiceIntrospector;
import com.central.oauth2.common.component.CustomServerBearerTokenAuthConverter;
import com.central.oauth2.common.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.oauth2.server.resource.authentication.OpaqueTokenReactiveAuthenticationManager;
import org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.security.web.server.authentication.AuthenticationWebFilter;
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter;
import org.springframework.security.web.server.authentication.ServerAuthenticationEntryPointFailureHandler;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import javax.annotation.Resource;
/**
* @author zlt
* @version 1.0
* @date 2023/12/5
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@EnableWebFluxSecurity
@Import(BaseSecurityConfig.class)
public class DefaultWebFluxResourceServerConf {
@Resource
private SecurityProperties securityProperties;
@Resource
private ServerAuthenticationEntryPoint serverAuthenticationEntryPoint;
@Resource
private ServerAccessDeniedHandler serverAccessDeniedHandler;
@Autowired(required = false)
private ReactiveAuthorizationManager authorizationManager;
@Autowired(required = false)
private ServerAuthenticationSuccessHandler successHandler;
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http.csrf(ServerHttpSecurity.CsrfSpec::disable)
.cors(ServerHttpSecurity.CorsSpec::disable)
.headers(hSpec -> hSpec.frameOptions(ServerHttpSecurity.HeaderSpec.FrameOptionsSpec::disable))
.httpBasic(ServerHttpSecurity.HttpBasicSpec::disable)
.exceptionHandling(e -> {
e.authenticationEntryPoint(serverAuthenticationEntryPoint)
.accessDeniedHandler(serverAccessDeniedHandler);
});
http.authorizeExchange(exchange -> {
if (securityProperties.getAuth().getHttpUrls().length > 0) {
exchange.pathMatchers(securityProperties.getAuth().getHttpUrls()).authenticated();
}
if (securityProperties.getIgnore().getUrls().length > 0) {
exchange.pathMatchers(securityProperties.getIgnore().getUrls()).permitAll();
}
exchange.pathMatchers(HttpMethod.OPTIONS).permitAll();
// url 鉴权
if (authorizationManager != null) {
exchange.anyExchange().access(authorizationManager);
} else {
exchange.anyExchange().authenticated();
}
});
http.addFilterAt(this.getAuthWebFilter(), SecurityWebFiltersOrder.AUTHENTICATION);
return http.build();
}
protected AuthenticationWebFilter getAuthWebFilter() {
AuthenticationWebFilter oauth2 = new AuthenticationWebFilter(this.getAuthenticationManager());
oauth2.setServerAuthenticationConverter(this.getAuthenticationConverter());
oauth2.setAuthenticationFailureHandler(this.getFailureHandler());
if (successHandler != null) {
oauth2.setAuthenticationSuccessHandler(successHandler);
}
return oauth2;
}
protected ReactiveAuthenticationManager getAuthenticationManager() {
return new OpaqueTokenReactiveAuthenticationManager(this.getOpaqueTokenIntrospector());
}
protected ServerAuthenticationConverter getAuthenticationConverter() {
CustomServerBearerTokenAuthConverter authenticationConverter =
new CustomServerBearerTokenAuthConverter(securityProperties);
authenticationConverter.setAllowUriQueryParameter(true);
return authenticationConverter;
}
protected ReactiveOpaqueTokenIntrospector getOpaqueTokenIntrospector() {
return new CustomReactiveAuthorizationServiceIntrospector();
}
protected ServerAuthenticationEntryPointFailureHandler getFailureHandler() {
ServerAuthenticationEntryPointFailureHandler failureHandler =
new ServerAuthenticationEntryPointFailureHandler(serverAuthenticationEntryPoint);
failureHandler.setRethrowAuthenticationServiceException(false);
return failureHandler;
}
}
@@ -1,12 +1,11 @@
package com.central.oauth2.common.config;
import com.central.oauth2.common.util.AuthUtils;
import jakarta.websocket.server.ServerEndpointConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.websocket.server.ServerEndpointConfig;
/**
* webSocket鉴权配置
*
@@ -14,7 +13,7 @@ import javax.websocket.server.ServerEndpointConfig;
* @version 1.0
* @date 2022/5/8
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@@ -1,89 +0,0 @@
package com.central.oauth2.common.constants;
/**
* id_token属性名常量
*
* @author zlt
* @version 1.0
* @date 2021/4/23
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class IdTokenClaimNames {
/**
* {@code iss} - the Issuer identifier
*/
public final static String ISS = "iss";
/**
* {@code sub} - the Subject identifier
*/
public final static String SUB = "sub";
/**
* {@code aud} - the Audience(s) that the ID Token is intended for
*/
public final static String AUD = "aud";
/**
* {@code exp} - the Expiration time on or after which the ID Token MUST NOT be accepted
*/
public final static String EXP = "exp";
/**
* {@code iat} - the time at which the ID Token was issued
*/
public final static String IAT = "iat";
/**
* {@code auth_time} - the time when the End-User authentication occurred
*/
public final static String AUTH_TIME = "auth_time";
/**
* {@code nonce} - a {@code String} value used to associate a Client session with an ID Token,
* and to mitigate replay attacks.
*/
public final static String NONCE = "nonce";
/**
* {@code acr} - the Authentication Context Class Reference
*/
public final static String ACR = "acr";
/**
* {@code amr} - the Authentication Methods References
*/
public final static String AMR = "amr";
/**
* {@code azp} - the Authorized party to which the ID Token was issued
*/
public final static String AZP = "azp";
/**
* {@code at_hash} - the Access Token hash value
*/
public final static String AT_HASH = "at_hash";
/**
* {@code c_hash} - the Authorization Code hash value
*/
public final static String C_HASH = "c_hash";
/**
* {@code name} - 用户姓名
*/
public final static String NAME = "name";
/**
* {@code login_name} - 登录名
*/
public final static String L_NAME = "login_name";
/**
* {@code picture} - 头像照片
*/
public final static String PIC = "picture";
}
@@ -1,96 +0,0 @@
package com.central.oauth2.common.converter;
import com.central.common.model.LoginAppUser;
import com.central.common.model.SysUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.util.StringUtils;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 优化自org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter
* jwt返回的principal改为返回SysUser,增加扩展字段
*
* @author zlt
* @date 2019/8/5
*/
public class CustomUserAuthenticationConverter implements UserAuthenticationConverter {
private Collection<? extends GrantedAuthority> defaultAuthorities;
private UserDetailsService userDetailsService;
/**
* Optional {@link UserDetailsService} to use when extracting an {@link Authentication} from the incoming map.
*
* @param userDetailsService the userDetailsService to set
*/
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
/**
* Default value for authorities if an Authentication is being created and the input has no data for authorities.
* Note that unless this property is set, the default Authentication created by {@link #extractAuthentication(Map)}
* will be unauthenticated.
*
* @param defaultAuthorities the defaultAuthorities to set. Default null.
*/
public void setDefaultAuthorities(String[] defaultAuthorities) {
this.defaultAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
.arrayToCommaDelimitedString(defaultAuthorities));
}
@Override
public Map<String, ?> convertUserAuthentication(Authentication authentication) {
Map<String, Object> response = new LinkedHashMap<String, Object>();
response.put(USERNAME, authentication.getName());
if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
}
return response;
}
@Override
public Authentication extractAuthentication(Map<String, ?> map) {
if (map.containsKey(USERNAME)) {
Object principal = map.get(USERNAME);
Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
if (userDetailsService != null) {
UserDetails user = userDetailsService.loadUserByUsername((String) map.get(USERNAME));
authorities = user.getAuthorities();
principal = user;
} else {
Integer id = (Integer)map.get("id");
LoginAppUser user = new LoginAppUser();
user.setUsername((String)principal);
user.setId(Long.valueOf(id));
principal = user;
}
return new UsernamePasswordAuthenticationToken(principal, "N/A", authorities);
}
return null;
}
private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
if (!map.containsKey(AUTHORITIES)) {
return defaultAuthorities;
}
Object authorities = map.get(AUTHORITIES);
if (authorities instanceof String) {
return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
}
if (authorities instanceof Collection) {
return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
.collectionToCommaDelimitedString((Collection<?>) authorities));
}
throw new IllegalArgumentException("Authorities must be either a String or a Collection");
}
}
@@ -0,0 +1,23 @@
package com.central.oauth2.common.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* token 类型
*
* @author: zlt
* @date: 2023/12/4
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Getter
@AllArgsConstructor
public enum TokenType {
REDIS("redis"),
MEMORY("inMemory"),
JWT("jwt"),
REF("reference");
private final String name;
}
@@ -0,0 +1,17 @@
package com.central.oauth2.common.exception;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
/**
* @author: zlt
* @date: 2023/12/10
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class CustomOAuth2AuthorizationException extends OAuth2AuthenticationException {
public CustomOAuth2AuthorizationException(String msg) {
super(new OAuth2Error(msg), msg);
}
}
@@ -0,0 +1,46 @@
package com.central.oauth2.common.pojo;
import lombok.Data;
import java.io.Serial;
import java.io.Serializable;
/**
* @author zlt
* @version 1.0
* @date 2023/12/2
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Data
public class ClientDto implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
private String id;
private String clientId;
/**
* 应用名称
*/
private String clientName;
private String resourceIds = "";
private String clientSecret;
private String clientSecretStr;
private String scope = "all";
private String authorizedGrantTypes = "authorization_code,password,refresh_token,client_credentials";
private String webServerRedirectUri;
private String authorities = "";
private Integer accessTokenValiditySeconds = 18000;
private Integer refreshTokenValiditySeconds = 28800;
private String additionalInformation = "{}";
private String autoapprove = "true";
/**
* 令牌类型: reference 引用令牌(不透明), self-contained 自包含令牌(jwt))
*/
private String tokenFormat = "reference";
private Long creatorId;
}
@@ -10,7 +10,7 @@ import lombok.Setter;
* @version 1.0
* @date 2019/1/19
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
@@ -58,4 +58,9 @@ public class AuthProperties {
* 默认私钥对应的公钥为:MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6u4sP969hZP7BUEeAXJlq5wEmZ2CIZU4+5JADY8Ium55qGaE5qXEwMaV+M2HFWU4PZbHfH+RGEIMwjkARRok93krFnJuuwTjLwgyUSsKm5M7v3Ek8zdqs474v1qOxqE6BmHz9QJfgnAtFYxwEyVRoQ12+IAhpOzDU3rz02VR05kGCrgGU6szxDtp6cQ+u9ACGPy/uKdIQ6H7aM/oxMyPlwK9H38ni6Lxai7q56qp6F1p7drxh8CWJZ3j0NicB5ZPnOMtrGL5lfnifHBjB+CDJXv8kffY0zwL3J+LrnyFbpKeNeMJZpykoYW85Pdz+8WnE9KGMM3EeOeD/QX/OfMdFQIDAQAB
*/
private String decryptParamPrivateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDq7iw/3r2Fk/sFQR4BcmWrnASZnYIhlTj7kkANjwi6bnmoZoTmpcTAxpX4zYcVZTg9lsd8f5EYQgzCOQBFGiT3eSsWcm67BOMvCDJRKwqbkzu/cSTzN2qzjvi/Wo7GoToGYfP1Al+CcC0VjHATJVGhDXb4gCGk7MNTevPTZVHTmQYKuAZTqzPEO2npxD670AIY/L+4p0hDoftoz+jEzI+XAr0ffyeLovFqLurnqqnoXWnt2vGHwJYlnePQ2JwHlk+c4y2sYvmV+eJ8cGMH4IMle/yR99jTPAvcn4uufIVukp414wlmnKShhbzk93P7xacT0oYwzcR454P9Bf858x0VAgMBAAECggEBAJxK94VGWi+T01wbhirQQHN6yFSqRPiyncY/9f0PO29MMAOosKIBhnP5qaxsj4HcZR4UQYLCG3VX+8T6xwMx8YXyRogYeTJSfhG8Ej2NtPDrcsRaMYrdQ09RvosPZA0hFclJQVOu0HumxVegpq8WFMhgfNW16KwgF5JiKfRpY5aw4NDWZFmdNExdymrWPheI8pWBq/U+l8oqrekhbiEKXM2UXmLlKTS9Nk46LRYwaaiDW8JEFuPdx0cnakb+ecCXGd/8Cc8Hxn/mLyvqS1cWHT3J+lXRkfcnNnrJTR9qhf9l077XBMJqVckFEpK4kKbXHZd957ISAxq48Tm+xMX9KAECgYEA995szPToU0BxTTtOD4Z4c5JvbURQEcDQl/dB+qCQnu/orW5ZWv4++lHq2SZPjzbt7M8OaoRN8A5zYcNrYe4kBhLOLqHdaS1yUGIIjAejEAJplR5GqI3T5qzaLjpyiUZpO0mOcwAazCevnSXH6uO5jP0sjwxwaXz4OsTcpHIXHqECgYEA8qMXhh+G88+vTELL/2dHhtTIf7IAJLQ37c1Xrm6uwOHPfiDr256Lc4EzF8QAQqlHoYm1jRK7xDfFymY/SJKJVhYehWlNilnMuDuDOqseC/Zn2KgjMSjLLVkbp25DcpAu6SSiWlBvemrV3jivX/MU0BFp8HjbrlUcl12lRtYgrfUCgYB+iN2iA6RWW597fbrr0gnLdgXMEgOODJBwA5l7CFzLxk1Ru/OBsCkWQJtTH2ueALyVF16UodXnpnjgf5Jh++AH+bGnvJn7B2hEAMe8NGnZ0mFz7nDDuyNhrvvyfYPa8EboLTS7IGKNtfTAlHjqQDaI8vW8UO1R7KoL1lOM33FOAQKBgQDt/Z6jReU+3CUbbiFeANWdoLSQ2+1cExEQxWsNgy8Rreux0WTG4/nwb3fIBc4jlJrYDZTwLMHTssjkv+muq1zd/ZAuV51g6LfutSEAuLseDLDLSBBMtbCkaFTBo1uw0U/SCsbcQy01K/leoMcUG//8HjiFUGZZ1s3WgloM4xbmyQKBgAipgnoEyzvUfe2OMOc5ARGNSGZG4JGTGCyfnrYvYfffWpAokklHOkZMumeSWJXkx5F+MgJd9fxBK9S57PZ09gWkoeSVg0xcz5QMjh8BswfCdyet/CXQtwIfK0Wf1gWdAxC6vvv3DQ7zXbTlvqMdVOFzCKlocCYkzWMvIsejWXnW";
/**
* 授权服务器URL(颁发者标识符)
*/
private String issuer = "http://localhost:8000";
}
@@ -1,5 +1,6 @@
package com.central.oauth2.common.properties;
import com.central.common.constant.SecurityConstants;
import lombok.Getter;
import lombok.Setter;
@@ -13,7 +14,7 @@ import java.util.List;
* @version 1.0
* @date 2019/1/19
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
@@ -23,15 +24,11 @@ public class PermitProperties {
* 监控中心和swagger需要访问的url
*/
private static final String[] ENDPOINTS = {
"/oauth/**",
"/actuator/**",
"/*/v2/api-docs",
"/swagger/api-docs",
"/swagger-ui.html",
"/doc.html",
"/swagger-resources/**",
"/webjars/**",
"/druid/**"
SecurityConstants.LOGIN_PAGE,
SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/**",
"/doc.html", "/swagger-ui.html", "/v3/api-docs/**", "/swagger-ui/**",
"/actuator/**", "/webjars/**", "/druid/**",
"/css/**", "/js/**", "/images/**", "/favicon.ico", "/error"
};
/**
@@ -13,7 +13,7 @@ import java.util.List;
* @version 1.0
* @date 2019/7/9
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
@@ -0,0 +1,26 @@
package com.central.oauth2.common.properties;
import lombok.Getter;
import lombok.Setter;
/**
* 资源服务器配置
*
* @author: zlt
* @date: 2023/11/26
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
@Getter
public class ResourceServerProperties {
/**
* 令牌类型:
* - redis: 通过 redis 来验证
* - inMemory: 通过本地内存来验证
* - jwt: 自包含令牌,自己解析内容
* - reference: 引用令牌,通过远程调用授权服务器进行验证
*/
private String tokenType = "redis";
}
@@ -10,7 +10,7 @@ import org.springframework.cloud.context.config.annotation.RefreshScope;
* @version 1.0
* @date 2019/1/4
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
@@ -23,4 +23,6 @@ public class SecurityProperties {
private PermitProperties ignore = new PermitProperties();
private ValidateCodeProperties code = new ValidateCodeProperties();
private ResourceServerProperties resourceServer = new ResourceServerProperties();
}
@@ -1,27 +0,0 @@
package com.central.oauth2.common.properties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
/**
* Token配置
*
* @author zlt
* @version 1.0
* @date 2021/5/19
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
@Getter
@ConfigurationProperties(prefix = "zlt.oauth2.token.store")
@RefreshScope
public class TokenStoreProperties {
/**
* token存储类型(redis/db/authJwt/resJwt)
*/
private String type = "redis";
}
@@ -13,7 +13,7 @@ import java.util.List;
* @version 1.0
* @date 2019/8/2
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
@@ -1,44 +0,0 @@
package com.central.oauth2.common.service.impl;
import com.central.oauth2.common.properties.SecurityProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
* 自定义 TokenExtractor
*
* @author zlt
* @version 1.0
* @date 2022/6/4
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@ConditionalOnClass(HttpServletRequest.class)
@Component
public class CustomBearerTokenExtractor extends BearerTokenExtractor {
@Resource
private SecurityProperties securityProperties;
private final AntPathMatcher antPathMatcher = new AntPathMatcher();
/**
* 解决只要请求携带access_token,排除鉴权的url依然会被拦截
*/
@Override
public Authentication extract(HttpServletRequest request) {
//判断当前请求为排除鉴权的url时,直接返回null
for (String url : securityProperties.getIgnore().getUrls()) {
if (antPathMatcher.match(url, request.getRequestURI())) {
return null;
}
}
return super.extract(request);
}
}
@@ -1,120 +1,126 @@
package com.central.oauth2.common.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.central.common.constant.CommonConstant;
import com.central.common.context.TenantContextHolder;
import com.central.common.model.SysMenu;
import com.central.oauth2.common.properties.SecurityProperties;
import com.central.oauth2.common.util.AuthUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.util.AntPathMatcher;
import java.util.List;
import java.util.stream.Collectors;
/**
* 请求权限判断service
*
* @author zlt
* @date 2018/10/28
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
public abstract class DefaultPermissionServiceImpl {
@Autowired
private SecurityProperties securityProperties;
private final AntPathMatcher antPathMatcher = new AntPathMatcher();
/**
* 查询当前用户拥有的资源权限
* @param roleCodes 角色code列表,多个以','隔开
* @return
*/
public abstract List<SysMenu> findMenuByRoleCodes(String roleCodes);
public boolean hasPermission(Authentication authentication, String requestMethod, String requestURI) {
// 前端跨域OPTIONS请求预检放行 也可通过前端配置代理实现
if (HttpMethod.OPTIONS.name().equalsIgnoreCase(requestMethod)) {
return true;
}
if (!(authentication instanceof AnonymousAuthenticationToken)) {
//判断是否开启url权限验证
if (!securityProperties.getAuth().getUrlPermission().getEnable()) {
return true;
}
//超级管理员admin不需认证
String username = AuthUtils.getUsername(authentication);
if (CommonConstant.ADMIN_USER_NAME.equals(username)) {
return true;
}
OAuth2Authentication auth2Authentication = (OAuth2Authentication)authentication;
//判断应用黑白名单
if (!isNeedAuth(auth2Authentication.getOAuth2Request().getClientId())) {
return true;
}
//判断不进行url权限认证的api,所有已登录用户都能访问的url
for (String path : securityProperties.getAuth().getUrlPermission().getIgnoreUrls()) {
if (antPathMatcher.match(path, requestURI)) {
return true;
}
}
List<SimpleGrantedAuthority> grantedAuthorityList = (List<SimpleGrantedAuthority>) authentication.getAuthorities();
if (CollectionUtil.isEmpty(grantedAuthorityList)) {
log.warn("角色列表为空:{}", authentication.getPrincipal());
return false;
}
//保存租户信息
String clientId = auth2Authentication.getOAuth2Request().getClientId();
TenantContextHolder.setTenant(clientId);
String roleCodes = grantedAuthorityList.stream().map(SimpleGrantedAuthority::getAuthority).collect(Collectors.joining(", "));
List<SysMenu> menuList = findMenuByRoleCodes(roleCodes);
for (SysMenu menu : menuList) {
if (StringUtils.isNotEmpty(menu.getUrl()) && antPathMatcher.match(menu.getUrl(), requestURI)) {
if (StrUtil.isNotEmpty(menu.getPathMethod())) {
return requestMethod.equalsIgnoreCase(menu.getPathMethod());
} else {
return true;
}
}
}
}
return false;
}
/**
* 判断应用是否满足白名单和黑名单的过滤逻辑
* @param clientId 应用id
* @return true(需要认证),false(不需要认证)
*/
private boolean isNeedAuth(String clientId) {
boolean result = true;
//白名单
List<String> includeClientIds = securityProperties.getAuth().getUrlPermission().getIncludeClientIds();
//黑名单
List<String> exclusiveClientIds = securityProperties.getAuth().getUrlPermission().getExclusiveClientIds();
if (includeClientIds.size() > 0) {
result = includeClientIds.contains(clientId);
} else if(exclusiveClientIds.size() > 0) {
result = !exclusiveClientIds.contains(clientId);
}
return result;
}
}
package com.central.oauth2.common.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.central.common.constant.CommonConstant;
import com.central.common.constant.SecurityConstants;
import com.central.common.context.TenantContextHolder;
import com.central.common.model.LoginAppUser;
import com.central.common.model.SysMenu;
import com.central.oauth2.common.properties.SecurityProperties;
import com.central.oauth2.common.util.AuthUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal;
import org.springframework.util.AntPathMatcher;
import java.security.Principal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 请求权限判断service
*
* @author zlt
* @date 2018/10/28
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
public abstract class DefaultPermissionServiceImpl {
@Autowired
private SecurityProperties securityProperties;
private final AntPathMatcher antPathMatcher = new AntPathMatcher();
/**
* 查询当前用户拥有的资源权限
* @param roleCodes 角色code列表,多个以','隔开
* @return
*/
public abstract List<SysMenu> findMenuByRoleCodes(String roleCodes);
public boolean hasPermission(Authentication authentication, String requestMethod, String requestURI) {
// 前端跨域OPTIONS请求预检放行 也可通过前端配置代理实现
if (HttpMethod.OPTIONS.name().equalsIgnoreCase(requestMethod)) {
return true;
}
if (!(authentication instanceof AnonymousAuthenticationToken)) {
//判断是否开启url权限验证
if (!securityProperties.getAuth().getUrlPermission().getEnable()) {
return true;
}
OAuth2IntrospectionAuthenticatedPrincipal authenticatedPrincipal = (OAuth2IntrospectionAuthenticatedPrincipal)authentication.getPrincipal();
//超级管理员admin不需认证
String username = authenticatedPrincipal.getName();
if (CommonConstant.ADMIN_USER_NAME.equals(username)) {
return true;
}
Map<String, Object> claims = authenticatedPrincipal.getAttributes();
String clientId = (String)claims.get(SecurityConstants.CLIENT_ID);
//判断应用黑白名单
if (!isNeedAuth(clientId)) {
return true;
}
//判断不进行url权限认证的api,所有已登录用户都能访问的url
for (String path : securityProperties.getAuth().getUrlPermission().getIgnoreUrls()) {
if (antPathMatcher.match(path, requestURI)) {
return true;
}
}
Collection<SimpleGrantedAuthority> grantedAuthorityList = (Collection<SimpleGrantedAuthority>) authentication.getAuthorities();
if (CollectionUtil.isEmpty(grantedAuthorityList)) {
log.warn("角色列表为空:{}", authentication.getPrincipal());
return false;
}
//保存租户信息
TenantContextHolder.setTenant(clientId);
String roleCodes = grantedAuthorityList.stream().map(SimpleGrantedAuthority::getAuthority).collect(Collectors.joining(", "));
List<SysMenu> menuList = findMenuByRoleCodes(roleCodes);
for (SysMenu menu : menuList) {
if (StringUtils.isNotEmpty(menu.getUrl()) && antPathMatcher.match(menu.getUrl(), requestURI)) {
if (StrUtil.isNotEmpty(menu.getPathMethod())) {
return requestMethod.equalsIgnoreCase(menu.getPathMethod());
} else {
return true;
}
}
}
}
return false;
}
/**
* 判断应用是否满足白名单和黑名单的过滤逻辑
* @param clientId 应用id
* @return true(需要认证),false(不需要认证)
*/
private boolean isNeedAuth(String clientId) {
boolean result = true;
//白名单
List<String> includeClientIds = securityProperties.getAuth().getUrlPermission().getIncludeClientIds();
//黑名单
List<String> exclusiveClientIds = securityProperties.getAuth().getUrlPermission().getExclusiveClientIds();
if (includeClientIds.size() > 0) {
result = includeClientIds.contains(clientId);
} else if(exclusiveClientIds.size() > 0) {
result = !exclusiveClientIds.contains(clientId);
}
return result;
}
}
@@ -0,0 +1,365 @@
package com.central.oauth2.common.service.impl;
import com.central.common.constant.SecurityConstants;
import com.central.oauth2.common.pojo.ClientDto;
import com.central.oauth2.common.properties.SecurityProperties;
import com.central.oauth2.common.token.CustomAccessToken;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.ExpiredObjectListener;
import org.redisson.api.RBucket;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;
import org.redisson.codec.SerializationCodec;
import org.springframework.lang.Nullable;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationCode;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.util.Assert;
import java.lang.reflect.Field;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
/**
* 实现 Redis 存储 OAuth2Authorization 对象
* 1. 自动续签token(可配置是否开启)
* 2. 增加 client_id_to_access 和 uname_to_access 两个集合,用于查看在线用户
* 3. 增加过期监听,删除 client_id_to_access 和 uname_to_access 集合的值
*
* @author: zlt
* @date: 2023/11/9
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@RequiredArgsConstructor
public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationService {
private final static SerializationCodec AUTH_CODEC = new SerializationCodec();
private final static Long STATE_TIMEOUT_MINUTES = 10L;
private static final String AUTHORIZATION = "token";
private final SecurityProperties securityProperties;
private final RedissonClient redisson;
private final ExpiredObjectListener expiredObjectListener = new ExpiredObjectListener() {
private final static String KEY_SPLIT = "::";
/**
* redis 失效监听,删除集合里的值
* 在 redis.conf 文件中,确保以下设置是启用的:notify-keyspace-events Ex
* 监听的key格式为:token::access_token::${clientId}::${username}::${access_token}
* 例如:token::access_token::webApp::admin::q7ySjsjZoinAx0zUJADqV9P1VmCwYmQDdemwOuhDHjNXVmkzkvquMk_vUBX_Yz40JModOhUwixu-ICH5hti50-KXngBgkn_V1pxu-PZ1YGNkBIDXneE0z4WYx6uFIVHS
*/
@Override
public void onExpired(String name) {
String[] keyArr = name.split(KEY_SPLIT);
if (keyArr.length == 5) {
String clientId = keyArr[2];
String username = keyArr[3];
String accessToken = keyArr[4];
redisListDelete(getClientIdListKey(clientId), accessToken);
redisListDelete(getUnameListKey(clientId, username), accessToken);
}
}
};
@Override
public void save(OAuth2Authorization authorization) {
if (isState(authorization)) {
String token = authorization.getAttribute("state");
this.redisBucketSet(OAuth2ParameterNames.STATE, token, authorization, Duration.ofMinutes(STATE_TIMEOUT_MINUTES));
}
if (isCode(authorization)) {
OAuth2AuthorizationCode authorizationCode = authorization.getToken(OAuth2AuthorizationCode.class).getToken();
Duration duration = this.getExpireSeconds(authorizationCode);
this.redisBucketSet(OAuth2ParameterNames.CODE, authorizationCode.getTokenValue(), authorization, duration);
}
if (isRefreshToken(authorization)) {
OAuth2RefreshToken refreshToken = authorization.getRefreshToken().getToken();
Duration duration = this.getExpireSeconds(refreshToken);
this.redisBucketSet(OAuth2ParameterNames.REFRESH_TOKEN, refreshToken.getTokenValue(), authorization, duration);
}
if (isAccessToken(authorization)) {
Duration duration = this.saveAccessToken(authorization);
OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
// 应用id集合
this.redisListAdd(this.getClientIdListKey(authorization), accessToken.getTokenValue(), duration);
// 应用id + 登录名 集合
this.redisListAdd(this.getUnameListKey(authorization), accessToken.getTokenValue(), duration);
}
}
private Duration saveAccessToken(OAuth2Authorization authorization) {
return this.saveAccessToken(authorization, false);
}
private Duration saveAccessToken(OAuth2Authorization authorization, boolean isRenew) {
OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
Duration duration = this.getExpireSeconds(accessToken);
this.redisBucketSet(OAuth2ParameterNames.ACCESS_TOKEN, accessToken.getTokenValue(), authorization, duration);
RBucket<Integer> listenKeyBucket = redisson.getBucket(buildListenerKey(
OAuth2ParameterNames.ACCESS_TOKEN, authorization.getRegisteredClientId()
, authorization.getPrincipalName(), accessToken.getTokenValue()));
if (!isRenew) {
listenKeyBucket.set(1, duration);
listenKeyBucket.addListener(expiredObjectListener);
} else {
listenKeyBucket.expire(duration);
}
return duration;
}
@Override
public void remove(OAuth2Authorization authorization) {
Assert.notNull(authorization, "authorization cannot be null");
List<String> keys = new ArrayList<>();
if (isState(authorization)) {
String token = authorization.getAttribute("state");
keys.add(buildKey(OAuth2ParameterNames.STATE, token));
}
if (isCode(authorization)) {
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization
.getToken(OAuth2AuthorizationCode.class);
OAuth2AuthorizationCode authorizationCodeToken = authorizationCode.getToken();
keys.add(buildKey(OAuth2ParameterNames.CODE, authorizationCodeToken.getTokenValue()));
}
if (isRefreshToken(authorization)) {
OAuth2RefreshToken refreshToken = authorization.getRefreshToken().getToken();
keys.add(buildKey(OAuth2ParameterNames.REFRESH_TOKEN, refreshToken.getTokenValue()));
}
if (isAccessToken(authorization)) {
OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
keys.add(buildKey(OAuth2ParameterNames.ACCESS_TOKEN, accessToken.getTokenValue()));
}
redisson.getKeys().delete(keys.toArray(String[]::new));
this.removeList(authorization);
}
@Override
@Nullable
public OAuth2Authorization findById(String id) {
return this.findByToken(id, OAuth2TokenType.ACCESS_TOKEN);
}
@Override
@Nullable
public OAuth2Authorization findByToken(String token, @Nullable OAuth2TokenType tokenType) {
Assert.hasText(token, "token cannot be empty");
if (tokenType == null) {
tokenType = OAuth2TokenType.ACCESS_TOKEN;
}
OAuth2Authorization authorization = this.redisBucketGet(tokenType.getValue(), token);
boolean isRenew = securityProperties.getAuth().getRenew().getEnable();
if (isRenew && tokenType.equals(OAuth2TokenType.ACCESS_TOKEN) && authorization != null) {
this.renew(authorization);
}
return authorization;
}
public void remove(String accessToken) {
OAuth2Authorization oAuth2Authorization = this.findById(accessToken);
this.remove(oAuth2Authorization);
}
public List<String> findTokensByClientId(String clientId) {
RList<String> rList = redisson.getList(this.getClientIdListKey(clientId));
return rList.readAll();
}
public List<String> findTokensByClientIdAndUserName(String clientId, String username) {
RList<String> rList = redisson.getList(this.getUnameListKey(clientId, username));
return rList.readAll();
}
private String buildKey(String type, String id) {
return String.format("%s::%s::%s", AUTHORIZATION, type, id);
}
private String buildListenerKey(String type, String clientId, String username, String tokenValue) {
return String.format("%s::%s::%s::%s::%s", AUTHORIZATION, type, clientId, username, tokenValue);
}
private static boolean isState(OAuth2Authorization authorization) {
return Objects.nonNull(authorization.getAttribute("state"));
}
private static boolean isCode(OAuth2Authorization authorization) {
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization
.getToken(OAuth2AuthorizationCode.class);
return Objects.nonNull(authorizationCode);
}
private static boolean isRefreshToken(OAuth2Authorization authorization) {
return Objects.nonNull(authorization.getRefreshToken());
}
private static boolean isAccessToken(OAuth2Authorization authorization) {
return Objects.nonNull(authorization.getAccessToken());
}
/**
* 续签 access_token
*/
private void renew(OAuth2Authorization authorization) {
// 判断当前应用是否需要自动续签
if (checkRenewClientId(authorization.getRegisteredClientId())) {
// 获取过期时长
long validitySeconds = getAccessTokenValiditySeconds(authorization.getRegisteredClientId());
if (validitySeconds > 0) {
OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
long expiresIn = ChronoUnit.SECONDS.between(Instant.now(), accessToken.getExpiresAt());
double expiresRatio = expiresIn / (double) validitySeconds;
// 判断是否需要续签,当前剩余时间小于过期时长的50%则续签
if (expiresRatio <= securityProperties.getAuth().getRenew().getTimeRatio()) {
// 更新AccessToken过期时间
updateAccessTokenExpiresAt(authorization, validitySeconds);
}
}
}
}
/**
* 判断应用自动续签是否满足白名单和黑名单的过滤逻辑
*
* @param clientId 应用id
* @return 是否满足
*/
private boolean checkRenewClientId(String clientId) {
boolean result = true;
//白名单
List<String> includeClientIds = securityProperties.getAuth().getRenew().getIncludeClientIds();
//黑名单
List<String> exclusiveClientIds = securityProperties.getAuth().getRenew().getExclusiveClientIds();
if (includeClientIds.size() > 0) {
result = includeClientIds.contains(clientId);
} else if (exclusiveClientIds.size() > 0) {
result = !exclusiveClientIds.contains(clientId);
}
return result;
}
/**
* 获取token的总有效时长
*
* @param clientId 应用id
*/
private long getAccessTokenValiditySeconds(String clientId) {
ClientDto clientDetails = (ClientDto)redisson.getBucket(clientRedisKey(clientId)).get();
if (clientDetails != null) {
return clientDetails.getAccessTokenValiditySeconds();
}
//返回默认值
return SecurityConstants.ACCESS_TOKEN_VALIDITY_SECONDS;
}
/**
* 更新 access_token 的过期时间
*/
@SuppressWarnings("unchecked")
private void updateAccessTokenExpiresAt(OAuth2Authorization authorization, long validitySeconds) {
try {
Class<?> authClazz = authorization.getClass();
Field tokensField = authClazz.getDeclaredField("tokens");
tokensField.setAccessible(true);
Map<Class<? extends OAuth2Token>, OAuth2Authorization.Token<?>> tokens = (Map<Class<? extends OAuth2Token>, OAuth2Authorization.Token<?>>) tokensField.get(authorization);
OAuth2Authorization.Token<OAuth2AccessToken> newToken = this.genateNewAccessToken(authorization.getAccessToken(), validitySeconds);
Map<Class<? extends OAuth2Token>, OAuth2Authorization.Token<?>> newTokens = new HashMap<>(tokens);
newTokens.put(OAuth2AccessToken.class, newToken);
tokensField.set(authorization, Collections.unmodifiableMap(newTokens));
this.saveAccessToken(authorization, true);
// 更新集合中的过期时间
this.updateListExpiresAt(this.getClientIdListKey(authorization), Duration.ofSeconds(validitySeconds));
this.updateListExpiresAt(this.getUnameListKey(authorization), Duration.ofSeconds(validitySeconds));
} catch (Exception e) {
log.error("updateAccessTokenExpiresAt-error", e);
throw new RuntimeException(e);
}
}
private void removeList(OAuth2Authorization authorization) {
this.redisListDelete(this.getClientIdListKey(authorization), authorization.getId());
this.redisListDelete(this.getUnameListKey(authorization), authorization.getId());
}
private void updateListExpiresAt(String key, Duration duration) {
redisson.getList(key).expire(duration);
}
private OAuth2Authorization.Token<OAuth2AccessToken> genateNewAccessToken(OAuth2Authorization.Token<OAuth2AccessToken> oldToken, long validitySeconds) {
Instant issuedAt = Instant.now();
Instant expiresAt = issuedAt.plus(Duration.ofSeconds(validitySeconds));
OAuth2AccessToken oldAccessToken = oldToken.getToken();
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
oldAccessToken.getTokenValue(), issuedAt,
expiresAt, oldAccessToken.getScopes());
return new CustomAccessToken(accessToken, oldToken.getMetadata());
}
private Duration getExpireSeconds(OAuth2Token oAuth2Token) {
return Duration.ofSeconds(
ChronoUnit.SECONDS.between(oAuth2Token.getIssuedAt(), oAuth2Token.getExpiresAt()));
}
private RBucket<OAuth2Authorization> redisBucketSet(String type, String id, OAuth2Authorization value, Duration duration) {
RBucket<OAuth2Authorization> rBucket = redisson.getBucket(buildKey(type, id), AUTH_CODEC);
rBucket.set(value, duration);
return rBucket;
}
private String getClientIdListKey(OAuth2Authorization authorization) {
return this.getClientIdListKey(authorization.getRegisteredClientId());
}
private String getClientIdListKey(String clientId) {
return buildKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS, clientId);
}
private String getUnameListKey(OAuth2Authorization authorization) {
return this.getUnameListKey(authorization.getRegisteredClientId(), authorization.getPrincipalName());
}
private String getUnameListKey(String clientId, String username) {
return buildKey(SecurityConstants.REDIS_UNAME_TO_ACCESS, clientId + "::" + username);
}
private OAuth2Authorization redisBucketGet(String type, String id) {
return (OAuth2Authorization)redisson.getBucket(buildKey(type, id), AUTH_CODEC).get();
}
private RList<String> redisListAdd(String key, String value, Duration duration) {
RList<String> rList = redisson.getList(key);
rList.add(value);
rList.expire(duration);
return rList;
}
private RList<String> redisListDelete(String key, String value) {
RList<String> rList = redisson.getList(key);
rList.remove(value);
return rList;
}
private String clientRedisKey(String clientId) {
return SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId;
}
}
@@ -1,28 +0,0 @@
package com.central.oauth2.common.store;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import javax.sql.DataSource;
/**
* 认证服务器使用数据库存取令牌
*
* @author zlt
* @date 2018/7/24 16:23
*/
@Configuration
@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "db")
public class AuthDbTokenStore {
@Autowired
private DataSource dataSource;
@Bean
public TokenStore tokenStore(){
return new JdbcTokenStore(dataSource);
}
}
@@ -1,55 +0,0 @@
package com.central.oauth2.common.store;
import com.central.common.model.SysUser;
import com.central.oauth2.common.converter.CustomUserAuthenticationConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import javax.annotation.Resource;
import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;
/**
* 认证服务器使用 JWT RSA 非对称加密令牌
*
* @author zlt
* @date 2018/7/24 16:21
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Configuration
@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "authJwt")
public class AuthJwtTokenStore {
@Resource
private KeyProperties keyProperties;
@Bean
public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
return new JwtTokenStore(jwtAccessTokenConverter);
}
@Bean
@Order(2)
public JwtAccessTokenConverter jwtAccessTokenConverter() {
final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
KeyPair keyPair = new KeyStoreKeyFactory
(keyProperties.getKeyStore().getLocation(), keyProperties.getKeyStore().getSecret().toCharArray())
.getKeyPair(keyProperties.getKeyStore().getAlias());
converter.setKeyPair(keyPair);
DefaultAccessTokenConverter tokenConverter = (DefaultAccessTokenConverter)converter.getAccessTokenConverter();
tokenConverter.setUserTokenConverter(new CustomUserAuthenticationConverter());
return converter;
}
}
@@ -1,29 +0,0 @@
package com.central.oauth2.common.store;
import com.central.oauth2.common.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.security.oauth2.provider.token.TokenStore;
/**
* 认证服务器使用Redis存取令牌
* 注意: 需要配置redis参数
*
* @author zlt
* @date 2018/7/25 9:36
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Configuration
@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "redis", matchIfMissing = true)
public class AuthRedisTokenStore {
@Bean
public TokenStore tokenStore(RedisConnectionFactory connectionFactory, SecurityProperties securityProperties, RedisSerializer<Object> redisValueSerializer) {
return new CustomRedisTokenStore(connectionFactory, securityProperties, redisValueSerializer);
}
}
@@ -1,543 +0,0 @@
package com.central.oauth2.common.store;
import com.central.common.constant.SecurityConstants;
import com.central.oauth2.common.properties.SecurityProperties;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.JdkSerializationStrategy;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStoreSerializationStrategy;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* 优化自Spring Security的RedisTokenStore
* 1. 支持redis所有集群模式包括cluster模式
* 2. 使用pipeline减少连接次数,提升性能
* 3. 自动续签token(可配置是否开启)
*
* @author zlt
* @date 2019/7/7
*/
public class CustomRedisTokenStore implements TokenStore {
private static final String ACCESS = "access:";
private static final String ACCESS_BAK = "access_bak:";
private static final String AUTH_TO_ACCESS = "auth_to_access:";
private static final String REFRESH_AUTH = "refresh_auth:";
private static final String ACCESS_TO_REFRESH = "access_to_refresh:";
private static final String REFRESH = "refresh:";
private static final String REFRESH_TO_ACCESS = "refresh_to_access:";
private static final boolean springDataRedis_2_0 = ClassUtils.isPresent(
"org.springframework.data.redis.connection.RedisStandaloneConfiguration",
RedisTokenStore.class.getClassLoader());
private final RedisConnectionFactory connectionFactory;
private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator();
private RedisTokenStoreSerializationStrategy serializationStrategy = new JdkSerializationStrategy();
private String prefix = "";
private Method redisConnectionSet_2_0;
/**
* 认证配置
*/
private SecurityProperties securityProperties;
/**
* 业务redis的value序列化
*/
private RedisSerializer<Object> redisValueSerializer;
public CustomRedisTokenStore(RedisConnectionFactory connectionFactory, SecurityProperties securityProperties, RedisSerializer<Object> redisValueSerializer) {
this.connectionFactory = connectionFactory;
this.securityProperties = securityProperties;
this.redisValueSerializer = redisValueSerializer;
if (springDataRedis_2_0) {
this.loadRedisConnectionMethods_2_0();
}
}
public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) {
this.authenticationKeyGenerator = authenticationKeyGenerator;
}
public void setSerializationStrategy(RedisTokenStoreSerializationStrategy serializationStrategy) {
this.serializationStrategy = serializationStrategy;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
private void loadRedisConnectionMethods_2_0() {
this.redisConnectionSet_2_0 = ReflectionUtils.findMethod(
RedisConnection.class, "set", byte[].class, byte[].class);
}
private RedisConnection getConnection() {
return connectionFactory.getConnection();
}
private byte[] serialize(Object object) {
return serializationStrategy.serialize(object);
}
private byte[] serializeKey(String object) {
return serialize(prefix + object);
}
private OAuth2AccessToken deserializeAccessToken(byte[] bytes) {
return serializationStrategy.deserialize(bytes, OAuth2AccessToken.class);
}
private OAuth2Authentication deserializeAuthentication(byte[] bytes) {
return serializationStrategy.deserialize(bytes, OAuth2Authentication.class);
}
private OAuth2RefreshToken deserializeRefreshToken(byte[] bytes) {
return serializationStrategy.deserialize(bytes, OAuth2RefreshToken.class);
}
private ClientDetails deserializeClientDetails(byte[] bytes) {
return (ClientDetails) redisValueSerializer.deserialize(bytes);
}
private byte[] serialize(String string) {
return serializationStrategy.serialize(string);
}
private String deserializeString(byte[] bytes) {
return serializationStrategy.deserializeString(bytes);
}
@Override
public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
String key = authenticationKeyGenerator.extractKey(authentication);
byte[] serializedKey = serializeKey(AUTH_TO_ACCESS + key);
byte[] bytes;
RedisConnection conn = getConnection();
try {
bytes = conn.get(serializedKey);
} finally {
conn.close();
}
OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
if (accessToken != null) {
OAuth2Authentication storedAuthentication = readAuthentication(accessToken.getValue());
if ((storedAuthentication == null || !key.equals(authenticationKeyGenerator.extractKey(storedAuthentication)))) {
// Keep the stores consistent (maybe the same user is
// represented by this authentication but the details have
// changed)
storeAccessToken(accessToken, authentication);
}
}
return accessToken;
}
@Override
public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
OAuth2Authentication auth2Authentication = readAuthentication(token.getValue());
//是否开启token续签
boolean isRenew = securityProperties.getAuth().getRenew().getEnable();
if (isRenew && auth2Authentication != null) {
OAuth2Request clientAuth = auth2Authentication.getOAuth2Request();
//判断当前应用是否需要自动续签
if (checkRenewClientId(clientAuth.getClientId())) {
//获取过期时长
int validitySeconds = getAccessTokenValiditySeconds(clientAuth.getClientId());
if (validitySeconds > 0) {
double expiresRatio = token.getExpiresIn() / (double) validitySeconds;
//判断是否需要续签,当前剩余时间小于过期时长的50%则续签
if (expiresRatio <= securityProperties.getAuth().getRenew().getTimeRatio()) {
//更新AccessToken过期时间
DefaultOAuth2AccessToken oAuth2AccessToken = (DefaultOAuth2AccessToken) token;
oAuth2AccessToken.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
storeAccessToken(oAuth2AccessToken, auth2Authentication, true);
}
}
}
}
return auth2Authentication;
}
/**
* 判断应用自动续签是否满足白名单和黑名单的过滤逻辑
*
* @param clientId 应用id
* @return 是否满足
*/
private boolean checkRenewClientId(String clientId) {
boolean result = true;
//白名单
List<String> includeClientIds = securityProperties.getAuth().getRenew().getIncludeClientIds();
//黑名单
List<String> exclusiveClientIds = securityProperties.getAuth().getRenew().getExclusiveClientIds();
if (includeClientIds.size() > 0) {
result = includeClientIds.contains(clientId);
} else if (exclusiveClientIds.size() > 0) {
result = !exclusiveClientIds.contains(clientId);
}
return result;
}
/**
* 获取token的总有效时长
*
* @param clientId 应用id
*/
private int getAccessTokenValiditySeconds(String clientId) {
RedisConnection conn = getConnection();
byte[] bytes;
try {
bytes = conn.get(serializeKey(SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId));
} finally {
conn.close();
}
if (bytes != null) {
ClientDetails clientDetails = deserializeClientDetails(bytes);
if (clientDetails.getAccessTokenValiditySeconds() != null) {
return clientDetails.getAccessTokenValiditySeconds();
}
}
//返回默认值
return SecurityConstants.ACCESS_TOKEN_VALIDITY_SECONDS;
}
@Override
public OAuth2Authentication readAuthentication(String token) {
byte[] bytes;
RedisConnection conn = getConnection();
try {
bytes = conn.get(serializeKey(SecurityConstants.REDIS_TOKEN_AUTH + token));
} finally {
conn.close();
}
return deserializeAuthentication(bytes);
}
@Override
public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) {
return readAuthenticationForRefreshToken(token.getValue());
}
public OAuth2Authentication readAuthenticationForRefreshToken(String token) {
RedisConnection conn = getConnection();
try {
byte[] bytes = conn.get(serializeKey(REFRESH_AUTH + token));
return deserializeAuthentication(bytes);
} finally {
conn.close();
}
}
@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
storeAccessToken(token, authentication, false);
}
/**
* 存储token
*
* @param isRenew 是否续签
*/
private void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication, boolean isRenew) {
byte[] serializedAccessToken = serialize(token);
byte[] serializedAuth = serialize(authentication);
byte[] accessKey = serializeKey(ACCESS + token.getValue());
byte[] accessBakKey = serializeKey(ACCESS_BAK + token.getValue());
byte[] authKey = serializeKey(SecurityConstants.REDIS_TOKEN_AUTH + token.getValue());
byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication));
byte[] approvalKey = serializeKey(SecurityConstants.REDIS_UNAME_TO_ACCESS + getApprovalKey(authentication));
byte[] clientId = serializeKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());
RedisConnection conn = getConnection();
try {
byte[] oldAccessToken = conn.get(accessKey);
//如果token已存在,并且不是续签的话直接返回
if (!isRenew && oldAccessToken != null) {
return;
}
conn.openPipeline();
if (springDataRedis_2_0) {
try {
this.redisConnectionSet_2_0.invoke(conn, accessKey, serializedAccessToken);
this.redisConnectionSet_2_0.invoke(conn, accessBakKey, serializedAccessToken);
this.redisConnectionSet_2_0.invoke(conn, authKey, serializedAuth);
this.redisConnectionSet_2_0.invoke(conn, authToAccessKey, serializedAccessToken);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
} else {
conn.set(accessKey, serializedAccessToken);
conn.set(accessBakKey, serializedAccessToken);
conn.set(authKey, serializedAuth);
conn.set(authToAccessKey, serializedAccessToken);
}
//如果是续签token,需要先删除集合里旧的值
if (oldAccessToken != null) {
if (!authentication.isClientOnly()) {
conn.lRem(approvalKey, 1, oldAccessToken);
}
conn.lRem(clientId, 1, oldAccessToken);
}
if (!authentication.isClientOnly()) {
conn.rPush(approvalKey, serializedAccessToken);
}
conn.rPush(clientId, serializedAccessToken);
if (token.getExpiration() != null) {
int seconds = token.getExpiresIn();
conn.expire(accessKey, seconds);
conn.expire(accessBakKey, seconds + 60);
conn.expire(authKey, seconds);
conn.expire(authToAccessKey, seconds);
conn.expire(clientId, seconds);
conn.expire(approvalKey, seconds);
}
OAuth2RefreshToken refreshToken = token.getRefreshToken();
if (refreshToken != null && refreshToken.getValue() != null) {
byte[] refresh = serialize(token.getRefreshToken().getValue());
byte[] auth = serialize(token.getValue());
byte[] refreshToAccessKey = serializeKey(REFRESH_TO_ACCESS + token.getRefreshToken().getValue());
byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + token.getValue());
if (springDataRedis_2_0) {
try {
this.redisConnectionSet_2_0.invoke(conn, refreshToAccessKey, auth);
this.redisConnectionSet_2_0.invoke(conn, accessToRefreshKey, refresh);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
} else {
conn.set(refreshToAccessKey, auth);
conn.set(accessToRefreshKey, refresh);
}
expireRefreshToken(refreshToken, conn, refreshToAccessKey, accessToRefreshKey);
}
conn.closePipeline();
} finally {
conn.close();
}
}
private static String getApprovalKey(OAuth2Authentication authentication) {
String userName = authentication.getUserAuthentication() == null ? ""
: authentication.getUserAuthentication().getName();
return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName);
}
private static String getApprovalKey(String clientId, String userName) {
return clientId + (userName == null ? "" : ":" + userName);
}
@Override
public void removeAccessToken(OAuth2AccessToken accessToken) {
removeAccessToken(accessToken.getValue());
}
@Override
public OAuth2AccessToken readAccessToken(String tokenValue) {
byte[] key = serializeKey(ACCESS + tokenValue);
byte[] bytes;
RedisConnection conn = getConnection();
try {
bytes = conn.get(key);
} finally {
conn.close();
}
return deserializeAccessToken(bytes);
}
public void removeAccessToken(String tokenValue) {
byte[] accessKey = serializeKey(ACCESS + tokenValue);
byte[] accessBakKey = serializeKey(ACCESS_BAK + tokenValue);
byte[] authKey = serializeKey(SecurityConstants.REDIS_TOKEN_AUTH + tokenValue);
byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue);
RedisConnection conn = getConnection();
try {
byte[] access = conn.get(accessKey);
byte[] auth = conn.get(authKey);
conn.openPipeline();
conn.del(accessKey);
conn.del(accessBakKey);
conn.del(accessToRefreshKey);
// Don't remove the refresh token - it's up to the caller to do that
conn.del(authKey);
conn.closePipeline();
OAuth2Authentication authentication = deserializeAuthentication(auth);
if (authentication != null) {
String key = authenticationKeyGenerator.extractKey(authentication);
byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + key);
byte[] unameKey = serializeKey(SecurityConstants.REDIS_UNAME_TO_ACCESS + getApprovalKey(authentication));
byte[] clientId = serializeKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());
conn.openPipeline();
conn.del(authToAccessKey);
conn.lRem(unameKey, 1, access);
conn.lRem(clientId, 1, access);
conn.del(serialize(ACCESS + key));
conn.closePipeline();
}
} finally {
conn.close();
}
}
@Override
public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
byte[] refreshKey = serializeKey(REFRESH + refreshToken.getValue());
byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + refreshToken.getValue());
byte[] serializedRefreshToken = serialize(refreshToken);
RedisConnection conn = getConnection();
try {
conn.openPipeline();
if (springDataRedis_2_0) {
try {
this.redisConnectionSet_2_0.invoke(conn, refreshKey, serializedRefreshToken);
this.redisConnectionSet_2_0.invoke(conn, refreshAuthKey, serialize(authentication));
} catch (Exception ex) {
throw new RuntimeException(ex);
}
} else {
conn.set(refreshKey, serializedRefreshToken);
conn.set(refreshAuthKey, serialize(authentication));
}
expireRefreshToken(refreshToken, conn, refreshKey, refreshAuthKey);
conn.closePipeline();
} finally {
conn.close();
}
}
private void expireRefreshToken(OAuth2RefreshToken refreshToken, RedisConnection conn, byte[] refreshKey, byte[] refreshAuthKey) {
if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken;
Date expiration = expiringRefreshToken.getExpiration();
if (expiration != null) {
int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L)
.intValue();
conn.expire(refreshKey, seconds);
conn.expire(refreshAuthKey, seconds);
}
}
}
@Override
public OAuth2RefreshToken readRefreshToken(String tokenValue) {
byte[] key = serializeKey(REFRESH + tokenValue);
byte[] bytes;
RedisConnection conn = getConnection();
try {
bytes = conn.get(key);
} finally {
conn.close();
}
return deserializeRefreshToken(bytes);
}
@Override
public void removeRefreshToken(OAuth2RefreshToken refreshToken) {
removeRefreshToken(refreshToken.getValue());
}
public void removeRefreshToken(String tokenValue) {
byte[] refreshKey = serializeKey(REFRESH + tokenValue);
byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + tokenValue);
byte[] refresh2AccessKey = serializeKey(REFRESH_TO_ACCESS + tokenValue);
byte[] access2RefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue);
RedisConnection conn = getConnection();
try {
conn.openPipeline();
conn.del(refreshKey);
conn.del(refreshAuthKey);
conn.del(refresh2AccessKey);
conn.del(access2RefreshKey);
conn.closePipeline();
} finally {
conn.close();
}
}
@Override
public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) {
removeAccessTokenUsingRefreshToken(refreshToken.getValue());
}
private void removeAccessTokenUsingRefreshToken(String refreshToken) {
byte[] key = serializeKey(REFRESH_TO_ACCESS + refreshToken);
RedisConnection conn = getConnection();
byte[] bytes = null;
try {
bytes = conn.get(key);
conn.del(key);
} finally {
conn.close();
}
if (bytes == null) {
return;
}
String accessToken = deserializeString(bytes);
if (accessToken != null) {
removeAccessToken(accessToken);
}
}
@Override
public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
byte[] approvalKey = serializeKey(SecurityConstants.REDIS_UNAME_TO_ACCESS + getApprovalKey(clientId, userName));
List<byte[]> byteList;
RedisConnection conn = getConnection();
try {
byteList = conn.lRange(approvalKey, 0, -1);
} finally {
conn.close();
}
return getTokenCollections(byteList);
}
@Override
public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
byte[] key = serializeKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + clientId);
List<byte[]> byteList;
RedisConnection conn = getConnection();
try {
byteList = conn.lRange(key, 0, -1);
} finally {
conn.close();
}
return getTokenCollections(byteList);
}
private Collection<OAuth2AccessToken> getTokenCollections(List<byte[]> byteList) {
if (byteList == null || byteList.size() == 0) {
return Collections.emptySet();
}
List<OAuth2AccessToken> accessTokens = new ArrayList<>(byteList.size());
for (byte[] bytes : byteList) {
OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
accessTokens.add(accessToken);
}
return Collections.unmodifiableCollection(accessTokens);
}
}
@@ -1,89 +0,0 @@
package com.central.oauth2.common.store;
import cn.hutool.core.util.StrUtil;
import com.central.common.constant.SecurityConstants;
import com.central.oauth2.common.converter.CustomUserAuthenticationConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.web.client.RestTemplate;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Base64;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 资源服务器 TokenStore 配置类,使用 JWT RSA 非对称加密
*
* @author zlt
* @date 2018/8/20 9:25
*/
@Configuration
@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "resJwt")
public class ResJwtTokenStore {
@Autowired
private ResourceServerProperties resource;
@Bean
public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
return new JwtTokenStore(jwtAccessTokenConverter);
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setVerifierKey(getPubKey());
DefaultAccessTokenConverter tokenConverter = (DefaultAccessTokenConverter)converter.getAccessTokenConverter();
tokenConverter.setUserTokenConverter(new CustomUserAuthenticationConverter());
return converter;
}
/**
* 获取非对称加密公钥 Key
* @return 公钥 Key
*/
private String getPubKey() {
Resource res = new ClassPathResource(SecurityConstants.RSA_PUBLIC_KEY);
try (BufferedReader br = new BufferedReader(new InputStreamReader(res.getInputStream()))) {
return br.lines().collect(Collectors.joining("\n"));
} catch (IOException ioe) {
return getKeyFromAuthorizationServer();
}
}
/**
* 通过访问授权服务器获取非对称加密公钥 Key
* @return 公钥 Key
*/
private String getKeyFromAuthorizationServer() {
if (StrUtil.isNotEmpty(this.resource.getJwt().getKeyUri())) {
final HttpHeaders headers = new HttpHeaders();
final String username = this.resource.getClientId();
final String password = this.resource.getClientSecret();
if (username != null && password != null) {
final byte[] token = Base64.getEncoder().encode((username + ":" + password).getBytes());
headers.add("Authorization", "Basic " + new String(token));
}
final HttpEntity<Void> request = new HttpEntity<>(headers);
final String url = this.resource.getJwt().getKeyUri();
return (String) new RestTemplate()
.exchange(url, HttpMethod.GET, request, Map.class).getBody()
.get("value");
}
return null;
}
}
@@ -0,0 +1,66 @@
package com.central.oauth2.common.token;
import lombok.Getter;
import lombok.Setter;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.server.authorization.util.SpringAuthorizationServerVersion;
import java.io.Serial;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
/**
* @author: zlt
* @date: 2023/11/15
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Getter
@Setter
public class BaseAuthenticationToken extends AbstractAuthenticationToken {
@Serial
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
private final AuthorizationGrantType grantType;
private Authentication clientPrincipal;
private Map<String, Object> additionalParameters;
private Set<String> scopes;
public BaseAuthenticationToken(AuthorizationGrantType authorizationGrantType) {
super(null);
this.grantType = authorizationGrantType;
}
public BaseAuthenticationToken(AuthorizationGrantType authorizationGrantType, Set<String> scopes
, Authentication clientPrincipal, @Nullable Map<String, Object> additionalParameters) {
super(null);
this.grantType = authorizationGrantType;
this.scopes = Collections.unmodifiableSet(scopes != null ? scopes : Collections.emptySet());
this.clientPrincipal = clientPrincipal;
this.additionalParameters = additionalParameters;
}
public BaseAuthenticationToken(Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.grantType = null;
this.clientPrincipal = null;
this.additionalParameters = null;
this.scopes = null;
}
@Override
public Object getPrincipal() {
return this.clientPrincipal;
}
@Override
public Object getCredentials() {
return "";
}
}
@@ -0,0 +1,19 @@
package com.central.oauth2.common.token;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import java.util.Map;
/**
* @author: zlt
* @date: 2023/11/20
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class CustomAccessToken extends OAuth2Authorization.Token<OAuth2AccessToken> {
public CustomAccessToken(OAuth2AccessToken token, Map metadata) {
super(token, metadata);
}
}
@@ -1,37 +0,0 @@
package com.central.oauth2.common.token;
import lombok.Getter;
import java.io.Serializable;
/**
* 表单登录的认证信息对象
*
* @author zlt
* @version 1.0
* @date 2021/7/24
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Getter
public class CustomWebAuthenticationDetails implements Serializable {
private static final long serialVersionUID = - 1;
private final String accountType;
private final String remoteAddress;
private final String sessionId;
public CustomWebAuthenticationDetails(String remoteAddress, String sessionId, String accountType) {
this.remoteAddress = remoteAddress;
this.sessionId = sessionId;
this.accountType = accountType;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString()).append("; accountType: ").append(this.getAccountType());
return sb.toString();
}
}
@@ -1,84 +1,36 @@
/**
*
*/
package com.central.oauth2.common.token;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import java.util.Collection;
/**
* @author zlt
* @author: zlt
* @date: 2023/11/10
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class MobileAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
// ~ Instance fields
// ================================================================================================
@Getter
public class MobileAuthenticationToken extends BaseAuthenticationToken {
public static final AuthorizationGrantType GRANT_TYPE = new AuthorizationGrantType("mobile_password");
private final Object principal;
private Object credentials;
private final String credentials;
// ~ Constructors
// ===================================================================================================
/**
* This constructor can be safely used by any code that wishes to create a
* <code>UsernamePasswordAuthenticationToken</code>, as the {@link #isAuthenticated()}
* will return <code>false</code>.
*
*/
public MobileAuthenticationToken(String mobile, String password) {
super(null);
super(GRANT_TYPE);
this.principal = mobile;
this.credentials = password;
setAuthenticated(false);
}
/**
* This constructor should only be used by <code>AuthenticationManager</code> or
* <code>AuthenticationProvider</code> implementations that are satisfied with
* producing a trusted (i.e. {@link #isAuthenticated()} = <code>true</code>)
* authentication token.
*
* @param principal
* @param authorities
*/
public MobileAuthenticationToken(Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
this.credentials = credentials;
super.setAuthenticated(true);
}
// ~ Methods
// ========================================================================================================
@Override
public Object getCredentials() {
return this.credentials;
}
@Override
public Object getPrincipal() {
return this.principal;
}
@Override
public void setAuthenticated(boolean isAuthenticated) {
if (isAuthenticated) {
throw new IllegalArgumentException(
"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
}
super.setAuthenticated(false);
}
@Override
public void eraseCredentials() {
super.eraseCredentials();
public MobileAuthenticationToken(UserDetails user, String password, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = user;
this.credentials = password;
}
}
@@ -1,78 +1,32 @@
package com.central.oauth2.common.token;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import java.util.Collection;
/**
* @author zlt
* @author: zlt
* @date: 2023/11/18
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class OpenIdAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
// ~ Instance fields
// ================================================================================================
@Getter
public class OpenIdAuthenticationToken extends BaseAuthenticationToken {
public static final AuthorizationGrantType GRANT_TYPE = new AuthorizationGrantType("openId");
private final Object principal;
// ~ Constructors
// ===================================================================================================
/**
* This constructor can be safely used by any code that wishes to create a
* <code>UsernamePasswordAuthenticationToken</code>, as the {@link #isAuthenticated()}
* will return <code>false</code>.
*
*/
public OpenIdAuthenticationToken(String openId) {
super(null);
super(GRANT_TYPE);
this.principal = openId;
setAuthenticated(false);
}
/**
* This constructor should only be used by <code>AuthenticationManager</code> or
* <code>AuthenticationProvider</code> implementations that are satisfied with
* producing a trusted (i.e. {@link #isAuthenticated()} = <code>true</code>)
* authentication token.
*
* @param principal
* @param authorities
*/
public OpenIdAuthenticationToken(Object principal,
Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
super.setAuthenticated(true);
}
// ~ Methods
// ========================================================================================================
@Override
public Object getCredentials() {
return null;
}
@Override
public Object getPrincipal() {
return this.principal;
}
@Override
public void setAuthenticated(boolean isAuthenticated) {
if (isAuthenticated) {
throw new IllegalArgumentException(
"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
}
super.setAuthenticated(false);
}
@Override
public void eraseCredentials() {
super.eraseCredentials();
public OpenIdAuthenticationToken(UserDetails principal, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
}
}
@@ -0,0 +1,35 @@
package com.central.oauth2.common.token;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import java.util.Collection;
/**
* @author: zlt
* @date: 2023/11/18
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Getter
public class PasswordAuthenticationToken extends BaseAuthenticationToken {
public static final AuthorizationGrantType GRANT_TYPE = new AuthorizationGrantType("password");
private final Object principal;
private final String credentials;
public PasswordAuthenticationToken(String username, String password) {
super(GRANT_TYPE);
this.principal = username;
this.credentials = password;
super.setAuthenticated(true);
}
public PasswordAuthenticationToken(UserDetails user, String password, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = user;
this.credentials = password;
}
}
@@ -0,0 +1,42 @@
package com.central.oauth2.common.token;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import java.util.Collection;
/**
* @author: zlt
* @date: 2023/11/18
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Getter
public class PasswordCodeAuthenticationToken extends BaseAuthenticationToken {
public static final AuthorizationGrantType GRANT_TYPE = new AuthorizationGrantType("password_code");
private final Object principal;
private final String credentials;
private final String deviceId;
private final String validCode;
public PasswordCodeAuthenticationToken(String username, String password, String deviceId, String validCode) {
super(GRANT_TYPE);
this.principal = username;
this.credentials = password;
this.deviceId = deviceId;
this.validCode = validCode;
super.setAuthenticated(true);
}
public PasswordCodeAuthenticationToken(UserDetails user, String password, String deviceId
, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = user;
this.credentials = password;
this.deviceId = deviceId;
this.validCode = null;
}
}
@@ -1,37 +0,0 @@
package com.central.oauth2.common.token;
import lombok.Getter;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collection;
/**
* 增加租户id,解决不同租户单点登录时角色没变化
*
* @author zlt
* @date 2020/6/10
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class TenantUsernamePasswordAuthenticationToken extends UsernamePasswordAuthenticationToken {
private static final long serialVersionUID = -5638287853803374687L;
/**
* 租户id
*/
@Getter
private final String clientId;
public TenantUsernamePasswordAuthenticationToken(Object principal, Object credentials, String clientId) {
super(principal, credentials);
this.clientId = clientId;
}
public TenantUsernamePasswordAuthenticationToken(Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities, String clientId) {
super(principal, credentials, authorities);
this.clientId = clientId;
}
}
@@ -1,24 +1,28 @@
package com.central.oauth2.common.util;
import cn.hutool.extra.spring.SpringUtil;
import com.central.common.constant.CommonConstant;
import com.central.common.constant.SecurityConstants;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.model.SysUser;
import com.central.common.utils.SpringUtil;
import com.central.oauth2.common.token.CustomWebAuthenticationDetails;
import com.central.common.model.LoginAppUser;
import com.central.common.utils.LoginUserUtils;
import com.central.oauth2.common.exception.CustomOAuth2AuthorizationException;
import com.central.oauth2.common.token.BaseAuthenticationToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionException;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 认证授权相关工具类
@@ -26,7 +30,7 @@ import java.util.*;
* @author zlt
* @date 2018/5/13
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@@ -37,6 +41,9 @@ public class AuthUtils {
private static final String BASIC_ = "Basic ";
private static final Pattern authorizationPattern = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-:._~+/]+=*)$",
Pattern.CASE_INSENSITIVE);
/**
* 获取requet(head/param)中的token
* @param request
@@ -45,7 +52,7 @@ public class AuthUtils {
public static String extractToken(HttpServletRequest request) {
String token = extractHeaderToken(request);
if (token == null) {
token = request.getParameter(OAuth2AccessToken.ACCESS_TOKEN);
token = request.getParameter(OAuth2ParameterNames.ACCESS_TOKEN);
if (token == null) {
log.debug("Token not found in request parameters. Not an OAuth2 request.");
}
@@ -58,18 +65,14 @@ public class AuthUtils {
* @param request
* @return
*/
private static String extractHeaderToken(HttpServletRequest request) {
Enumeration<String> headers = request.getHeaders(CommonConstant.TOKEN_HEADER);
while (headers.hasMoreElements()) {
String value = headers.nextElement();
if ((value.startsWith(OAuth2AccessToken.BEARER_TYPE))) {
String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim();
int commaIndex = authHeaderValue.indexOf(',');
if (commaIndex > 0) {
authHeaderValue = authHeaderValue.substring(0, commaIndex);
}
return authHeaderValue;
}
public static String extractHeaderToken(HttpServletRequest request) {
String authorization = request.getHeader(CommonConstant.TOKEN_HEADER);
if (!StringUtils.startsWithIgnoreCase(authorization, "bearer")) {
return null;
}
Matcher matcher = authorizationPattern.matcher(authorization);
if (matcher.matches()) {
return matcher.group("token");
}
return null;
}
@@ -77,35 +80,33 @@ public class AuthUtils {
/**
* 校验accessToken
*/
public static SysUser checkAccessToken(HttpServletRequest request) {
public static LoginAppUser checkAccessToken(HttpServletRequest request) {
String accessToken = extractToken(request);
return checkAccessToken(accessToken);
}
public static SysUser checkAccessToken(String accessTokenValue) {
TokenStore tokenStore = SpringUtil.getBean(TokenStore.class);
OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue);
if (accessToken == null || accessToken.getValue() == null) {
throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
} else if (accessToken.isExpired()) {
tokenStore.removeAccessToken(accessToken);
throw new InvalidTokenException("Access token expired: " + accessTokenValue);
public static LoginAppUser checkAccessToken(String accessTokenValue) {
OAuth2Authorization authorization = checkAccessTokenToAuth(accessTokenValue);
Authentication authentication = (Authentication)authorization.getAttributes().get(Principal.class.getName());
if (authentication == null) {
throw new OAuth2IntrospectionException("Invalid access token: " + accessTokenValue);
}
OAuth2Authentication result = tokenStore.readAuthentication(accessToken);
if (result == null) {
throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
}
return setContext(result);
return LoginUserUtils.setContext(authentication);
}
/**
* 用户信息赋值 context 对象
*/
public static SysUser setContext(Authentication authentication) {
SecurityContextHolder.getContext().setAuthentication(authentication);
SysUser user = getUser(authentication);
LoginUserContextHolder.setUser(user);
return user;
public static OAuth2Authorization checkAccessTokenToAuth(String accessTokenValue) {
if (accessTokenValue == null) {
throw new OAuth2IntrospectionException("Invalid access token: " + null);
}
OAuth2AuthorizationService authorizationService = SpringUtil.getBean(OAuth2AuthorizationService.class);
OAuth2Authorization authorization = authorizationService.findByToken(accessTokenValue, OAuth2TokenType.ACCESS_TOKEN);
if (authorization == null || authorization.getAccessToken() == null) {
throw new OAuth2IntrospectionException("Invalid access token: " + accessTokenValue);
} else if (authorization.getAccessToken().isExpired()) {
authorizationService.remove(authorization);
throw new OAuth2IntrospectionException("Access token expired: " + accessTokenValue);
}
return authorization;
}
/**
@@ -114,11 +115,20 @@ public class AuthUtils {
public static String[] extractClient(HttpServletRequest request) {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith(BASIC_)) {
throw new UnapprovedClientAuthenticationException("请求头中client信息为空");
throw new CustomOAuth2AuthorizationException("The client information in the request header is empty");
}
return extractHeaderClient(header);
}
public static String extractClientId(HttpServletRequest request) {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith(BASIC_)) {
throw new CustomOAuth2AuthorizationException("The client information in the request header is empty");
}
String[] clientArr = extractHeaderClient(header);
return clientArr[0];
}
/**
* 从header 请求中的clientId:clientSecret
*
@@ -130,57 +140,19 @@ public class AuthUtils {
String clientStr = new String(decoded, StandardCharsets.UTF_8);
String[] clientArr = clientStr.split(":");
if (clientArr.length != 2) {
throw new RuntimeException("Invalid basic authentication token");
throw new CustomOAuth2AuthorizationException("Invalid basic authentication token");
}
return clientArr;
}
/**
* 获取登陆的用户名
*/
public static String getUsername(Authentication authentication) {
Object principal = authentication.getPrincipal();
String username = null;
if (principal instanceof SysUser) {
username = ((SysUser) principal).getUsername();
} else if (principal instanceof String) {
username = (String) principal;
}
return username;
}
/**
* 获取登陆的用户对象
*/
public static SysUser getUser(Authentication authentication) {
SysUser user = null;
if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
Object principal = authentication.getPrincipal();
//客户端模式只返回一个clientId
if (principal instanceof SysUser) {
user = (SysUser)principal;
}
}
return user;
}
/**
* 获取登陆的帐户类型
*/
public static String getAccountType(Authentication authentication) {
String accountType = null;
if (authentication != null) {
Object details = authentication.getDetails();
if (details != null) {
if (details instanceof CustomWebAuthenticationDetails) {
CustomWebAuthenticationDetails detailsObj = (CustomWebAuthenticationDetails) details;
accountType = detailsObj.getAccountType();
} else {
Map<String, String> detailsMap = (Map<String, String>) details;
if (detailsMap != null) {
accountType = detailsMap.get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
}
}
if (authentication instanceof BaseAuthenticationToken authenticationToken) {
accountType = (String)authenticationToken.getAdditionalParameters().get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
}
}
return accountType;
@@ -1,108 +0,0 @@
package com.central.oauth2.common.util;
import com.central.common.constant.SecurityConstants;
import com.central.common.utils.JsonUtil;
import com.central.common.utils.RsaUtils;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.jwt.crypto.sign.SignatureVerifier;
import org.springframework.security.jwt.crypto.sign.Signer;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.stream.Collectors;
/**
* jwt工具类
*
* @author zlt
* @date 2019/7/21
*/
public class JwtUtils {
private static final String PUBKEY_START = "-----BEGIN PUBLIC KEY-----";
private static final String PUBKEY_END = "-----END PUBLIC KEY-----";
/**
* 通过classpath获取公钥值
*/
public static RSAPublicKey getPubKeyObj() {
Resource res = new ClassPathResource(SecurityConstants.RSA_PUBLIC_KEY);
try (BufferedReader br = new BufferedReader(new InputStreamReader(res.getInputStream()))) {
String pubKey = br.lines().collect(Collectors.joining("\n"));
pubKey = pubKey.substring(PUBKEY_START.length(), pubKey.indexOf(PUBKEY_END));
return RsaUtils.getPublicKey(pubKey);
} catch (Exception ioe) {
ioe.printStackTrace();
}
return null;
}
/**
* {"exp":1563256084,"user_name":"admin","authorities":["ADMIN"],"jti":"4ce02f54-3d1c-4461-8af1-73f0841a35df","client_id":"webApp","scope":["app"]}
* @param jwtToken token值
* @param rsaPublicKey 公钥
* @return
*/
public static JsonNode decodeAndVerify(String jwtToken, RSAPublicKey rsaPublicKey) {
SignatureVerifier rsaVerifier = new RsaVerifier(rsaPublicKey);
Jwt jwt = JwtHelper.decodeAndVerify(jwtToken, rsaVerifier);
return JsonUtil.parse(jwt.getClaims());
}
/**
* {"exp":1563256084,"user_name":"admin","authorities":["ADMIN"],"jti":"4ce02f54-3d1c-4461-8af1-73f0841a35df","client_id":"webApp","scope":["app"]}
* @param jwtToken token值
* @return
*/
public static JsonNode decodeAndVerify(String jwtToken) {
return decodeAndVerify(jwtToken, getPubKeyObj());
}
/**
* 判断jwt是否过期
* @param claims jwt内容
* @param currTime 当前时间
* @return 未过期:true,已过期:false
*/
public static boolean checkExp(JsonNode claims, long currTime) {
long exp = claims.get("exp").asLong();
if (exp < currTime) {
return false;
}
return true;
}
/**
* 判断jwt是否过期
* @param claims jwt内容
* @return 未过期:true,已过期:false
*/
public static boolean checkExp(JsonNode claims) {
return checkExp(claims, System.currentTimeMillis());
}
public static Jwt encode(CharSequence content, KeyProperties keyProperties) {
KeyPair keyPair = new KeyStoreKeyFactory(
keyProperties.getKeyStore().getLocation(),
keyProperties.getKeyStore().getSecret().toCharArray())
.getKeyPair(keyProperties.getKeyStore().getAlias());
PrivateKey privateKey = keyPair.getPrivate();
Signer rsaSigner = new RsaSigner((RSAPrivateKey) privateKey);
return JwtHelper.encode(content, rsaSigner);
}
public static String encodeStr(CharSequence content, KeyProperties keyProperties) {
return encode(content, keyProperties).getEncoded();
}
}
@@ -0,0 +1,197 @@
package com.central.oauth2.common.util;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.ResolvableType;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth2.server.authorization.InMemoryOAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.InMemoryOAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings;
import org.springframework.security.oauth2.server.authorization.token.*;
import org.springframework.util.StringUtils;
import java.util.Map;
/**
* @author: zlt
* @date: 2023/11/16
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class OAuth2ConfigurerUtils {
private OAuth2ConfigurerUtils() {
}
public static RegisteredClientRepository getRegisteredClientRepository(HttpSecurity httpSecurity) {
RegisteredClientRepository registeredClientRepository = httpSecurity.getSharedObject(RegisteredClientRepository.class);
if (registeredClientRepository == null) {
registeredClientRepository = getBean(httpSecurity, RegisteredClientRepository.class);
httpSecurity.setSharedObject(RegisteredClientRepository.class, registeredClientRepository);
}
return registeredClientRepository;
}
public static OAuth2AuthorizationService getAuthorizationService(HttpSecurity httpSecurity) {
OAuth2AuthorizationService authorizationService = httpSecurity.getSharedObject(OAuth2AuthorizationService.class);
if (authorizationService == null) {
authorizationService = getOptionalBean(httpSecurity, OAuth2AuthorizationService.class);
if (authorizationService == null) {
authorizationService = new InMemoryOAuth2AuthorizationService();
}
httpSecurity.setSharedObject(OAuth2AuthorizationService.class, authorizationService);
}
return authorizationService;
}
public static OAuth2AuthorizationConsentService getAuthorizationConsentService(HttpSecurity httpSecurity) {
OAuth2AuthorizationConsentService authorizationConsentService = httpSecurity.getSharedObject(OAuth2AuthorizationConsentService.class);
if (authorizationConsentService == null) {
authorizationConsentService = getOptionalBean(httpSecurity, OAuth2AuthorizationConsentService.class);
if (authorizationConsentService == null) {
authorizationConsentService = new InMemoryOAuth2AuthorizationConsentService();
}
httpSecurity.setSharedObject(OAuth2AuthorizationConsentService.class, authorizationConsentService);
}
return authorizationConsentService;
}
@SuppressWarnings("unchecked")
public static OAuth2TokenGenerator<? extends OAuth2Token> getTokenGenerator(HttpSecurity httpSecurity) {
OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator = httpSecurity.getSharedObject(OAuth2TokenGenerator.class);
if (tokenGenerator == null) {
tokenGenerator = getOptionalBean(httpSecurity, OAuth2TokenGenerator.class);
if (tokenGenerator == null) {
JwtGenerator jwtGenerator = getJwtGenerator(httpSecurity);
OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
OAuth2TokenCustomizer<OAuth2TokenClaimsContext> accessTokenCustomizer = getAccessTokenCustomizer(httpSecurity);
if (accessTokenCustomizer != null) {
accessTokenGenerator.setAccessTokenCustomizer(accessTokenCustomizer);
}
OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();
if (jwtGenerator != null) {
tokenGenerator = new DelegatingOAuth2TokenGenerator(
jwtGenerator, accessTokenGenerator, refreshTokenGenerator);
} else {
tokenGenerator = new DelegatingOAuth2TokenGenerator(
accessTokenGenerator, refreshTokenGenerator);
}
}
httpSecurity.setSharedObject(OAuth2TokenGenerator.class, tokenGenerator);
}
return tokenGenerator;
}
private static JwtGenerator getJwtGenerator(HttpSecurity httpSecurity) {
JwtGenerator jwtGenerator = httpSecurity.getSharedObject(JwtGenerator.class);
if (jwtGenerator == null) {
JwtEncoder jwtEncoder = getJwtEncoder(httpSecurity);
if (jwtEncoder != null) {
jwtGenerator = new JwtGenerator(jwtEncoder);
OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer = getJwtCustomizer(httpSecurity);
if (jwtCustomizer != null) {
jwtGenerator.setJwtCustomizer(jwtCustomizer);
}
httpSecurity.setSharedObject(JwtGenerator.class, jwtGenerator);
}
}
return jwtGenerator;
}
private static JwtEncoder getJwtEncoder(HttpSecurity httpSecurity) {
JwtEncoder jwtEncoder = httpSecurity.getSharedObject(JwtEncoder.class);
if (jwtEncoder == null) {
jwtEncoder = getOptionalBean(httpSecurity, JwtEncoder.class);
if (jwtEncoder == null) {
JWKSource<SecurityContext> jwkSource = getJwkSource(httpSecurity);
if (jwkSource != null) {
jwtEncoder = new NimbusJwtEncoder(jwkSource);
}
}
if (jwtEncoder != null) {
httpSecurity.setSharedObject(JwtEncoder.class, jwtEncoder);
}
}
return jwtEncoder;
}
@SuppressWarnings("unchecked")
public static JWKSource<SecurityContext> getJwkSource(HttpSecurity httpSecurity) {
JWKSource<SecurityContext> jwkSource = httpSecurity.getSharedObject(JWKSource.class);
if (jwkSource == null) {
ResolvableType type = ResolvableType.forClassWithGenerics(JWKSource.class, SecurityContext.class);
jwkSource = getOptionalBean(httpSecurity, type);
if (jwkSource != null) {
httpSecurity.setSharedObject(JWKSource.class, jwkSource);
}
}
return jwkSource;
}
private static OAuth2TokenCustomizer<JwtEncodingContext> getJwtCustomizer(HttpSecurity httpSecurity) {
ResolvableType type = ResolvableType.forClassWithGenerics(OAuth2TokenCustomizer.class, JwtEncodingContext.class);
return getOptionalBean(httpSecurity, type);
}
private static OAuth2TokenCustomizer<OAuth2TokenClaimsContext> getAccessTokenCustomizer(HttpSecurity httpSecurity) {
ResolvableType type = ResolvableType.forClassWithGenerics(OAuth2TokenCustomizer.class, OAuth2TokenClaimsContext.class);
return getOptionalBean(httpSecurity, type);
}
public static AuthorizationServerSettings getAuthorizationServerSettings(HttpSecurity httpSecurity) {
AuthorizationServerSettings authorizationServerSettings = httpSecurity.getSharedObject(AuthorizationServerSettings.class);
if (authorizationServerSettings == null) {
authorizationServerSettings = getBean(httpSecurity, AuthorizationServerSettings.class);
httpSecurity.setSharedObject(AuthorizationServerSettings.class, authorizationServerSettings);
}
return authorizationServerSettings;
}
public static <T> T getBean(HttpSecurity httpSecurity, Class<T> type) {
return httpSecurity.getSharedObject(ApplicationContext.class).getBean(type);
}
@SuppressWarnings("unchecked")
public static <T> T getBean(HttpSecurity httpSecurity, ResolvableType type) {
ApplicationContext context = httpSecurity.getSharedObject(ApplicationContext.class);
String[] names = context.getBeanNamesForType(type);
if (names.length == 1) {
return (T) context.getBean(names[0]);
}
if (names.length > 1) {
throw new NoUniqueBeanDefinitionException(type, names);
}
throw new NoSuchBeanDefinitionException(type);
}
public static <T> T getOptionalBean(HttpSecurity httpSecurity, Class<T> type) {
Map<String, T> beansMap = BeanFactoryUtils.beansOfTypeIncludingAncestors(
httpSecurity.getSharedObject(ApplicationContext.class), type);
if (beansMap.size() > 1) {
throw new NoUniqueBeanDefinitionException(type, beansMap.size(),
"Expected single matching bean of type '" + type.getName() + "' but found " +
beansMap.size() + ": " + StringUtils.collectionToCommaDelimitedString(beansMap.keySet()));
}
return (!beansMap.isEmpty() ? beansMap.values().iterator().next() : null);
}
@SuppressWarnings("unchecked")
public static <T> T getOptionalBean(HttpSecurity httpSecurity, ResolvableType type) {
ApplicationContext context = httpSecurity.getSharedObject(ApplicationContext.class);
String[] names = context.getBeanNamesForType(type);
if (names.length > 1) {
throw new NoUniqueBeanDefinitionException(type, names);
}
return names.length == 1 ? (T) context.getBean(names[0]) : null;
}
}
@@ -1,2 +0,0 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.central.oauth2.common.AuthClientAutoConfiguration
+15 -11
View File
@@ -4,7 +4,7 @@
<parent>
<groupId>com.zlt</groupId>
<artifactId>zlt-commons</artifactId>
<version>5.6.0</version>
<version>6.0.0</version>
</parent>
<artifactId>zlt-common-core</artifactId>
<description>公共通用组件</description>
@@ -14,24 +14,16 @@
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
@@ -98,5 +90,17 @@
<groupId>com.alibaba</groupId>
<artifactId>transmittable-thread-local</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
</dependencies>
</project>
@@ -1,16 +0,0 @@
package com.central.common.annotation;
import java.lang.annotation.*;
/**
* 请求的方法参数上添加该注解,则注入当前登录账号的应用id
* 例:public void test(@LoginClient String clientId) //注入webApp
*
* @author zlt
* @date 2018/7/24 16:44
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LoginClient {
}
@@ -1,21 +0,0 @@
package com.central.common.annotation;
import java.lang.annotation.*;
/**
* 请求的方法参数SysUser上添加该注解,则注入当前登录人信息
* 例1:public void test(@LoginUser SysUser user) //只有username 和 roles
* 例2:public void test(@LoginUser(isFull = true) SysUser user) //能获取SysUser对象的所有信息
*
* @author zlt
* @date 2018/7/24 16:44
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LoginUser {
/**
* 是否查询SysUser对象所有信息,true则通过rpc接口查询
*/
boolean isFull() default false;
}
@@ -23,7 +23,7 @@ public class BannerInitializer implements ApplicationContextInitializer<Configur
LogoBanner logoBanner = new LogoBanner(BannerInitializer.class, "/zltmp/logo.txt", "Welcome to zlt", 5, 6, new Color[5], true);
CustomBanner.show(logoBanner, new Description(BannerConstant.VERSION + ":", CommonConstant.PROJECT_VERSION, 0, 1)
, new Description("Github:", "https://github.com/zlt2000", 0, 1)
, new Description("Blog:", "https://zlt2000.gitee.io", 0, 1)
, new Description("Blog:", "http://zlt2000.gitee.io", 0, 1)
);
}
}
@@ -10,7 +10,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
*
* @author zlt
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class DefaultPasswordConfig {
@@ -1,39 +0,0 @@
package com.central.common.config;
import com.central.common.feign.UserService;
import com.central.common.resolver.ClientArgumentResolver;
import com.central.common.resolver.TokenArgumentResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
/**
* 默认SpringMVC拦截器
*
* @author zlt
* @date 2019/8/5
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class DefaultWebMvcConfig implements WebMvcConfigurer {
@Lazy
@Autowired
private UserService userService;
/**
* Token参数解析
*
* @param argumentResolvers 解析类
*/
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
//注入用户信息
argumentResolvers.add(new TokenArgumentResolver(userService));
//注入应用信息
argumentResolvers.add(new ClientArgumentResolver());
}
}
@@ -10,7 +10,7 @@ public interface CommonConstant {
/**
* 项目版本号(banner使用)
*/
String PROJECT_VERSION = "5.6.0";
String PROJECT_VERSION = "6.0.0";
/**
* token请求头名称
@@ -5,10 +5,12 @@ package com.central.common.constant;
*
* @author zlt
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public interface SecurityConstants {
String PROJECT_LICENSE= "http://zlt2000.gitee.io/";
/**
* 用户信息分隔符
*/
@@ -64,6 +66,10 @@ public interface SecurityConstants {
*/
String OAUTH_TOKEN_URL = "/oauth/token";
String OAUTH_CHECK_TOKEN_URL = "/oauth/check_token";
String OAUTH_JWKS_URL = "/oauth/jwks";
/**
* 默认的处理验证码的url前缀
*/
@@ -161,11 +167,11 @@ public interface SecurityConstants {
/**
* redis中应用对应的token集合的key
*/
String REDIS_CLIENT_ID_TO_ACCESS = "client_id_to_access:";
String REDIS_CLIENT_ID_TO_ACCESS = "client_id_to_access";
/**
* redis中用户名对应的token集合的key
*/
String REDIS_UNAME_TO_ACCESS = "uname_to_access:";
String REDIS_UNAME_TO_ACCESS = "uname_to_access";
/**
* rsa公钥
*/
@@ -189,4 +195,32 @@ public interface SecurityConstants {
* 账号类型参数名
*/
String ACCOUNT_TYPE_PARAM_NAME = "account_type";
/**
* 协议字段
*/
String LICENSE_NAME = "license";
/**
* 客户端ID
*/
String CLIENT_ID = "client_id";
/**
* 用户信息
*/
String DETAILS_USER = "user_info";
/**
* 用户ID
*/
String DETAILS_USER_ID = "user_id";
/**
* 用户名
*/
String USERNAME = "username";
/**
* jwk set缓存前缀
*/
String AUTHORIZATION_JWS_PREFIX_KEY = "authorization_jws";
}
@@ -1,7 +1,7 @@
package com.central.common.context;
import com.alibaba.ttl.TransmittableThreadLocal;
import com.central.common.model.SysUser;
import com.central.common.model.LoginAppUser;
/**
* 登录用户holder
@@ -9,17 +9,17 @@ import com.central.common.model.SysUser;
* @author zlt
* @date 2022/6/26
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class LoginUserContextHolder {
private static final ThreadLocal<SysUser> CONTEXT = new TransmittableThreadLocal<>();
private static final ThreadLocal<LoginAppUser> CONTEXT = new TransmittableThreadLocal<>();
public static void setUser(SysUser user) {
public static void setUser(LoginAppUser user) {
CONTEXT.set(user);
}
public static SysUser getUser() {
public static LoginAppUser getUser() {
return CONTEXT.get();
}
@@ -6,11 +6,11 @@ import cn.hutool.core.util.StrUtil;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.enums.DataScope;
import com.central.common.feign.UserService;
import com.central.common.model.LoginAppUser;
import com.central.common.model.SysRole;
import com.central.common.model.SysUser;
import com.central.common.properties.DataScopeProperties;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
@@ -21,10 +21,10 @@ import java.util.Objects;
*/
public class CreatorDataScopeSqlHandler implements SqlHandler{
@Autowired
@Resource
UserService userService;
@Autowired
@Resource
private DataScopeProperties dataScopeProperties;
/**
@@ -35,7 +35,7 @@ public class CreatorDataScopeSqlHandler implements SqlHandler{
*/
@Override
public String handleScopeSql() {
SysUser user = LoginUserContextHolder.getUser();
LoginAppUser user = LoginUserContextHolder.getUser();
Assert.notNull(user, "登陆人不能为空");
List<SysRole> roleList = userService.findRolesByUserId(user.getId());
return StrUtil.isBlank(dataScopeProperties.getCreatorIdColumnName())
@@ -2,7 +2,6 @@ package com.central.common.feign;
import com.central.common.constant.ServiceNameConstants;
import com.central.common.feign.fallback.UserServiceFallbackFactory;
import com.central.common.model.LoginAppUser;
import com.central.common.model.SysRole;
import com.central.common.model.SysUser;
import org.springframework.cloud.openfeign.FeignClient;
@@ -15,7 +14,7 @@ import java.util.List;
/**
* @author zlt
*/
@FeignClient(name = ServiceNameConstants.USER_SERVICE, fallbackFactory = UserServiceFallbackFactory.class, decode404 = true)
@FeignClient(name = ServiceNameConstants.USER_SERVICE, fallbackFactory = UserServiceFallbackFactory.class, dismiss404 = true)
public interface UserService {
/**
* feign rpc访问远程/users/{username}接口
@@ -34,7 +33,7 @@ public interface UserService {
* @return
*/
@GetMapping(value = "/users-anon/login", params = "username")
LoginAppUser findByUsername(@RequestParam("username") String username);
SysUser findByUsername(@RequestParam("username") String username);
/**
* 通过手机号查询用户、角色信息
@@ -42,7 +41,7 @@ public interface UserService {
* @param mobile 手机号
*/
@GetMapping(value = "/users-anon/mobile", params = "mobile")
LoginAppUser findByMobile(@RequestParam("mobile") String mobile);
SysUser findByMobile(@RequestParam("mobile") String mobile);
/**
* 根据OpenId查询用户信息
@@ -50,7 +49,7 @@ public interface UserService {
* @param openId openId
*/
@GetMapping(value = "/users-anon/openId", params = "openId")
LoginAppUser findByOpenId(@RequestParam("openId") String openId);
SysUser findByOpenId(@RequestParam("openId") String openId);
/**
@@ -1,7 +1,6 @@
package com.central.common.feign.fallback;
import com.central.common.feign.UserService;
import com.central.common.model.LoginAppUser;
import com.central.common.model.SysRole;
import com.central.common.model.SysUser;
import org.springframework.cloud.openfeign.FallbackFactory;
@@ -28,21 +27,21 @@ public class UserServiceFallbackFactory implements FallbackFactory<UserService>
}
@Override
public LoginAppUser findByUsername(String username) {
public SysUser findByUsername(String username) {
log.error("通过用户名查询用户异常:{}", username, throwable);
return new LoginAppUser();
return new SysUser();
}
@Override
public LoginAppUser findByMobile(String mobile) {
public SysUser findByMobile(String mobile) {
log.error("通过手机号查询用户异常:{}", mobile, throwable);
return new LoginAppUser();
return new SysUser();
}
@Override
public LoginAppUser findByOpenId(String openId) {
public SysUser findByOpenId(String openId) {
log.error("通过openId查询用户异常:{}", openId, throwable);
return new LoginAppUser();
return new SysUser();
}
/**
@@ -8,7 +8,7 @@ import java.util.concurrent.TimeUnit;
* @author zlt
* @date 2018/5/29 14:12
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public interface DistributedLock {
@@ -7,7 +7,7 @@ import java.util.concurrent.TimeUnit;
* @author zlt
* @date 2020/6/6
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@@ -20,7 +20,7 @@ import org.springframework.expression.spel.support.StandardEvaluationContext;
* @author zlt
* @date 2020/6/6
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@@ -9,7 +9,7 @@ import lombok.Getter;
* @author zlt
* @date 2020/7/28
* <p>
* Blog: https://zlt2000.gitee.io
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@AllArgsConstructor

Some files were not shown because too many files have changed in this diff Show More