com.spotify
docker-maven-plugin
diff --git a/zlt-business/code-generator/pom.xml b/zlt-business/code-generator/pom.xml
index d7f26bc2..a3ff6890 100644
--- a/zlt-business/code-generator/pom.xml
+++ b/zlt-business/code-generator/pom.xml
@@ -4,7 +4,7 @@
com.zlt
zlt-business
- 5.6.0
+ 6.0.0
code-generator
@@ -26,8 +26,8 @@
zlt-db-spring-boot-starter
- com.zlt
- zlt-swagger2-spring-boot-starter
+ com.github.xiaoymin
+ knife4j-openapi3-jakarta-spring-boot-starter
com.alibaba.cloud
diff --git a/zlt-business/code-generator/src/main/java/com/central/generator/controller/SysGeneratorController.java b/zlt-business/code-generator/src/main/java/com/central/generator/controller/SysGeneratorController.java
index 4f53ce01..a3217ded 100644
--- a/zlt-business/code-generator/src/main/java/com/central/generator/controller/SysGeneratorController.java
+++ b/zlt-business/code-generator/src/main/java/com/central/generator/controller/SysGeneratorController.java
@@ -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
diff --git a/zlt-business/code-generator/src/main/resources/application.yml b/zlt-business/code-generator/src/main/resources/application.yml
index 167e7a65..3f985645 100644
--- a/zlt-business/code-generator/src/main/resources/application.yml
+++ b/zlt-business/code-generator/src/main/resources/application.yml
@@ -8,4 +8,15 @@ spring:
mybatis-plus:
mapper-locations: classpath:/mapper/*Mapper.xml
#实体扫描,多个package用逗号或者分号分隔
- typeAliasesPackage: com.central.generator.model
\ No newline at end of file
+ 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: 代码生成器接口文档
\ No newline at end of file
diff --git a/zlt-business/code-generator/src/main/resources/template/Controller.java.vm b/zlt-business/code-generator/src/main/resources/template/Controller.java.vm
index dad9d717..76554431 100644
--- a/zlt-business/code-generator/src/main/resources/template/Controller.java.vm
+++ b/zlt-business/code-generator/src/main/resources/template/Controller.java.vm
@@ -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 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});
diff --git a/zlt-business/file-center/pom.xml b/zlt-business/file-center/pom.xml
index 1aa61ef8..62e32722 100644
--- a/zlt-business/file-center/pom.xml
+++ b/zlt-business/file-center/pom.xml
@@ -4,7 +4,7 @@
com.zlt
zlt-business
- 5.6.0
+ 6.0.0
file-center
文件中心
@@ -55,8 +55,8 @@
- com.zlt
- zlt-swagger2-spring-boot-starter
+ com.github.xiaoymin
+ knife4j-openapi3-jakarta-spring-boot-starter
diff --git a/zlt-business/file-center/src/main/java/com/central/file/config/WebMvcConfig.java b/zlt-business/file-center/src/main/java/com/central/file/config/WebMvcConfig.java
deleted file mode 100644
index c4dc350f..00000000
--- a/zlt-business/file-center/src/main/java/com/central/file/config/WebMvcConfig.java
+++ /dev/null
@@ -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 {
-}
diff --git a/zlt-business/file-center/src/main/java/com/central/file/service/impl/FastdfsService.java b/zlt-business/file-center/src/main/java/com/central/file/service/impl/FastdfsService.java
index fe54278e..a931af9a 100644
--- a/zlt-business/file-center/src/main/java/com/central/file/service/impl/FastdfsService.java
+++ b/zlt-business/file-center/src/main/java/com/central/file/service/impl/FastdfsService.java
@@ -14,7 +14,7 @@ import java.io.OutputStream;
* @author zlt
* @date 2021/2/13
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Service
diff --git a/zlt-business/file-center/src/main/java/com/central/file/service/impl/S3Service.java b/zlt-business/file-center/src/main/java/com/central/file/service/impl/S3Service.java
index f87679d6..a6dd4b86 100644
--- a/zlt-business/file-center/src/main/java/com/central/file/service/impl/S3Service.java
+++ b/zlt-business/file-center/src/main/java/com/central/file/service/impl/S3Service.java
@@ -19,7 +19,7 @@ import java.io.OutputStream;
* @author zlt
* @date 2021/2/13
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Service
diff --git a/zlt-business/file-center/src/main/resources/application.yml b/zlt-business/file-center/src/main/resources/application.yml
index 839effbe..d2099f0a 100644
--- a/zlt-business/file-center/src/main/resources/application.yml
+++ b/zlt-business/file-center/src/main/resources/application.yml
@@ -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
diff --git a/zlt-business/pom.xml b/zlt-business/pom.xml
index 3b677e20..6dfdc8c6 100644
--- a/zlt-business/pom.xml
+++ b/zlt-business/pom.xml
@@ -4,7 +4,7 @@
com.zlt
central-platform
- 5.6.0
+ 6.0.0
zlt-business
业务中心
diff --git a/zlt-business/search-center/pom.xml b/zlt-business/search-center/pom.xml
index e733071d..cdccf458 100644
--- a/zlt-business/search-center/pom.xml
+++ b/zlt-business/search-center/pom.xml
@@ -4,7 +4,7 @@
com.zlt
zlt-business
- 5.6.0
+ 6.0.0
search-center
搜索中心
diff --git a/zlt-business/search-center/search-client/pom.xml b/zlt-business/search-center/search-client/pom.xml
index 4d9942bf..af2cde44 100644
--- a/zlt-business/search-center/search-client/pom.xml
+++ b/zlt-business/search-center/search-client/pom.xml
@@ -4,7 +4,7 @@
com.zlt
search-center
- 5.6.0
+ 6.0.0
search-client
搜索中心客户端
diff --git a/zlt-business/search-center/search-client/src/main/java/com/central/search/client/feign/AggregationService.java b/zlt-business/search-center/search-client/src/main/java/com/central/search/client/feign/AggregationService.java
index 117de292..ee4d6bd6 100644
--- a/zlt-business/search-center/search-client/src/main/java/com/central/search/client/feign/AggregationService.java
+++ b/zlt-business/search-center/search-client/src/main/java/com/central/search/client/feign/AggregationService.java
@@ -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 {
/**
* 查询文档列表
diff --git a/zlt-business/search-center/search-client/src/main/java/com/central/search/client/feign/SearchService.java b/zlt-business/search-center/search-client/src/main/java/com/central/search/client/feign/SearchService.java
index b094f5c2..9ea09f85 100644
--- a/zlt-business/search-center/search-client/src/main/java/com/central/search/client/feign/SearchService.java
+++ b/zlt-business/search-center/search-client/src/main/java/com/central/search/client/feign/SearchService.java
@@ -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 {
/**
* 查询文档列表
diff --git a/zlt-business/search-center/search-client/src/main/java/com/central/search/client/feign/fallback/SearchServiceFallbackFactory.java b/zlt-business/search-center/search-client/src/main/java/com/central/search/client/feign/fallback/SearchServiceFallbackFactory.java
index ad2cb5b3..bea16ce3 100644
--- a/zlt-business/search-center/search-client/src/main/java/com/central/search/client/feign/fallback/SearchServiceFallbackFactory.java
+++ b/zlt-business/search-center/search-client/src/main/java/com/central/search/client/feign/fallback/SearchServiceFallbackFactory.java
@@ -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 {
@Override
public SearchService create(Throwable throwable) {
diff --git a/zlt-business/search-center/search-server/pom.xml b/zlt-business/search-center/search-server/pom.xml
index caac10f4..5d7ea2a5 100644
--- a/zlt-business/search-center/search-server/pom.xml
+++ b/zlt-business/search-center/search-server/pom.xml
@@ -4,7 +4,7 @@
com.zlt
search-center
- 5.6.0
+ 6.0.0
search-server
搜索中心服务端
@@ -51,10 +51,9 @@
- com.zlt
- zlt-swagger2-spring-boot-starter
+ com.github.xiaoymin
+ knife4j-openapi3-jakarta-spring-boot-starter
-
org.springframework.boot
spring-boot-starter-actuator
diff --git a/zlt-business/search-center/search-server/src/main/java/com/central/admin/controller/IndexController.java b/zlt-business/search-center/search-server/src/main/java/com/central/admin/controller/IndexController.java
index 6104be2d..b2eb23be 100644
--- a/zlt-business/search-center/search-server/src/main/java/com/central/admin/controller/IndexController.java
+++ b/zlt-business/search-center/search-server/src/main/java/com/central/admin/controller/IndexController.java
@@ -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
diff --git a/zlt-business/search-center/search-server/src/main/java/com/central/admin/service/impl/IndexServiceImpl.java b/zlt-business/search-center/search-server/src/main/java/com/central/admin/service/impl/IndexServiceImpl.java
index f4ad351f..a04ab78f 100644
--- a/zlt-business/search-center/search-server/src/main/java/com/central/admin/service/impl/IndexServiceImpl.java
+++ b/zlt-business/search-center/search-server/src/main/java/com/central/admin/service/impl/IndexServiceImpl.java
@@ -33,7 +33,7 @@ import java.util.*;
* @author zlt
* @date 2019/4/23
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Service
diff --git a/zlt-business/search-center/search-server/src/main/java/com/central/common/config/WebMvcConfig.java b/zlt-business/search-center/search-server/src/main/java/com/central/common/config/WebMvcConfig.java
deleted file mode 100644
index b7b56bf3..00000000
--- a/zlt-business/search-center/search-server/src/main/java/com/central/common/config/WebMvcConfig.java
+++ /dev/null
@@ -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 {
-}
diff --git a/zlt-business/search-center/search-server/src/main/java/com/central/search/controller/AggregationController.java b/zlt-business/search-center/search-server/src/main/java/com/central/search/controller/AggregationController.java
index 01f3bc19..0e73421c 100644
--- a/zlt-business/search-center/search-server/src/main/java/com/central/search/controller/AggregationController.java
+++ b/zlt-business/search-center/search-server/src/main/java/com/central/search/controller/AggregationController.java
@@ -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;
diff --git a/zlt-business/search-center/search-server/src/main/java/com/central/search/controller/SearchController.java b/zlt-business/search-center/search-server/src/main/java/com/central/search/controller/SearchController.java
index 6a7f30a5..3eaf1714 100644
--- a/zlt-business/search-center/search-server/src/main/java/com/central/search/controller/SearchController.java
+++ b/zlt-business/search-center/search-server/src/main/java/com/central/search/controller/SearchController.java
@@ -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;
diff --git a/zlt-business/search-center/search-server/src/main/java/com/central/search/service/impl/AggregationServiceImpl.java b/zlt-business/search-center/search-server/src/main/java/com/central/search/service/impl/AggregationServiceImpl.java
index 26125f55..381799a8 100644
--- a/zlt-business/search-center/search-server/src/main/java/com/central/search/service/impl/AggregationServiceImpl.java
+++ b/zlt-business/search-center/search-server/src/main/java/com/central/search/service/impl/AggregationServiceImpl.java
@@ -35,7 +35,7 @@ import java.util.Map;
* @author zlt
* @date 2019/5/7
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Service
diff --git a/zlt-business/search-center/search-server/src/main/resources/application.yml b/zlt-business/search-center/search-server/src/main/resources/application.yml
index ef580d74..c9dd642e 100644
--- a/zlt-business/search-center/search-server/src/main/resources/application.yml
+++ b/zlt-business/search-center/search-server/src/main/resources/application.yml
@@ -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
\ No newline at end of file
+ show: sys-log-*,mysql-slowlog-*,sys_user,point-log-*,audit-log-*
\ No newline at end of file
diff --git a/zlt-business/user-center/pom.xml b/zlt-business/user-center/pom.xml
index 28f97a69..70d6aa41 100644
--- a/zlt-business/user-center/pom.xml
+++ b/zlt-business/user-center/pom.xml
@@ -4,7 +4,7 @@
com.zlt
zlt-business
- 5.6.0
+ 6.0.0
user-center
用户中心
@@ -40,8 +40,8 @@
- com.zlt
- zlt-swagger2-spring-boot-starter
+ com.github.xiaoymin
+ knife4j-openapi3-jakarta-spring-boot-starter
com.zlt
diff --git a/zlt-business/user-center/src/main/java/com/central/user/config/WebMvcConfig.java b/zlt-business/user-center/src/main/java/com/central/user/config/WebMvcConfig.java
deleted file mode 100644
index 4db93cde..00000000
--- a/zlt-business/user-center/src/main/java/com/central/user/config/WebMvcConfig.java
+++ /dev/null
@@ -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 {
-}
diff --git a/zlt-business/user-center/src/main/java/com/central/user/controller/SysMenuController.java b/zlt-business/user-center/src/main/java/com/central/user/controller/SysMenuController.java
index eaf16e99..3ad3081e 100644
--- a/zlt-business/user-center/src/main/java/com/central/user/controller/SysMenuController.java
+++ b/zlt-business/user-center/src/main/java/com/central/user/controller/SysMenuController.java
@@ -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
-
-
- javax.servlet
- javax.servlet-api
- true
-
\ No newline at end of file
diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/LoginUserFilter.java b/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/LoginUserFilter.java
index 21c9a3eb..f1f875f8 100644
--- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/LoginUserFilter.java
+++ b/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/LoginUserFilter.java
@@ -1,17 +1,17 @@
package com.central.common.filter;
import com.central.common.context.LoginUserContextHolder;
-import com.central.common.model.SysUser;
+import com.central.common.model.LoginAppUser;
import com.central.common.utils.LoginUserUtils;
+import jakarta.servlet.Filter;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
@@ -20,7 +20,7 @@ import java.io.IOException;
* @author zlt
* @date 2022/6/26
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@ConditionalOnClass(Filter.class)
@@ -30,7 +30,7 @@ public class LoginUserFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
try {
- SysUser user = LoginUserUtils.getCurrentUser(request, false);
+ LoginAppUser user = LoginUserUtils.getCurrentUser(request, false);
LoginUserContextHolder.setUser(user);
filterChain.doFilter(request, response);
} finally {
diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/TenantFilter.java b/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/TenantFilter.java
index 506faa24..939c9ced 100644
--- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/TenantFilter.java
+++ b/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/TenantFilter.java
@@ -4,14 +4,14 @@ 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 jakarta.servlet.Filter;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.web.filter.OncePerRequestFilter;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/resources/META-INF/spring.factories b/zlt-commons/zlt-common-spring-boot-starter/src/main/resources/META-INF/spring.factories
deleted file mode 100644
index ffb5ffd9..00000000
--- a/zlt-commons/zlt-common-spring-boot-starter/src/main/resources/META-INF/spring.factories
+++ /dev/null
@@ -1,3 +0,0 @@
-org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
-com.central.common.filter.TenantFilter, \
-com.central.common.filter.LoginUserFilter
\ No newline at end of file
diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/zlt-commons/zlt-common-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
new file mode 100644
index 00000000..c6b3ecb8
--- /dev/null
+++ b/zlt-commons/zlt-common-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
@@ -0,0 +1,2 @@
+com.central.common.filter.TenantFilter
+com.central.common.filter.LoginUserFilter
\ No newline at end of file
diff --git a/zlt-commons/zlt-db-spring-boot-starter/pom.xml b/zlt-commons/zlt-db-spring-boot-starter/pom.xml
index a9c73377..2d6cf775 100644
--- a/zlt-commons/zlt-db-spring-boot-starter/pom.xml
+++ b/zlt-commons/zlt-db-spring-boot-starter/pom.xml
@@ -5,7 +5,7 @@
com.zlt
zlt-commons
- 5.6.0
+ 6.0.0
4.0.0
jar
diff --git a/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/DateMetaObjectHandler.java b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/DateMetaObjectHandler.java
index cf86429e..accd94dc 100644
--- a/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/DateMetaObjectHandler.java
+++ b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/DateMetaObjectHandler.java
@@ -12,7 +12,7 @@ import java.util.Date;
* @author zlt
* @date 2018/12/11
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class DateMetaObjectHandler implements MetaObjectHandler {
diff --git a/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/MybatisPlusAutoConfigure.java b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/MybatisPlusAutoConfigure.java
index 9f732b07..d5047549 100644
--- a/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/MybatisPlusAutoConfigure.java
+++ b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/MybatisPlusAutoConfigure.java
@@ -25,7 +25,7 @@ import org.springframework.context.annotation.Bean;
* @author zlt
* @date 2020/4/5
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@EnableConfigurationProperties({MybatisPlusAutoFillProperties.class, DataScopeProperties.class})
diff --git a/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/interceptor/CustomTenantInterceptor.java b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/interceptor/CustomTenantInterceptor.java
index f2083e7f..86e84e46 100644
--- a/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/interceptor/CustomTenantInterceptor.java
+++ b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/interceptor/CustomTenantInterceptor.java
@@ -18,7 +18,7 @@ import java.util.List;
* @version 1.0
* @date 2022/5/6
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class CustomTenantInterceptor extends TenantLineInnerInterceptor {
diff --git a/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/properties/MybatisPlusAutoFillProperties.java b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/properties/MybatisPlusAutoFillProperties.java
index 44b88f0f..4217377e 100644
--- a/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/properties/MybatisPlusAutoFillProperties.java
+++ b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/properties/MybatisPlusAutoFillProperties.java
@@ -11,7 +11,7 @@ import org.springframework.cloud.context.config.annotation.RefreshScope;
* @author zlt
* @date 2020/4/5
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
diff --git a/zlt-commons/zlt-db-spring-boot-starter/src/main/resources/META-INF/spring.factories b/zlt-commons/zlt-db-spring-boot-starter/src/main/resources/META-INF/spring.factories
deleted file mode 100644
index a939175d..00000000
--- a/zlt-commons/zlt-db-spring-boot-starter/src/main/resources/META-INF/spring.factories
+++ /dev/null
@@ -1,3 +0,0 @@
-org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
-com.central.db.config.TenantAutoConfigure,\
-com.central.db.config.MybatisPlusAutoConfigure
diff --git a/zlt-commons/zlt-db-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/zlt-commons/zlt-db-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
new file mode 100644
index 00000000..fc4a5382
--- /dev/null
+++ b/zlt-commons/zlt-db-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
@@ -0,0 +1,2 @@
+com.central.db.config.TenantAutoConfigure
+com.central.db.config.MybatisPlusAutoConfigure
\ No newline at end of file
diff --git a/zlt-commons/zlt-elasticsearch-spring-boot-starter/pom.xml b/zlt-commons/zlt-elasticsearch-spring-boot-starter/pom.xml
index 3011499f..dce8cd23 100644
--- a/zlt-commons/zlt-elasticsearch-spring-boot-starter/pom.xml
+++ b/zlt-commons/zlt-elasticsearch-spring-boot-starter/pom.xml
@@ -5,7 +5,7 @@
com.zlt
zlt-commons
- 5.6.0
+ 6.0.0
4.0.0
jar
diff --git a/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/java/com/central/es/config/RestAutoConfigure.java b/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/java/com/central/es/config/RestAutoConfigure.java
index 40711835..b232cc34 100644
--- a/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/java/com/central/es/config/RestAutoConfigure.java
+++ b/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/java/com/central/es/config/RestAutoConfigure.java
@@ -1,19 +1,20 @@
package com.central.es.config;
import com.central.es.properties.RestClientPoolProperties;
+import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
-import org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientProperties;
-import org.springframework.boot.autoconfigure.elasticsearch.RestClientBuilderCustomizer;
+import org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
-import org.springframework.boot.context.properties.PropertyMapper;
-import org.springframework.context.annotation.Bean;
-import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
+import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
+
+import javax.annotation.Resource;
+import java.util.List;
/**
* es自动配置
@@ -21,55 +22,49 @@ import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
* @author zlt
* @date 2020/3/28
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@EnableConfigurationProperties(RestClientPoolProperties.class)
-public class RestAutoConfigure {
- @Bean
- public RestClientBuilderCustomizer restClientBuilderCustomizer(RestClientPoolProperties poolProperties
- , ElasticsearchRestClientProperties restProperties) {
- return (builder) -> {
- setRequestConfig(builder, poolProperties);
+public class RestAutoConfigure extends AbstractElasticsearchConfiguration {
+ private final static String SCHEME = "http";
+ private final static String URI_SPLIT = ":";
- setHttpClientConfig(builder, poolProperties, restProperties);
- };
- }
+ @Resource
+ private ElasticsearchProperties restProperties;
- /**
- * 异步httpclient连接延时配置
- */
- private void setRequestConfig(RestClientBuilder builder, RestClientPoolProperties poolProperties){
- builder.setRequestConfigCallback(requestConfigBuilder -> {
- requestConfigBuilder.setConnectTimeout(poolProperties.getConnectTimeOut())
- .setSocketTimeout(poolProperties.getSocketTimeOut())
- .setConnectionRequestTimeout(poolProperties.getConnectionRequestTimeOut());
- return requestConfigBuilder;
- });
- }
+ @Resource
+ private RestClientPoolProperties poolProperties;
- /**
- * 异步httpclient连接数配置
- */
- private void setHttpClientConfig(RestClientBuilder builder, RestClientPoolProperties poolProperties, ElasticsearchRestClientProperties restProperties){
- builder.setHttpClientConfigCallback(httpClientBuilder -> {
- httpClientBuilder.setMaxConnTotal(poolProperties.getMaxConnectNum())
- .setMaxConnPerRoute(poolProperties.getMaxConnectPerRoute());
-
- PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();
- map.from(restProperties::getUsername).to(username -> {
- CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
- credentialsProvider.setCredentials(AuthScope.ANY,
- new UsernamePasswordCredentials(username, restProperties.getPassword()));
- httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
- });
- return httpClientBuilder;
- });
- }
-
- @Bean
- @ConditionalOnMissingBean
- public ElasticsearchRestTemplate elasticsearchRestTemplate(RestHighLevelClient restHighLevelClient) {
- return new ElasticsearchRestTemplate(restHighLevelClient);
+ @Override
+ public RestHighLevelClient elasticsearchClient() {
+ List urlArr = restProperties.getUris();
+ HttpHost[] httpPostArr = new HttpHost[urlArr.size()];
+ for (int i = 0; i < urlArr.size(); i++) {
+ HttpHost httpHost = new HttpHost(urlArr.get(i).split(URI_SPLIT)[0].trim(),
+ Integer.parseInt(urlArr.get(i).split(URI_SPLIT)[1].trim()), SCHEME);
+ httpPostArr[i] = httpHost;
+ }
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(AuthScope.ANY,
+ new UsernamePasswordCredentials(restProperties.getUsername(), restProperties.getPassword()));
+ RestClientBuilder builder = RestClient.builder(httpPostArr)
+ // 异步httpclient连接数配置
+ .setHttpClientConfigCallback(httpClientBuilder -> {
+ // 账号密码登录
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
+ // httpclient连接数配置
+ httpClientBuilder.setMaxConnTotal(poolProperties.getMaxConnectNum())
+ .setMaxConnPerRoute(poolProperties.getMaxConnectPerRoute());
+ return httpClientBuilder;
+ })
+ // 异步httpclient连接延时配置
+ .setRequestConfigCallback(requestConfigBuilder -> {
+ requestConfigBuilder.setConnectTimeout(poolProperties.getConnectTimeOut())
+ .setSocketTimeout(poolProperties.getSocketTimeOut())
+ .setConnectionRequestTimeout(poolProperties.getConnectionRequestTimeOut());
+ return requestConfigBuilder;
+ });
+ return new RestHighLevelClient(builder);
}
}
diff --git a/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/java/com/central/es/properties/RestClientPoolProperties.java b/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/java/com/central/es/properties/RestClientPoolProperties.java
index 16b9d232..bfe5f8d2 100644
--- a/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/java/com/central/es/properties/RestClientPoolProperties.java
+++ b/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/java/com/central/es/properties/RestClientPoolProperties.java
@@ -11,7 +11,7 @@ import org.springframework.cloud.context.config.annotation.RefreshScope;
* @author zlt
* @date 2020/3/28
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
diff --git a/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/java/com/central/es/utils/SearchBuilder.java b/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/java/com/central/es/utils/SearchBuilder.java
index ba2521a3..c119600c 100644
--- a/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/java/com/central/es/utils/SearchBuilder.java
+++ b/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/java/com/central/es/utils/SearchBuilder.java
@@ -37,7 +37,7 @@ import java.util.Map;
* @author zlt
* @date 2020/3/28
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
diff --git a/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/resources/META-INF/spring.factories b/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/resources/META-INF/spring.factories
deleted file mode 100644
index fdaf2cf3..00000000
--- a/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/resources/META-INF/spring.factories
+++ /dev/null
@@ -1,2 +0,0 @@
-org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
-com.central.es.config.RestAutoConfigure
\ No newline at end of file
diff --git a/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
new file mode 100644
index 00000000..e6eeaa70
--- /dev/null
+++ b/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
@@ -0,0 +1 @@
+com.central.es.config.RestAutoConfigure
\ No newline at end of file
diff --git a/zlt-commons/zlt-loadbalancer-spring-boot-starter/pom.xml b/zlt-commons/zlt-loadbalancer-spring-boot-starter/pom.xml
index 0b9a91c9..3251f28d 100644
--- a/zlt-commons/zlt-loadbalancer-spring-boot-starter/pom.xml
+++ b/zlt-commons/zlt-loadbalancer-spring-boot-starter/pom.xml
@@ -5,7 +5,7 @@
com.zlt
zlt-commons
- 5.6.0
+ 6.0.0
4.0.0
jar
@@ -30,15 +30,9 @@
true
- org.apache.httpcomponents
- httpclient
+ org.apache.httpcomponents.client5
+ httpclient5
-
- javax.servlet
- javax.servlet-api
- true
-
-
org.springframework.boot
spring-boot-configuration-processor
diff --git a/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/RestTemplateAutoConfigure.java b/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/RestTemplateAutoConfigure.java
index b5fe3ef3..8685479e 100644
--- a/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/RestTemplateAutoConfigure.java
+++ b/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/RestTemplateAutoConfigure.java
@@ -1,20 +1,21 @@
package com.central.common.lb;
import com.central.common.lb.config.RestTemplateProperties;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.config.RequestConfig;
-import org.apache.http.config.Registry;
-import org.apache.http.config.RegistryBuilder;
-import org.apache.http.conn.socket.ConnectionSocketFactory;
-import org.apache.http.conn.socket.PlainConnectionSocketFactory;
-import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
-import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
-import org.apache.http.impl.client.HttpClientBuilder;
-import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
+import org.apache.hc.client5.http.classic.HttpClient;
+import org.apache.hc.client5.http.config.ConnectionConfig;
+import org.apache.hc.client5.http.config.RequestConfig;
+import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
+import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
+import org.apache.hc.client5.http.socket.ConnectionSocketFactory;
+import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory;
+import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
+import org.apache.hc.core5.http.config.Registry;
+import org.apache.hc.core5.http.config.RegistryBuilder;
+import org.apache.hc.core5.util.Timeout;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
-import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@@ -23,9 +24,10 @@ import org.springframework.web.client.RestTemplate;
* @author zlt
* @date 2018/11/17
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
+@Configuration
@EnableConfigurationProperties(RestTemplateProperties.class)
public class RestTemplateAutoConfigure {
@Autowired
@@ -61,19 +63,22 @@ public class RestTemplateAutoConfigure {
// 同路由并发数20
connectionManager.setDefaultMaxPerRoute(restTemplateProperties.getMaxPerRoute());
- RequestConfig requestConfig = RequestConfig.custom()
+ ConnectionConfig connectConfig = ConnectionConfig.custom()
// 读超时
- .setSocketTimeout(restTemplateProperties.getReadTimeout())
+ .setSocketTimeout(Timeout.ofMicroseconds(restTemplateProperties.getReadTimeout()))
// 链接超时
- .setConnectTimeout(restTemplateProperties.getConnectTimeout())
+ .setConnectTimeout(Timeout.ofMicroseconds(restTemplateProperties.getConnectTimeout()))
+ .build();
+ connectionManager.setDefaultConnectionConfig(connectConfig);
+
+ RequestConfig requestConfig = RequestConfig.custom()
// 链接不够用的等待时间
- .setConnectionRequestTimeout(restTemplateProperties.getReadTimeout())
+ .setConnectionRequestTimeout(Timeout.ofMicroseconds(restTemplateProperties.getReadTimeout()))
.build();
return HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(connectionManager)
- .setRetryHandler(new DefaultHttpRequestRetryHandler(3, true))
.build();
}
}
diff --git a/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/annotation/EnableBaseFeignInterceptor.java b/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/annotation/EnableBaseFeignInterceptor.java
index a0a9a817..1f3996ea 100644
--- a/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/annotation/EnableBaseFeignInterceptor.java
+++ b/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/annotation/EnableBaseFeignInterceptor.java
@@ -14,7 +14,7 @@ import java.lang.annotation.Target;
* @author zlt
* @date 2019/10/26
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Target(ElementType.TYPE)
diff --git a/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/config/FeignHttpInterceptorConfig.java b/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/config/FeignHttpInterceptorConfig.java
index 4e0e006a..2113be81 100644
--- a/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/config/FeignHttpInterceptorConfig.java
+++ b/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/config/FeignHttpInterceptorConfig.java
@@ -11,7 +11,7 @@ import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.PostConstruct;
-import javax.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
@@ -23,7 +23,7 @@ import java.util.Map;
* @author zlt
* @date 2019/10/26
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class FeignHttpInterceptorConfig {
diff --git a/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/config/FeignInterceptorConfig.java b/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/config/FeignInterceptorConfig.java
index 59da835e..2a544bd0 100644
--- a/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/config/FeignInterceptorConfig.java
+++ b/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/config/FeignInterceptorConfig.java
@@ -11,7 +11,7 @@ import org.springframework.context.annotation.Bean;
*
* @author zlt
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class FeignInterceptorConfig {
diff --git a/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/config/RestTemplateProperties.java b/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/config/RestTemplateProperties.java
index b0dd15cb..2e51ada2 100644
--- a/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/config/RestTemplateProperties.java
+++ b/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/java/com/central/common/lb/config/RestTemplateProperties.java
@@ -10,7 +10,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
* @author zlt
* @date 2017/11/17
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
diff --git a/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/resources/META-INF/spring.factories b/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/resources/META-INF/spring.factories
deleted file mode 100644
index 6154b24d..00000000
--- a/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/resources/META-INF/spring.factories
+++ /dev/null
@@ -1,3 +0,0 @@
-org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
-com.central.common.lb.RestTemplateAutoConfigure,\
-com.central.common.lb.config.VerionIsolationAutoConfig
\ No newline at end of file
diff --git a/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
new file mode 100644
index 00000000..d58da65b
--- /dev/null
+++ b/zlt-commons/zlt-loadbalancer-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
@@ -0,0 +1,2 @@
+com.central.common.lb.RestTemplateAutoConfigure
+com.central.common.lb.config.VerionIsolationAutoConfig
\ No newline at end of file
diff --git a/zlt-commons/zlt-log-spring-boot-starter/pom.xml b/zlt-commons/zlt-log-spring-boot-starter/pom.xml
index f921e7a0..032c7388 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/pom.xml
+++ b/zlt-commons/zlt-log-spring-boot-starter/pom.xml
@@ -5,7 +5,7 @@
com.zlt
zlt-commons
- 5.6.0
+ 6.0.0
4.0.0
jar
@@ -18,15 +18,6 @@
slf4j-api
-
- org.springframework.boot
- spring-boot-starter
-
-
- org.springframework.cloud
- spring-cloud-context
-
-
com.alibaba
transmittable-thread-local
@@ -52,11 +43,6 @@
spring-web
true
-
- javax.servlet
- javax.servlet-api
- true
-
org.springframework.boot
spring-boot-starter-jdbc
@@ -72,5 +58,9 @@
feign-core
true
+
+ org.apache.tomcat.embed
+ tomcat-embed-core
+
diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/annotation/AuditLog.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/annotation/AuditLog.java
index cde75670..f06297a4 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/annotation/AuditLog.java
+++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/annotation/AuditLog.java
@@ -6,7 +6,7 @@ import java.lang.annotation.*;
* @author zlt
* @date 2020/2/3
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Target({ElementType.METHOD, ElementType.TYPE})
diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/aspect/AuditLogAspect.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/aspect/AuditLogAspect.java
index a94fd8a6..6ca481be 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/aspect/AuditLogAspect.java
+++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/aspect/AuditLogAspect.java
@@ -4,6 +4,7 @@ import com.central.log.annotation.AuditLog;
import com.central.log.model.Audit;
import com.central.log.properties.AuditLogProperties;
import com.central.log.service.IAuditService;
+import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
@@ -20,7 +21,6 @@ import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
-import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
/**
@@ -29,7 +29,7 @@ import java.time.LocalDateTime;
* @author zlt
* @date 2020/2/3
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/model/Audit.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/model/Audit.java
index 6cdc07ee..89bcb01e 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/model/Audit.java
+++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/model/Audit.java
@@ -11,7 +11,7 @@ import java.time.LocalDateTime;
* @author zlt
* @date 2020/2/3
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/monitor/PointUtil.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/monitor/PointUtil.java
index d7a38fa6..2abcd2ab 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/monitor/PointUtil.java
+++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/monitor/PointUtil.java
@@ -15,7 +15,7 @@ import java.util.Map;
*
* @author zlt
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/properties/AuditLogProperties.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/properties/AuditLogProperties.java
index 3f6713a8..0ea4941e 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/properties/AuditLogProperties.java
+++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/properties/AuditLogProperties.java
@@ -11,7 +11,7 @@ import org.springframework.cloud.context.config.annotation.RefreshScope;
* @author zlt
* @date 2020/2/3
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/properties/LogDbProperties.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/properties/LogDbProperties.java
index 518fc72f..f54e9837 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/properties/LogDbProperties.java
+++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/properties/LogDbProperties.java
@@ -3,6 +3,7 @@ package com.central.log.properties;
import com.zaxxer.hikari.HikariConfig;
import lombok.Getter;
import lombok.Setter;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
@@ -12,11 +13,12 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
* @author zlt
* @date 2020/2/8
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
@Getter
@ConfigurationProperties(prefix = "zlt.audit-log.datasource")
+@ConditionalOnClass(HikariConfig.class)
public class LogDbProperties extends HikariConfig {
}
diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/IAuditService.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/IAuditService.java
index 9e0c11b7..108675fa 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/IAuditService.java
+++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/IAuditService.java
@@ -8,7 +8,7 @@ import com.central.log.model.Audit;
* @author zlt
* @date 2020/2/3
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public interface IAuditService {
diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/impl/DbAuditServiceImpl.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/impl/DbAuditServiceImpl.java
index 1cae063c..df98bc7d 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/impl/DbAuditServiceImpl.java
+++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/impl/DbAuditServiceImpl.java
@@ -23,7 +23,7 @@ import javax.sql.DataSource;
* @author zlt
* @date 2020/2/8
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/impl/LoggerAuditServiceImpl.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/impl/LoggerAuditServiceImpl.java
index facfd34e..742502b9 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/impl/LoggerAuditServiceImpl.java
+++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/impl/LoggerAuditServiceImpl.java
@@ -14,7 +14,7 @@ import java.time.format.DateTimeFormatter;
* @author zlt
* @date 2020/2/3
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/DubboTraceFilter.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/DubboTraceFilter.java
index 1cd42cdf..4a53b1b5 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/DubboTraceFilter.java
+++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/DubboTraceFilter.java
@@ -11,7 +11,7 @@ import org.apache.dubbo.rpc.*;
* @author zlt
* @date 2021/1/30
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Activate(group = {CommonConstants.PROVIDER, CommonConstants.CONSUMER}, order = MDCTraceUtils.FILTER_ORDER)
diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/FeignTraceConfig.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/FeignTraceConfig.java
index d5a0d1e4..7edb2508 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/FeignTraceConfig.java
+++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/FeignTraceConfig.java
@@ -15,7 +15,7 @@ import javax.annotation.Resource;
* @author zlt
* @date 2021/1/28
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Configuration
diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/MDCTraceUtils.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/MDCTraceUtils.java
index d9bf610f..fdb86558 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/MDCTraceUtils.java
+++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/MDCTraceUtils.java
@@ -13,7 +13,7 @@ import java.util.concurrent.atomic.AtomicInteger;
* @author zlt
* @date 2020/10/14
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class MDCTraceUtils {
diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/WebTraceFilter.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/WebTraceFilter.java
index c7415f3e..8d4852c2 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/WebTraceFilter.java
+++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/trace/WebTraceFilter.java
@@ -2,16 +2,16 @@ package com.central.log.trace;
import cn.hutool.core.util.StrUtil;
import com.central.log.properties.TraceProperties;
+import jakarta.annotation.Resource;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
-import javax.annotation.Resource;
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
@@ -20,7 +20,7 @@ import java.io.IOException;
* @author zlt
* @date 2020/10/14
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Component
diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/org/slf4j/TtlMDCAdapter.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/org/slf4j/TtlMDCAdapter.java
index a1df074b..1bd01703 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/org/slf4j/TtlMDCAdapter.java
+++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/org/slf4j/TtlMDCAdapter.java
@@ -2,12 +2,10 @@ package org.slf4j;
import ch.qos.logback.classic.util.LogbackMDCAdapter;
import com.alibaba.ttl.TransmittableThreadLocal;
+import org.slf4j.helpers.ThreadLocalMapOfStacks;
import org.slf4j.spi.MDCAdapter;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
/**
* 重构{@link LogbackMDCAdapter}类,搭配TransmittableThreadLocal实现父子线程之间的数据传递
@@ -16,17 +14,12 @@ import java.util.Set;
* @date 2019/8/17
*/
public class TtlMDCAdapter implements MDCAdapter {
- private final ThreadLocal> copyOnInheritThreadLocal = new TransmittableThreadLocal<>();
-
- private static final int WRITE_OPERATION = 1;
- private static final int MAP_COPY_OPERATION = 2;
+ final ThreadLocal> readWriteThreadLocalMap = new TransmittableThreadLocal<>();
+ final ThreadLocal> readOnlyThreadLocalMap = new TransmittableThreadLocal<>();
+ private final ThreadLocalMapOfStacks threadLocalMapOfDeques = new ThreadLocalMapOfStacks();
private static TtlMDCAdapter mtcMDCAdapter;
- /**
- * keeps track of the last operation performed
- */
- private final ThreadLocal lastOperation = new ThreadLocal<>();
static {
mtcMDCAdapter = new TtlMDCAdapter();
@@ -37,60 +30,39 @@ public class TtlMDCAdapter implements MDCAdapter {
return mtcMDCAdapter;
}
- private Integer getAndSetLastOperation(int op) {
- Integer lastOp = lastOperation.get();
- lastOperation.set(op);
- return lastOp;
- }
-
- private static boolean wasLastOpReadOrNull(Integer lastOp) {
- return lastOp == null || lastOp == MAP_COPY_OPERATION;
- }
-
- private Map duplicateAndInsertNewMap(Map oldMap) {
- Map newMap = Collections.synchronizedMap(new HashMap<>());
- if (oldMap != null) {
- // we don't want the parent thread modifying oldMap while we are
- // iterating over it
- synchronized (oldMap) {
- newMap.putAll(oldMap);
- }
- }
-
- copyOnInheritThreadLocal.set(newMap);
- return newMap;
- }
-
- /**
- * Put a context value (the val parameter) as identified with the
- * key parameter into the current thread's context map. Note that
- * contrary to log4j, the val parameter can be null.
- *
- *
- * If the current thread does not have a context map it is created as a side
- * effect of this call.
- *
- * @throws IllegalArgumentException in case the "key" parameter is null
- */
- @Override
- public void put(String key, String val) {
+ public void put(String key, String val) throws IllegalArgumentException {
if (key == null) {
throw new IllegalArgumentException("key cannot be null");
}
+ Map current = readWriteThreadLocalMap.get();
+ if (current == null) {
+ current = new HashMap<>();
+ readWriteThreadLocalMap.set(current);
+ }
- Map oldMap = copyOnInheritThreadLocal.get();
- Integer lastOp = getAndSetLastOperation(WRITE_OPERATION);
+ current.put(key, val);
+ nullifyReadOnlyThreadLocalMap();
+ }
- if (wasLastOpReadOrNull(lastOp) || oldMap == null) {
- Map newMap = duplicateAndInsertNewMap(oldMap);
- newMap.put(key, val);
+ /**
+ * Get the context identified by the key parameter.
+ *
+ *
+ * This method has no side effects.
+ */
+ @Override
+ public String get(String key) {
+ Map hashMap = readWriteThreadLocalMap.get();
+
+ if ((hashMap != null) && (key != null)) {
+ return hashMap.get(key);
} else {
- oldMap.put(key, val);
+ return null;
}
}
/**
- * Remove the the context identified by the key parameter.
+ * Remove the context identified by the key parameter.
*
*/
@Override
@@ -98,53 +70,58 @@ public class TtlMDCAdapter implements MDCAdapter {
if (key == null) {
return;
}
- Map oldMap = copyOnInheritThreadLocal.get();
- if (oldMap == null) {
- return;
+
+ Map current = readWriteThreadLocalMap.get();
+ if (current != null) {
+ current.remove(key);
+ nullifyReadOnlyThreadLocalMap();
}
-
- Integer lastOp = getAndSetLastOperation(WRITE_OPERATION);
-
- if (wasLastOpReadOrNull(lastOp)) {
- Map newMap = duplicateAndInsertNewMap(oldMap);
- newMap.remove(key);
- } else {
- oldMap.remove(key);
- }
-
}
+ private void nullifyReadOnlyThreadLocalMap() {
+ readOnlyThreadLocalMap.set(null);
+ }
/**
* Clear all entries in the MDC.
*/
@Override
public void clear() {
- lastOperation.set(WRITE_OPERATION);
- copyOnInheritThreadLocal.remove();
+ readWriteThreadLocalMap.set(null);
+ nullifyReadOnlyThreadLocalMap();
}
/**
- * Get the context identified by the key parameter.
- *
- */
- @Override
- public String get(String key) {
- final Map map = copyOnInheritThreadLocal.get();
- if ((map != null) && (key != null)) {
- return map.get(key);
- } else {
- return null;
- }
- }
-
- /**
- * Get the current thread's MDC as a map. This method is intended to be used
- * internally.
+ * Get the current thread's MDC as a map. This method is intended to be used
+ * internally.
+ *
+ * The returned map is unmodifiable (since version 1.3.2/1.4.2).
*/
+ @SuppressWarnings("unchecked")
public Map getPropertyMap() {
- lastOperation.set(MAP_COPY_OPERATION);
- return copyOnInheritThreadLocal.get();
+ Map readOnlyMap = readOnlyThreadLocalMap.get();
+ if (readOnlyMap == null) {
+ Map current = readWriteThreadLocalMap.get();
+ if (current != null) {
+ final Map tempMap = new HashMap<>(current);
+ readOnlyMap = Collections.unmodifiableMap(tempMap);
+ readOnlyThreadLocalMap.set(readOnlyMap);
+ }
+ }
+ return readOnlyMap;
+ }
+
+ /**
+ * Return a copy of the current thread's context map. Returned value may be
+ * null.
+ */
+ public Map getCopyOfContextMap() {
+ Map readOnlyMap = getPropertyMap();
+ if (readOnlyMap == null) {
+ return null;
+ } else {
+ return new HashMap<>(readOnlyMap);
+ }
}
/**
@@ -152,37 +129,43 @@ public class TtlMDCAdapter implements MDCAdapter {
* null.
*/
public Set getKeys() {
- Map map = getPropertyMap();
+ Map readOnlyMap = getPropertyMap();
- if (map != null) {
- return map.keySet();
+ if (readOnlyMap != null) {
+ return readOnlyMap.keySet();
} else {
return null;
}
}
- /**
- * Return a copy of the current thread's context map. Returned value may be
- * null.
- */
- @Override
- public Map getCopyOfContextMap() {
- Map hashMap = copyOnInheritThreadLocal.get();
- if (hashMap == null) {
- return null;
+ @SuppressWarnings("unchecked")
+ public void setContextMap(Map contextMap) {
+ if (contextMap != null) {
+ readWriteThreadLocalMap.set(new HashMap(contextMap));
} else {
- return new HashMap<>(hashMap);
+ readWriteThreadLocalMap.set(null);
}
+ nullifyReadOnlyThreadLocalMap();
+ }
+
+
+ @Override
+ public void pushByKey(String key, String value) {
+ threadLocalMapOfDeques.pushByKey(key, value);
}
@Override
- public void setContextMap(Map contextMap) {
- lastOperation.set(WRITE_OPERATION);
+ public String popByKey(String key) {
+ return threadLocalMapOfDeques.popByKey(key);
+ }
- Map newMap = Collections.synchronizedMap(new HashMap<>());
- newMap.putAll(contextMap);
+ @Override
+ public Deque getCopyOfDequeByKey(String key) {
+ return threadLocalMapOfDeques.getCopyOfDequeByKey(key);
+ }
- // the newMap replaces the old one for serialisation's sake
- copyOnInheritThreadLocal.set(newMap);
+ @Override
+ public void clearDequeByKey(String key) {
+ threadLocalMapOfDeques.clearDequeByKey(key);
}
}
diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/META-INF/spring.factories b/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/META-INF/spring.factories
index afcf8d5a..6a817fe4 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/META-INF/spring.factories
+++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/META-INF/spring.factories
@@ -1,5 +1,2 @@
org.springframework.context.ApplicationContextInitializer=\
-com.central.log.config.TtlMDCAdapterInitializer
-
-org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
-com.central.log.LogAutoConfigure
\ No newline at end of file
+com.central.log.config.TtlMDCAdapterInitializer
\ No newline at end of file
diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
new file mode 100644
index 00000000..a350d862
--- /dev/null
+++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
@@ -0,0 +1 @@
+com.central.log.LogAutoConfigure
\ No newline at end of file
diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/logback-spring.xml b/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/logback-spring.xml
index 3fe98f07..016c7622 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/logback-spring.xml
+++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/logback-spring.xml
@@ -23,7 +23,6 @@
- true
${CONSOLE_LOG_PATTERN}
UTF-8
diff --git a/zlt-commons/zlt-oss-spring-boot-starter/pom.xml b/zlt-commons/zlt-oss-spring-boot-starter/pom.xml
index e2abfeff..099920f9 100644
--- a/zlt-commons/zlt-oss-spring-boot-starter/pom.xml
+++ b/zlt-commons/zlt-oss-spring-boot-starter/pom.xml
@@ -5,7 +5,7 @@
com.zlt
zlt-commons
- 5.6.0
+ 6.0.0
4.0.0
jar
diff --git a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/config/OssAutoConfigure.java b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/config/OssAutoConfigure.java
index 725bc196..419e6074 100644
--- a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/config/OssAutoConfigure.java
+++ b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/config/OssAutoConfigure.java
@@ -10,7 +10,7 @@ import org.springframework.context.annotation.Import;
* @author zlt
* @date 2021/2/13
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@EnableConfigurationProperties(FileServerProperties.class)
diff --git a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/model/ObjectInfo.java b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/model/ObjectInfo.java
index 15883a23..6dccbe6d 100644
--- a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/model/ObjectInfo.java
+++ b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/model/ObjectInfo.java
@@ -7,7 +7,7 @@ import lombok.Setter;
* @author zlt
* @date 2021/2/11
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
diff --git a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/FdfsProperties.java b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/FdfsProperties.java
index 94a27ce1..7c2356d7 100644
--- a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/FdfsProperties.java
+++ b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/FdfsProperties.java
@@ -9,7 +9,7 @@ import lombok.Setter;
* @author zlt
* @date 2021/2/11
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
diff --git a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/FileServerProperties.java b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/FileServerProperties.java
index ac5a786d..565ef7b7 100644
--- a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/FileServerProperties.java
+++ b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/FileServerProperties.java
@@ -8,7 +8,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
* @author zlt
* @date 2021/2/11
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
diff --git a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/S3Properties.java b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/S3Properties.java
index 6cf0f25d..aebd41ee 100644
--- a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/S3Properties.java
+++ b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/S3Properties.java
@@ -9,7 +9,7 @@ import lombok.Setter;
* @author zlt
* @date 2021/2/11
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
diff --git a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/service/IOssService.java b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/service/IOssService.java
index c4fe6a58..c63b2a5f 100644
--- a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/service/IOssService.java
+++ b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/service/IOssService.java
@@ -10,7 +10,7 @@ import java.io.OutputStream;
* @author zlt
* @date 2021/2/9
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public interface IOssService {
diff --git a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/template/FdfsTemplate.java b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/template/FdfsTemplate.java
index 8390a563..5e1a4ddd 100644
--- a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/template/FdfsTemplate.java
+++ b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/template/FdfsTemplate.java
@@ -21,7 +21,7 @@ import java.io.InputStream;
* @author zlt
* @date 2021/2/11
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@ConditionalOnClass(FastFileStorageClient.class)
diff --git a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/template/S3Template.java b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/template/S3Template.java
index eebf5433..60eae251 100644
--- a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/template/S3Template.java
+++ b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/template/S3Template.java
@@ -35,7 +35,7 @@ import java.util.Calendar;
* @author zlt
* @date 2021/2/11
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@ConditionalOnClass(AmazonS3.class)
diff --git a/zlt-commons/zlt-oss-spring-boot-starter/src/main/resources/META-INF/spring.factories b/zlt-commons/zlt-oss-spring-boot-starter/src/main/resources/META-INF/spring.factories
deleted file mode 100644
index 43d799a7..00000000
--- a/zlt-commons/zlt-oss-spring-boot-starter/src/main/resources/META-INF/spring.factories
+++ /dev/null
@@ -1,2 +0,0 @@
-org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
-com.central.oss.config.OssAutoConfigure
\ No newline at end of file
diff --git a/zlt-commons/zlt-oss-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/zlt-commons/zlt-oss-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
new file mode 100644
index 00000000..3abb13b2
--- /dev/null
+++ b/zlt-commons/zlt-oss-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
@@ -0,0 +1 @@
+com.central.oss.config.OssAutoConfigure
diff --git a/zlt-commons/zlt-redis-spring-boot-starter/pom.xml b/zlt-commons/zlt-redis-spring-boot-starter/pom.xml
index ddf27ba3..77295143 100644
--- a/zlt-commons/zlt-redis-spring-boot-starter/pom.xml
+++ b/zlt-commons/zlt-redis-spring-boot-starter/pom.xml
@@ -5,7 +5,7 @@
com.zlt
zlt-commons
- 5.6.0
+ 6.0.0
4.0.0
jar
@@ -37,5 +37,10 @@
spring-boot-configuration-processor
true
+
+
+ com.fasterxml.jackson.datatype
+ jackson-datatype-jsr310
+
diff --git a/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/RedisAutoConfigure.java b/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/RedisAutoConfigure.java
index 6f25cec7..60196b5c 100644
--- a/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/RedisAutoConfigure.java
+++ b/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/RedisAutoConfigure.java
@@ -1,13 +1,14 @@
package com.central.common.redis;
import com.central.common.redis.properties.CacheManagerProperties;
-import org.springframework.beans.factory.annotation.Autowired;
+import jakarta.annotation.Resource;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
@@ -25,13 +26,14 @@ import java.util.Map;
* @author zlt
* @date 2018/11/6 11:02
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
+@ComponentScan
@EnableConfigurationProperties({RedisProperties.class, CacheManagerProperties.class})
@EnableCaching
public class RedisAutoConfigure {
- @Autowired
+ @Resource
private CacheManagerProperties cacheManagerProperties;
@Bean
diff --git a/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/component/RedissonAutoConfigCustomizers.java b/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/component/RedissonAutoConfigCustomizers.java
new file mode 100644
index 00000000..0f6e4986
--- /dev/null
+++ b/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/component/RedissonAutoConfigCustomizers.java
@@ -0,0 +1,24 @@
+package com.central.common.redis.component;
+
+import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
+import org.redisson.codec.JsonJacksonCodec;
+import org.redisson.config.Config;
+import org.redisson.spring.starter.RedissonAutoConfigurationCustomizer;
+import org.springframework.stereotype.Component;
+
+/**
+ * @author: zlt
+ * @date: 2023/11/21
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+@Component
+public class RedissonAutoConfigCustomizers implements RedissonAutoConfigurationCustomizer {
+ @Override
+ public void customize(Config configuration) {
+ JsonJacksonCodec jacksonCodec = new JsonJacksonCodec();
+ jacksonCodec.getObjectMapper().registerModule(new JavaTimeModule());
+ configuration.setCodec(jacksonCodec);
+ }
+}
diff --git a/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/lock/RedisDistributedLock.java b/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/lock/RedisDistributedLock.java
index 9b305e4c..fb48a52a 100644
--- a/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/lock/RedisDistributedLock.java
+++ b/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/lock/RedisDistributedLock.java
@@ -18,7 +18,7 @@ import java.util.concurrent.TimeUnit;
* @author zlt
* @date 2018/5/29 14:16
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*
* @deprecated 建议使用Redisson的实现方式 {@link RedissonDistributedLock}
diff --git a/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/lock/RedissonDistributedLock.java b/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/lock/RedissonDistributedLock.java
index fef19243..5e3ce110 100644
--- a/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/lock/RedissonDistributedLock.java
+++ b/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/lock/RedissonDistributedLock.java
@@ -9,6 +9,7 @@ import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@@ -20,11 +21,12 @@ import java.util.concurrent.TimeUnit;
* @author zlt
* @date 2020/5/5
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@ConditionalOnClass(RedissonClient.class)
@ConditionalOnProperty(prefix = "zlt.lock", name = "lockerType", havingValue = "REDIS", matchIfMissing = true)
+@Component
public class RedissonDistributedLock implements DistributedLock {
@Autowired
private RedissonClient redisson;
diff --git a/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/template/RedisRepository.java b/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/template/RedisRepository.java
index 7c80302f..704415fe 100644
--- a/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/template/RedisRepository.java
+++ b/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/template/RedisRepository.java
@@ -10,6 +10,7 @@ import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationUtils;
+import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.util.*;
@@ -21,10 +22,11 @@ import java.util.concurrent.TimeUnit;
*
* @author zlt
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
+@Component
public class RedisRepository {
/**
* Spring Redis Template
diff --git a/zlt-commons/zlt-redis-spring-boot-starter/src/main/resources/META-INF/spring.factories b/zlt-commons/zlt-redis-spring-boot-starter/src/main/resources/META-INF/spring.factories
deleted file mode 100644
index c0dc55ef..00000000
--- a/zlt-commons/zlt-redis-spring-boot-starter/src/main/resources/META-INF/spring.factories
+++ /dev/null
@@ -1,4 +0,0 @@
-org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
-com.central.common.redis.RedisAutoConfigure,\
-com.central.common.redis.lock.RedissonDistributedLock,\
-com.central.common.redis.template.RedisRepository
\ No newline at end of file
diff --git a/zlt-commons/zlt-redis-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/zlt-commons/zlt-redis-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
new file mode 100644
index 00000000..a936b4a2
--- /dev/null
+++ b/zlt-commons/zlt-redis-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
@@ -0,0 +1 @@
+com.central.common.redis.RedisAutoConfigure
\ No newline at end of file
diff --git a/zlt-commons/zlt-sentinel-spring-boot-starter/pom.xml b/zlt-commons/zlt-sentinel-spring-boot-starter/pom.xml
index 4c62722d..7bdc1b0a 100644
--- a/zlt-commons/zlt-sentinel-spring-boot-starter/pom.xml
+++ b/zlt-commons/zlt-sentinel-spring-boot-starter/pom.xml
@@ -5,7 +5,7 @@
com.zlt
zlt-commons
- 5.6.0
+ 6.0.0
4.0.0
jar
diff --git a/zlt-commons/zlt-sentinel-spring-boot-starter/src/main/java/com/central/sentinel/config/SentinelAutoConfigure.java b/zlt-commons/zlt-sentinel-spring-boot-starter/src/main/java/com/central/sentinel/config/SentinelAutoConfigure.java
index 864d8535..d7d27d3d 100644
--- a/zlt-commons/zlt-sentinel-spring-boot-starter/src/main/java/com/central/sentinel/config/SentinelAutoConfigure.java
+++ b/zlt-commons/zlt-sentinel-spring-boot-starter/src/main/java/com/central/sentinel/config/SentinelAutoConfigure.java
@@ -12,7 +12,7 @@ import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
-import javax.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequest;
/**
* Sentinel配置类
@@ -20,7 +20,7 @@ import javax.servlet.http.HttpServletRequest;
* @author zlt
* @date 2019/1/22
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class SentinelAutoConfigure {
diff --git a/zlt-commons/zlt-sentinel-spring-boot-starter/src/main/resources/META-INF/spring.factories b/zlt-commons/zlt-sentinel-spring-boot-starter/src/main/resources/META-INF/spring.factories
deleted file mode 100644
index 69f01160..00000000
--- a/zlt-commons/zlt-sentinel-spring-boot-starter/src/main/resources/META-INF/spring.factories
+++ /dev/null
@@ -1,2 +0,0 @@
-org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
-com.central.sentinel.config.SentinelAutoConfigure
diff --git a/zlt-commons/zlt-sentinel-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/zlt-commons/zlt-sentinel-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
new file mode 100644
index 00000000..bce30fd8
--- /dev/null
+++ b/zlt-commons/zlt-sentinel-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
@@ -0,0 +1 @@
+com.central.sentinel.config.SentinelAutoConfigure
\ No newline at end of file
diff --git a/zlt-commons/zlt-swagger2-spring-boot-starter/pom.xml b/zlt-commons/zlt-swagger2-spring-boot-starter/pom.xml
deleted file mode 100644
index 0a992c22..00000000
--- a/zlt-commons/zlt-swagger2-spring-boot-starter/pom.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
-
- com.zlt
- zlt-commons
- 5.6.0
-
- 4.0.0
- jar
- zlt-swagger2-spring-boot-starter
- swagger通用组件
-
-
- org.springframework.boot
- spring-boot-starter
-
-
- com.github.xiaoymin
- knife4j-micro-spring-boot-starter
-
-
- org.springframework.boot
- spring-boot-configuration-processor
- true
-
-
-
diff --git a/zlt-commons/zlt-swagger2-spring-boot-starter/src/main/java/com/central/common/swagger2/SwaggerAutoConfiguration.java b/zlt-commons/zlt-swagger2-spring-boot-starter/src/main/java/com/central/common/swagger2/SwaggerAutoConfiguration.java
deleted file mode 100644
index 0919f96d..00000000
--- a/zlt-commons/zlt-swagger2-spring-boot-starter/src/main/java/com/central/common/swagger2/SwaggerAutoConfiguration.java
+++ /dev/null
@@ -1,271 +0,0 @@
-package com.central.common.swagger2;
-
-import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
-import com.google.common.collect.Lists;
-import org.springframework.beans.factory.BeanFactory;
-import org.springframework.beans.factory.BeanFactoryAware;
-import org.springframework.beans.factory.config.ConfigurableBeanFactory;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Import;
-import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
-import springfox.documentation.builders.ApiInfoBuilder;
-import springfox.documentation.builders.ParameterBuilder;
-import springfox.documentation.builders.PathSelectors;
-import springfox.documentation.builders.RequestHandlerSelectors;
-import springfox.documentation.schema.ModelRef;
-import springfox.documentation.service.ApiInfo;
-import springfox.documentation.service.ApiKey;
-import springfox.documentation.service.AuthorizationScope;
-import springfox.documentation.service.Contact;
-import springfox.documentation.service.Parameter;
-import springfox.documentation.service.SecurityReference;
-import springfox.documentation.spi.DocumentationType;
-import springfox.documentation.spi.service.contexts.SecurityContext;
-import springfox.documentation.spring.web.plugins.Docket;
-import springfox.documentation.swagger2.annotations.EnableSwagger2;
-
-import java.util.ArrayList;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Objects;
-import java.util.Set;
-import java.util.stream.Collectors;
-
-/**
- * @author zlt
- * @date 2018/11/18 9:22
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Configuration
-@EnableSwagger2
-@EnableKnife4j
-@Import(BeanValidatorPluginsConfiguration.class)
-public class SwaggerAutoConfiguration implements BeanFactoryAware {
- private static final String AUTH_KEY = "Authorization";
-
- private BeanFactory beanFactory;
-
- @Bean
- @ConditionalOnMissingBean
- public SwaggerProperties swaggerProperties() {
- return new SwaggerProperties();
- }
-
- @Bean
- @ConditionalOnMissingBean
- @ConditionalOnProperty(name = "zlt.swagger.enabled", matchIfMissing = true)
- public List createRestApi(SwaggerProperties swaggerProperties) {
- ConfigurableBeanFactory configurableBeanFactory = (ConfigurableBeanFactory) beanFactory;
- List docketList = new LinkedList<>();
-
- // 没有分组
- if (swaggerProperties.getDocket().size() == 0) {
- final Docket docket = createDocket(swaggerProperties);
- configurableBeanFactory.registerSingleton("defaultDocket", docket);
- docketList.add(docket);
- return docketList;
- }
-
- // 分组创建
- for (String groupName : swaggerProperties.getDocket().keySet()) {
- SwaggerProperties.DocketInfo docketInfo = swaggerProperties.getDocket().get(groupName);
-
- ApiInfo apiInfo = new ApiInfoBuilder()
- .title(docketInfo.getTitle().isEmpty() ? swaggerProperties.getTitle() : docketInfo.getTitle())
- .description(docketInfo.getDescription().isEmpty() ? swaggerProperties.getDescription() : docketInfo.getDescription())
- .version(docketInfo.getVersion().isEmpty() ? swaggerProperties.getVersion() : docketInfo.getVersion())
- .license(docketInfo.getLicense().isEmpty() ? swaggerProperties.getLicense() : docketInfo.getLicense())
- .licenseUrl(docketInfo.getLicenseUrl().isEmpty() ? swaggerProperties.getLicenseUrl() : docketInfo.getLicenseUrl())
- .contact(
- new Contact(
- docketInfo.getContact().getName().isEmpty() ? swaggerProperties.getContact().getName() : docketInfo.getContact().getName(),
- docketInfo.getContact().getUrl().isEmpty() ? swaggerProperties.getContact().getUrl() : docketInfo.getContact().getUrl(),
- docketInfo.getContact().getEmail().isEmpty() ? swaggerProperties.getContact().getEmail() : docketInfo.getContact().getEmail()
- )
- )
- .termsOfServiceUrl(docketInfo.getTermsOfServiceUrl().isEmpty() ? swaggerProperties.getTermsOfServiceUrl() : docketInfo.getTermsOfServiceUrl())
- .build();
-
- // base-path处理
- // 当没有配置任何path的时候,解析/**
- if (docketInfo.getBasePath().isEmpty()) {
- docketInfo.getBasePath().add("/**");
- }
- List> basePath = new ArrayList<>(docketInfo.getBasePath().size());
- for (String path : docketInfo.getBasePath()) {
- basePath.add(PathSelectors.ant(path));
- }
-
- // exclude-path处理
- List> excludePath = new ArrayList<>(docketInfo.getExcludePath().size());
- for (String path : docketInfo.getExcludePath()) {
- excludePath.add(PathSelectors.ant(path));
- }
-
- Docket docket = new Docket(DocumentationType.SWAGGER_2)
- .host(swaggerProperties.getHost())
- .apiInfo(apiInfo)
- .globalOperationParameters(assemblyGlobalOperationParameters(swaggerProperties.getGlobalOperationParameters(),
- docketInfo.getGlobalOperationParameters()))
- .groupName(groupName)
- .select()
- .apis(RequestHandlerSelectors.basePackage(docketInfo.getBasePackage()))
- .paths(
- Predicates.and(
- Predicates.not(Predicates.or(excludePath)),
- Predicates.or(basePath)
- )
- )
- .build()
- .securitySchemes(securitySchemes())
- .securityContexts(securityContexts());
-
- configurableBeanFactory.registerSingleton(groupName, docket);
- docketList.add(docket);
- }
- return docketList;
- }
-
- /**
- * 创建 Docket对象
- *
- * @param swaggerProperties swagger配置
- * @return Docket
- */
- private Docket createDocket(final SwaggerProperties swaggerProperties) {
- ApiInfo apiInfo = new ApiInfoBuilder()
- .title(swaggerProperties.getTitle())
- .description(swaggerProperties.getDescription())
- .version(swaggerProperties.getVersion())
- .license(swaggerProperties.getLicense())
- .licenseUrl(swaggerProperties.getLicenseUrl())
- .contact(new Contact(swaggerProperties.getContact().getName(),
- swaggerProperties.getContact().getUrl(),
- swaggerProperties.getContact().getEmail()))
- .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl())
- .build();
-
- // base-path处理
- // 当没有配置任何path的时候,解析/**
- if (swaggerProperties.getBasePath().isEmpty()) {
- swaggerProperties.getBasePath().add("/**");
- }
- List> basePath = new ArrayList<>();
- for (String path : swaggerProperties.getBasePath()) {
- basePath.add(PathSelectors.ant(path));
- }
-
- // exclude-path处理
- List> excludePath = new ArrayList<>();
- for (String path : swaggerProperties.getExcludePath()) {
- excludePath.add(PathSelectors.ant(path));
- }
-
- return new Docket(DocumentationType.SWAGGER_2)
- .host(swaggerProperties.getHost())
- .apiInfo(apiInfo)
- .globalOperationParameters(buildGlobalOperationParametersFromSwaggerProperties(
- swaggerProperties.getGlobalOperationParameters()))
- .select()
- .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
- .paths(
- Predicates.and(
- Predicates.not(Predicates.or(excludePath)),
- Predicates.or(basePath)
- )
- )
- .build()
- .securitySchemes(securitySchemes())
- .securityContexts(securityContexts());
- }
-
- @Override
- public void setBeanFactory(BeanFactory beanFactory) {
- this.beanFactory = beanFactory;
- }
-
- private List securityContexts() {
- List contexts = new ArrayList<>(1);
- SecurityContext securityContext = SecurityContext.builder()
- .securityReferences(defaultAuth())
- //.forPaths(PathSelectors.regex("^(?!auth).*$"))
- .build();
- contexts.add(securityContext);
- return contexts;
- }
-
- private List defaultAuth() {
- AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
- AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
- authorizationScopes[0] = authorizationScope;
- List references = new ArrayList<>(1);
- references.add(new SecurityReference(AUTH_KEY, authorizationScopes));
- return references;
- }
-
- private List securitySchemes() {
- List apiKeys = new ArrayList<>(1);
- ApiKey apiKey = new ApiKey(AUTH_KEY, AUTH_KEY, "header");
- apiKeys.add(apiKey);
- return apiKeys;
- }
-
- private List buildGlobalOperationParametersFromSwaggerProperties(
- List globalOperationParameters) {
- List parameters = Lists.newArrayList();
-
- if (Objects.isNull(globalOperationParameters)) {
- return parameters;
- }
- for (SwaggerProperties.GlobalOperationParameter globalOperationParameter : globalOperationParameters) {
- parameters.add(new ParameterBuilder()
- .name(globalOperationParameter.getName())
- .description(globalOperationParameter.getDescription())
- .modelRef(new ModelRef(globalOperationParameter.getModelRef()))
- .parameterType(globalOperationParameter.getParameterType())
- .required(Boolean.parseBoolean(globalOperationParameter.getRequired()))
- .build());
- }
- return parameters;
- }
-
- /**
- * 局部参数按照name覆盖局部参数
- *
- * @param globalOperationParameters
- * @param docketOperationParameters
- * @return
- */
- private List assemblyGlobalOperationParameters(
- List globalOperationParameters,
- List docketOperationParameters) {
-
- if (Objects.isNull(docketOperationParameters) || docketOperationParameters.isEmpty()) {
- return buildGlobalOperationParametersFromSwaggerProperties(globalOperationParameters);
- }
-
- Set docketNames = docketOperationParameters.stream()
- .map(SwaggerProperties.GlobalOperationParameter::getName)
- .collect(Collectors.toSet());
-
- List resultOperationParameters = Lists.newArrayList();
-
- if (Objects.nonNull(globalOperationParameters)) {
- for (SwaggerProperties.GlobalOperationParameter parameter : globalOperationParameters) {
- if (!docketNames.contains(parameter.getName())) {
- resultOperationParameters.add(parameter);
- }
- }
- }
-
- resultOperationParameters.addAll(docketOperationParameters);
- return buildGlobalOperationParametersFromSwaggerProperties(resultOperationParameters);
- }
-}
diff --git a/zlt-commons/zlt-swagger2-spring-boot-starter/src/main/java/com/central/common/swagger2/SwaggerProperties.java b/zlt-commons/zlt-swagger2-spring-boot-starter/src/main/java/com/central/common/swagger2/SwaggerProperties.java
deleted file mode 100644
index 89bbc873..00000000
--- a/zlt-commons/zlt-swagger2-spring-boot-starter/src/main/java/com/central/common/swagger2/SwaggerProperties.java
+++ /dev/null
@@ -1,112 +0,0 @@
-package com.central.common.swagger2;
-
-import lombok.Data;
-import lombok.Getter;
-import lombok.Setter;
-import org.springframework.boot.context.properties.ConfigurationProperties;
-
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * swagger2 属性配置
- *
- * @author zlt
- * @date 2018/11/18 9:17
- */
-@Data
-@ConfigurationProperties("zlt.swagger")
-public class SwaggerProperties {
- /**是否开启swagger**/
- private Boolean enabled;
- /**标题**/
- private String title = "";
- /**描述**/
- private String description = "";
- /**版本**/
- private String version = "";
- /**许可证**/
- private String license = "";
- /**许可证URL**/
- private String licenseUrl = "";
- /**服务条款URL**/
- private String termsOfServiceUrl = "";
- /**联系人**/
- private Contact contact = new Contact();
-
- /**swagger会解析的包路径**/
- private String basePackage = "";
-
- /**swagger会解析的url规则**/
- private List basePath = new ArrayList<>();
- /**在basePath基础上需要排除的url规则**/
- private List excludePath = new ArrayList<>();
-
- /**分组文档**/
- private Map docket = new LinkedHashMap<>();
-
- /**host信息**/
- private String host = "";
-
- /**全局参数配置**/
- private List globalOperationParameters;
-
- @Setter
- @Getter
- public static class GlobalOperationParameter{
- /**参数名**/
- private String name;
-
- /**描述信息**/
- private String description;
-
- /**指定参数类型**/
- private String modelRef;
-
- /**参数放在哪个地方:header,query,path,body.form**/
- private String parameterType;
-
- /**参数是否必须传**/
- private String required;
- }
-
- @Data
- public static class DocketInfo {
- /**标题**/
- private String title = "";
- /**描述**/
- private String description = "";
- /**版本**/
- private String version = "";
- /**许可证**/
- private String license = "";
- /**许可证URL**/
- private String licenseUrl = "";
- /**服务条款URL**/
- private String termsOfServiceUrl = "";
-
- private Contact contact = new Contact();
-
- /**swagger会解析的包路径**/
- private String basePackage = "";
-
- /**swagger会解析的url规则**/
- private List basePath = new ArrayList<>();
- /**在basePath基础上需要排除的url规则**/
- private List excludePath = new ArrayList<>();
-
- private List globalOperationParameters;
- }
-
- @Data
- public static class Contact {
- /**联系人**/
- private String name = "";
- /**联系人url**/
- private String url = "";
- /**联系人email**/
- private String email = "";
- }
-}
diff --git a/zlt-commons/zlt-swagger2-spring-boot-starter/src/main/resources/META-INF/spring.factories b/zlt-commons/zlt-swagger2-spring-boot-starter/src/main/resources/META-INF/spring.factories
deleted file mode 100644
index ae9b3414..00000000
--- a/zlt-commons/zlt-swagger2-spring-boot-starter/src/main/resources/META-INF/spring.factories
+++ /dev/null
@@ -1,2 +0,0 @@
-org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
-com.central.common.swagger2.SwaggerAutoConfiguration
\ No newline at end of file
diff --git a/zlt-commons/zlt-zookeeper-spring-boot-starter/pom.xml b/zlt-commons/zlt-zookeeper-spring-boot-starter/pom.xml
index cd7c6b76..021241e9 100644
--- a/zlt-commons/zlt-zookeeper-spring-boot-starter/pom.xml
+++ b/zlt-commons/zlt-zookeeper-spring-boot-starter/pom.xml
@@ -5,7 +5,7 @@
com.zlt
zlt-commons
- 5.6.0
+ 6.0.0
4.0.0
jar
diff --git a/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/java/com/central/common/zookeeper/ZookeeperAutoConfiguration.java b/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/java/com/central/common/zookeeper/ZookeeperAutoConfiguration.java
index 9744726a..b74c1994 100644
--- a/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/java/com/central/common/zookeeper/ZookeeperAutoConfiguration.java
+++ b/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/java/com/central/common/zookeeper/ZookeeperAutoConfiguration.java
@@ -17,7 +17,7 @@ import org.springframework.context.annotation.ComponentScan;
* @version 1.0
* @date 2021/4/3
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@EnableConfigurationProperties(ZookeeperProperty.class)
diff --git a/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/java/com/central/common/zookeeper/lock/ZookeeperDistributedLock.java b/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/java/com/central/common/zookeeper/lock/ZookeeperDistributedLock.java
index 28d24808..cb0e9333 100644
--- a/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/java/com/central/common/zookeeper/lock/ZookeeperDistributedLock.java
+++ b/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/java/com/central/common/zookeeper/lock/ZookeeperDistributedLock.java
@@ -19,7 +19,7 @@ import java.util.concurrent.TimeUnit;
* @version 1.0
* @date 2021/4/3
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Component
diff --git a/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/java/com/central/common/zookeeper/properties/ZookeeperProperty.java b/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/java/com/central/common/zookeeper/properties/ZookeeperProperty.java
index 7ed7d167..f65781d1 100644
--- a/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/java/com/central/common/zookeeper/properties/ZookeeperProperty.java
+++ b/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/java/com/central/common/zookeeper/properties/ZookeeperProperty.java
@@ -11,7 +11,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
* @version 1.0
* @date 2021/4/3
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
diff --git a/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/java/com/central/common/zookeeper/template/ZookeeperTemplate.java b/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/java/com/central/common/zookeeper/template/ZookeeperTemplate.java
index 397e5323..93372f08 100644
--- a/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/java/com/central/common/zookeeper/template/ZookeeperTemplate.java
+++ b/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/java/com/central/common/zookeeper/template/ZookeeperTemplate.java
@@ -19,7 +19,7 @@ import java.util.List;
* @version 1.0
* @date 2021/4/10
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Component
diff --git a/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/resources/META-INF/spring.factories b/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/resources/META-INF/spring.factories
deleted file mode 100644
index 96f338c0..00000000
--- a/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/resources/META-INF/spring.factories
+++ /dev/null
@@ -1,2 +0,0 @@
-org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
-com.central.common.zookeeper.ZookeeperAutoConfiguration
\ No newline at end of file
diff --git a/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
new file mode 100644
index 00000000..3df4ac07
--- /dev/null
+++ b/zlt-commons/zlt-zookeeper-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
@@ -0,0 +1 @@
+com.central.common.zookeeper.ZookeeperAutoConfiguration
\ No newline at end of file
diff --git a/zlt-config/pom.xml b/zlt-config/pom.xml
index cebc4513..ed136e5d 100644
--- a/zlt-config/pom.xml
+++ b/zlt-config/pom.xml
@@ -5,7 +5,7 @@
com.zlt
central-platform
- 5.6.0
+ 6.0.0
4.0.0
jar
diff --git a/zlt-config/src/main/resources/application-dev.properties b/zlt-config/src/main/resources/application-dev.properties
index 43d5ef6f..80bcb0ac 100644
--- a/zlt-config/src/main/resources/application-dev.properties
+++ b/zlt-config/src/main/resources/application-dev.properties
@@ -5,9 +5,9 @@ zlt.datasource.username=root
zlt.datasource.password=1q2w3e4r
##### redis配置
-spring.redis.host=192.168.28.130
-spring.redis.port=6379
-spring.redis.timeout=5000
+spring.data.redis.host=192.168.28.130
+spring.data.redis.port=6379
+spring.data.redis.timeout=5000
##### elasticsearch配置
zlt.elasticsearch.uris=192.168.28.130:9200
diff --git a/zlt-config/src/main/resources/application-prod.properties b/zlt-config/src/main/resources/application-prod.properties
index bce88d75..63aa5830 100644
--- a/zlt-config/src/main/resources/application-prod.properties
+++ b/zlt-config/src/main/resources/application-prod.properties
@@ -1,13 +1,13 @@
########################## 统一变量配置 ##########################
##### 数据库配置
-zlt.datasource.ip=192.168.28.131
+zlt.datasource.ip=192.168.28.130
zlt.datasource.username=root
zlt.datasource.password=1q2w3e4r
##### redis配置
-spring.redis.sentinel.master=mymaster
-spring.redis.sentinel.nodes=172.17.0.1
-spring.redis.password=
+spring.data.redis.sentinel.master=mymaster
+spring.data.redis.sentinel.nodes=172.17.0.1
+spring.data.redis.password=
##### elasticsearch配置
zlt.elasticsearch.uris=192.168.28.130:9200
diff --git a/zlt-config/src/main/resources/application-test.properties b/zlt-config/src/main/resources/application-test.properties
index ddf04395..61981671 100644
--- a/zlt-config/src/main/resources/application-test.properties
+++ b/zlt-config/src/main/resources/application-test.properties
@@ -1,13 +1,13 @@
########################## 统一变量配置 ##########################
##### 数据库配置
-zlt.datasource.ip=192.168.28.131
+zlt.datasource.ip=192.168.28.130
zlt.datasource.username=root
zlt.datasource.password=1q2w3e4r
##### redis配置
-spring.redis.host=192.168.28.130
-spring.redis.port=6379
-spring.redis.timeout=5000
+spring.data.redis.host=192.168.28.130
+spring.data.redis.port=6379
+spring.data.redis.timeout=5000
##### elasticsearch配置
zlt.elasticsearch.uris=192.168.28.130:9200
diff --git a/zlt-config/src/main/resources/application.properties b/zlt-config/src/main/resources/application.properties
index 99f7c0c0..00bea821 100644
--- a/zlt-config/src/main/resources/application.properties
+++ b/zlt-config/src/main/resources/application.properties
@@ -1,4 +1,6 @@
########################## application级别通用配置 ##########################
+spring.main.allow-circular-references=true
+
##### loadbalancer配置
## 切换实例的重试
spring.cloud.loadbalancer.retry.enabled=false
@@ -77,13 +79,22 @@ mybatis-plus.configuration.cache-enabled=false
##### redis配置
# 连接池最大连接数(使用负值表示没有限制)
-spring.redis.lettuce.pool.max-active=8
+spring.data.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
-spring.redis.lettuce.pool.max-wait=-1
+spring.data.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接
-spring.redis.lettuce.pool.max-idle=8
+spring.data.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接
-spring.redis.lettuce.pool.min-idle=0
+spring.data.redis.lettuce.pool.min-idle=0
##### logging配置
-logging.level.com.alibaba.nacos.client.naming=warn
\ No newline at end of file
+logging.level.com.alibaba.nacos.client.naming=warn
+
+##### swagger配置
+springdoc.swagger-ui.path=/swagger-ui.html
+springdoc.swagger-ui.tags-sorter=alpha
+springdoc.swagger-ui.operations-sorter=alpha
+springdoc.api-docs.path=/v3/api-docs
+springdoc.default-flat-param-object=true
+
+knife4j.setting.language=zh_cn
\ No newline at end of file
diff --git a/zlt-demo/dubbo-demo/pom.xml b/zlt-demo/dubbo-demo/pom.xml
index 1c1a07e7..aeed6439 100644
--- a/zlt-demo/dubbo-demo/pom.xml
+++ b/zlt-demo/dubbo-demo/pom.xml
@@ -6,7 +6,7 @@
com.zlt
zlt-demo
- 5.6.0
+ 6.0.0
dubbo-demo
@@ -24,6 +24,7 @@
com.alibaba.cloud
spring-cloud-starter-dubbo
+ 2021.1
diff --git a/zlt-demo/dubbo-demo/src/main/java/org/zlt/WebDubboApp.java b/zlt-demo/dubbo-demo/src/main/java/org/zlt/WebDubboApp.java
index 059c4d5c..6f2ca145 100644
--- a/zlt-demo/dubbo-demo/src/main/java/org/zlt/WebDubboApp.java
+++ b/zlt-demo/dubbo-demo/src/main/java/org/zlt/WebDubboApp.java
@@ -8,7 +8,7 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
* @author zlt
* @date 2020/1/30
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@EnableDiscoveryClient
diff --git a/zlt-demo/dubbo-demo/src/main/java/org/zlt/controller/WebController.java b/zlt-demo/dubbo-demo/src/main/java/org/zlt/controller/WebController.java
index 0a2e9a84..bf8ae51e 100644
--- a/zlt-demo/dubbo-demo/src/main/java/org/zlt/controller/WebController.java
+++ b/zlt-demo/dubbo-demo/src/main/java/org/zlt/controller/WebController.java
@@ -11,7 +11,7 @@ import org.zlt.service.RpcService;
* @author zlt
* @date 2020/6/26
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
diff --git a/zlt-demo/dubbo-demo/src/main/java/org/zlt/service/RpcService.java b/zlt-demo/dubbo-demo/src/main/java/org/zlt/service/RpcService.java
index 00e6fc3c..2e7636f9 100644
--- a/zlt-demo/dubbo-demo/src/main/java/org/zlt/service/RpcService.java
+++ b/zlt-demo/dubbo-demo/src/main/java/org/zlt/service/RpcService.java
@@ -4,7 +4,7 @@ package org.zlt.service;
* @author zlt
* @date 2020/1/30
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public interface RpcService {
diff --git a/zlt-demo/dubbo-demo/src/main/java/org/zlt/service/impl/RpcServiceImpl.java b/zlt-demo/dubbo-demo/src/main/java/org/zlt/service/impl/RpcServiceImpl.java
index cfabb23e..c0f294a7 100644
--- a/zlt-demo/dubbo-demo/src/main/java/org/zlt/service/impl/RpcServiceImpl.java
+++ b/zlt-demo/dubbo-demo/src/main/java/org/zlt/service/impl/RpcServiceImpl.java
@@ -8,7 +8,7 @@ import org.zlt.service.RpcService;
* @author zlt
* @date 2020/1/30
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
diff --git a/zlt-demo/pom.xml b/zlt-demo/pom.xml
index fc979432..bd150ed3 100644
--- a/zlt-demo/pom.xml
+++ b/zlt-demo/pom.xml
@@ -4,14 +4,12 @@
com.zlt
central-platform
- 5.6.0
+ 6.0.0
zlt-demo
pom
-
- txlcn-demo
sharding-jdbc-demo
diff --git a/zlt-demo/resources-server-demo/pom.xml b/zlt-demo/resources-server-demo/pom.xml
index 746ea4e6..a1caf0c2 100644
--- a/zlt-demo/resources-server-demo/pom.xml
+++ b/zlt-demo/resources-server-demo/pom.xml
@@ -6,7 +6,7 @@
com.zlt
zlt-demo
- 5.6.0
+ 6.0.0
resources-server-demo
diff --git a/zlt-demo/resources-server-demo/src/main/java/org/zlt/ResourcesServerApp.java b/zlt-demo/resources-server-demo/src/main/java/org/zlt/ResourcesServerApp.java
index 58306000..2e26ca54 100644
--- a/zlt-demo/resources-server-demo/src/main/java/org/zlt/ResourcesServerApp.java
+++ b/zlt-demo/resources-server-demo/src/main/java/org/zlt/ResourcesServerApp.java
@@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
* @author zlt
* @date 2022/6/25
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@SpringBootApplication
diff --git a/zlt-demo/resources-server-demo/src/main/java/org/zlt/config/MyResourceConfig.java b/zlt-demo/resources-server-demo/src/main/java/org/zlt/config/MyResourceConfig.java
index 06582143..482aef1e 100644
--- a/zlt-demo/resources-server-demo/src/main/java/org/zlt/config/MyResourceConfig.java
+++ b/zlt-demo/resources-server-demo/src/main/java/org/zlt/config/MyResourceConfig.java
@@ -1,8 +1,7 @@
package org.zlt.config;
-import com.central.oauth2.common.config.DefaultResourceServerConf;
import org.springframework.context.annotation.Configuration;
-import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
+//import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
/**
* security资源服务器配置
@@ -11,10 +10,10 @@ import org.springframework.security.oauth2.config.annotation.web.configuration.E
* @version 1.0
* @date 2022/6/25
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
-@Configuration
+/*@Configuration
@EnableResourceServer
public class MyResourceConfig extends DefaultResourceServerConf {
-}
+}*/
diff --git a/zlt-demo/resources-server-demo/src/main/java/org/zlt/config/WebMvcConfig.java b/zlt-demo/resources-server-demo/src/main/java/org/zlt/config/WebMvcConfig.java
deleted file mode 100644
index f2d06702..00000000
--- a/zlt-demo/resources-server-demo/src/main/java/org/zlt/config/WebMvcConfig.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package org.zlt.config;
-
-import com.central.common.config.DefaultWebMvcConfig;
-import org.springframework.context.annotation.Configuration;
-
-/**
- * web服务器配置
- *
- * @author zlt
- * @version 1.0
- * @date 2022/6/25
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Configuration
-public class WebMvcConfig extends DefaultWebMvcConfig {
-}
diff --git a/zlt-demo/resources-server-demo/src/main/java/org/zlt/controller/TestController.java b/zlt-demo/resources-server-demo/src/main/java/org/zlt/controller/TestController.java
index 5ea4eb6f..4b936898 100644
--- a/zlt-demo/resources-server-demo/src/main/java/org/zlt/controller/TestController.java
+++ b/zlt-demo/resources-server-demo/src/main/java/org/zlt/controller/TestController.java
@@ -1,8 +1,7 @@
package org.zlt.controller;
-import com.central.common.annotation.LoginUser;
import com.central.common.context.LoginUserContextHolder;
-import com.central.common.model.SysUser;
+import com.central.common.utils.LoginUserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -11,25 +10,25 @@ import org.springframework.web.bind.annotation.RestController;
* @author zlt
* @date 2022/6/25
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@RestController
public class TestController {
/**
- * 通过 @LoginUser 获取当前登录人
+ * 通过 LoginUserUtils 获取当前登录人
*/
@GetMapping("/test/auth")
- public String auth(@LoginUser SysUser user) {
- return "auth:" + user.getUsername();
+ public String auth() {
+ return "auth:" + LoginUserUtils.getCurrentUser(false).getUsername();
}
/**
* 通过 LoginUserContextHolder 获取当前登录人
*/
@GetMapping("/test/auth2")
- public String auth() {
+ public String auth2() {
return "auth2:" + LoginUserContextHolder.getUser().getUsername();
}
diff --git a/zlt-demo/rocketmq-demo/pom.xml b/zlt-demo/rocketmq-demo/pom.xml
index 5f898f4a..6230d3e9 100644
--- a/zlt-demo/rocketmq-demo/pom.xml
+++ b/zlt-demo/rocketmq-demo/pom.xml
@@ -4,7 +4,7 @@
com.zlt
zlt-demo
- 5.6.0
+ 6.0.0
rocketmq-demo
pom
diff --git a/zlt-demo/rocketmq-demo/rocketmq-consume/pom.xml b/zlt-demo/rocketmq-demo/rocketmq-consume/pom.xml
index 6ac2c1f0..1f1852d9 100644
--- a/zlt-demo/rocketmq-demo/rocketmq-consume/pom.xml
+++ b/zlt-demo/rocketmq-demo/rocketmq-consume/pom.xml
@@ -4,7 +4,7 @@
com.zlt
rocketmq-demo
- 5.6.0
+ 6.0.0
rocketmq-consume
rocketMQ消费者demo
diff --git a/zlt-demo/rocketmq-demo/rocketmq-consume/src/main/java/com/rocketmq/demo/config/RocketMqConfig.java b/zlt-demo/rocketmq-demo/rocketmq-consume/src/main/java/com/rocketmq/demo/config/RocketMqConfig.java
deleted file mode 100644
index d377fc0c..00000000
--- a/zlt-demo/rocketmq-demo/rocketmq-consume/src/main/java/com/rocketmq/demo/config/RocketMqConfig.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package com.rocketmq.demo.config;
-
-import org.springframework.cloud.stream.annotation.EnableBinding;
-import org.springframework.cloud.stream.annotation.Input;
-import com.rocketmq.demo.config.RocketMqConfig.MySink;
-import org.springframework.cloud.stream.messaging.Sink;
-import org.springframework.messaging.SubscribableChannel;
-
-/**
- * @author zlt
- */
-@EnableBinding({MySink.class})
-public class RocketMqConfig {
- public interface MySink {
- @Input(Sink.INPUT)
- SubscribableChannel input();
-
- @Input("input2")
- SubscribableChannel input2();
-
- @Input("input3")
- SubscribableChannel input3();
- }
-}
diff --git a/zlt-demo/rocketmq-demo/rocketmq-consume/src/main/java/com/rocketmq/demo/service/ReceiveService.java b/zlt-demo/rocketmq-demo/rocketmq-consume/src/main/java/com/rocketmq/demo/service/ReceiveService.java
index b27fb358..ac81d7bd 100644
--- a/zlt-demo/rocketmq-demo/rocketmq-consume/src/main/java/com/rocketmq/demo/service/ReceiveService.java
+++ b/zlt-demo/rocketmq-demo/rocketmq-consume/src/main/java/com/rocketmq/demo/service/ReceiveService.java
@@ -2,38 +2,38 @@ package com.rocketmq.demo.service;
import com.rocketmq.demo.model.Order;
-import org.springframework.cloud.stream.annotation.StreamListener;
-import org.springframework.cloud.stream.messaging.Sink;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
-import org.springframework.messaging.handler.annotation.Payload;
-import org.springframework.stereotype.Service;
+
+import java.util.function.Consumer;
/**
* @author zlt
*/
-@Service
+@Configuration
public class ReceiveService {
/**
* 字符串消息
*/
- @StreamListener(Sink.INPUT)
- public void receiveInput(String receiveMsg) {
- System.out.println("input receive: " + receiveMsg);
+ @Bean
+ public Consumer receiveInput() {
+ return receiveMsg -> System.out.println("input receive: " + receiveMsg);
}
/**
* 对象消息
*/
- @StreamListener("input2")
- public void receiveInput2(@Payload Order order) {
- System.out.println("input2 receive: " + order);
+ @Bean
+ public Consumer receiveInput2() {
+ return order -> System.out.println("input2 receive: " + order);
}
/**
* 通过spring.messaging对象来接收消息
*/
- @StreamListener("input3")
- public void receiveInput3(Message msg) {
- System.out.println("input3 receive: " + msg);
- }
+ @Bean
+ public Consumer> receiveInput3() {
+ return msg -> System.out.println("input3 receive: " + msg);
+ }
}
\ No newline at end of file
diff --git a/zlt-demo/rocketmq-demo/rocketmq-consume/src/main/resources/application.yml b/zlt-demo/rocketmq-demo/rocketmq-consume/src/main/resources/application.yml
index 3b839fe4..86c2b8dd 100644
--- a/zlt-demo/rocketmq-demo/rocketmq-consume/src/main/resources/application.yml
+++ b/zlt-demo/rocketmq-demo/rocketmq-consume/src/main/resources/application.yml
@@ -6,34 +6,35 @@ spring:
name: rocketmq-produce
cloud:
stream:
- rocketmq:
- binder:
- # RocketMQ 服务器地址
- name-server: 192.168.28.130:9876
- bindings:
- input2:
- consumer:
- #增加tag过滤
- tags: tagObj
+ function:
+ definition: receiveInput;receiveInput2;receiveInput3
bindings:
- input:
+ receiveInput-in-0:
destination: test-topic
content-type: text/plain
group: consume-group1
consumer:
#并发消费线程数
concurrency: 20
- input2:
+ receiveInput2-in-0:
destination: test-topic
content-type: application/json
group: consume-group2
consumer:
#并发消费线程数
concurrency: 20
- input3:
+ receiveInput3-in-0:
destination: test-topic
content-type: text/plain
group: consume-group3
consumer:
#并发消费线程数
- concurrency: 20
\ No newline at end of file
+ concurrency: 20
+ rocketmq:
+ binder:
+ # RocketMQ 服务器地址
+ name-server: 192.168.28.130:9876
+
+logging:
+ level:
+ org.springframework.context.support: debug
\ No newline at end of file
diff --git a/zlt-demo/rocketmq-demo/rocketmq-produce/pom.xml b/zlt-demo/rocketmq-demo/rocketmq-produce/pom.xml
index 52d570c0..bb8b29a3 100644
--- a/zlt-demo/rocketmq-demo/rocketmq-produce/pom.xml
+++ b/zlt-demo/rocketmq-demo/rocketmq-produce/pom.xml
@@ -4,7 +4,7 @@
com.zlt
rocketmq-demo
- 5.6.0
+ 6.0.0
rocketmq-produce
rocketMQ生产者demo
diff --git a/zlt-demo/rocketmq-demo/rocketmq-produce/src/main/java/com/rocketmq/demo/config/RocketMqConfig.java b/zlt-demo/rocketmq-demo/rocketmq-produce/src/main/java/com/rocketmq/demo/config/RocketMqConfig.java
deleted file mode 100644
index 264a4e50..00000000
--- a/zlt-demo/rocketmq-demo/rocketmq-produce/src/main/java/com/rocketmq/demo/config/RocketMqConfig.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.rocketmq.demo.config;
-
-import org.springframework.cloud.stream.annotation.EnableBinding;
-import org.springframework.cloud.stream.annotation.Output;
-import com.rocketmq.demo.config.RocketMqConfig.MySource;
-import org.springframework.cloud.stream.messaging.Source;
-import org.springframework.messaging.MessageChannel;
-
-/**
- * 配置消息生产者
- *
- * @author zlt
- */
-@EnableBinding({MySource.class})
-public class RocketMqConfig {
- public interface MySource {
- @Output(Source.OUTPUT)
- MessageChannel output();
- }
-}
diff --git a/zlt-demo/rocketmq-demo/rocketmq-produce/src/main/java/com/rocketmq/demo/service/SenderService.java b/zlt-demo/rocketmq-demo/rocketmq-produce/src/main/java/com/rocketmq/demo/service/SenderService.java
index 0e1a16f1..012659ab 100644
--- a/zlt-demo/rocketmq-demo/rocketmq-produce/src/main/java/com/rocketmq/demo/service/SenderService.java
+++ b/zlt-demo/rocketmq-demo/rocketmq-produce/src/main/java/com/rocketmq/demo/service/SenderService.java
@@ -1,37 +1,40 @@
package com.rocketmq.demo.service;
import org.apache.rocketmq.common.message.MessageConst;
-import com.rocketmq.demo.config.RocketMqConfig.MySource;
-import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.MimeTypeUtils;
+import javax.annotation.Resource;
+
/**
* @author zlt
*/
@Service
public class SenderService {
- @Autowired
- private MySource source;
+ private final static String TEST_OUT = "test-out-0";
+
+ @Resource
+ private StreamBridge streamBridge;
/**
* 发送字符消息
*/
public void send(String msg) {
- source.output().send(MessageBuilder.withPayload(msg).build());
+ streamBridge.send(TEST_OUT, MessageBuilder.withPayload(msg).build());
}
/**
* 发送带tag的对象消息
*/
public void sendWithTags(T msg, String tag) {
- Message message = MessageBuilder.withPayload(msg)
+ Message message = MessageBuilder.withPayload(msg)
.setHeader(MessageConst.PROPERTY_TAGS, tag)
.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON)
.build();
- source.output().send(message);
+ streamBridge.send(TEST_OUT, message);
}
}
\ No newline at end of file
diff --git a/zlt-demo/rocketmq-demo/rocketmq-produce/src/main/resources/application.yml b/zlt-demo/rocketmq-demo/rocketmq-produce/src/main/resources/application.yml
index 821fb9fe..3ed79230 100644
--- a/zlt-demo/rocketmq-demo/rocketmq-produce/src/main/resources/application.yml
+++ b/zlt-demo/rocketmq-demo/rocketmq-produce/src/main/resources/application.yml
@@ -6,27 +6,16 @@ spring:
name: rocketmq-produce
cloud:
stream:
+ bindings:
+ test-out-0:
+ destination: test-topic
+ content-type: application/json
+ group: produce-group
rocketmq:
binder:
# RocketMQ 服务地址
name-server: 192.168.28.130:9876
- bindings:
- output:
- producer:
- group: produce-group
- output2:
- producer:
- group: test-group2
- bindings:
- output:
- destination: test-topic
- content-type: application/json
logging:
level:
- org:
- springframework:
- cloud:
- stream:
- binder:
- rocketmq: DEBUG
\ No newline at end of file
+ org.springframework.context.support: debug
\ No newline at end of file
diff --git a/zlt-demo/rocketmq-demo/rocketmq-transactional/pom.xml b/zlt-demo/rocketmq-demo/rocketmq-transactional/pom.xml
index f82b2e2a..b6c570b1 100644
--- a/zlt-demo/rocketmq-demo/rocketmq-transactional/pom.xml
+++ b/zlt-demo/rocketmq-demo/rocketmq-transactional/pom.xml
@@ -4,7 +4,7 @@
com.zlt
rocketmq-demo
- 5.6.0
+ 6.0.0
rocketmq-transactional
rocketMQ事务消息demo
diff --git a/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/java/com/rocketmq/demo/config/RocketMqConfig.java b/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/java/com/rocketmq/demo/config/RocketMqConfig.java
deleted file mode 100644
index c9adc743..00000000
--- a/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/java/com/rocketmq/demo/config/RocketMqConfig.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package com.rocketmq.demo.config;
-
-import org.springframework.cloud.stream.annotation.EnableBinding;
-import org.springframework.cloud.stream.annotation.Input;
-import org.springframework.cloud.stream.messaging.Sink;
-import org.springframework.cloud.stream.messaging.Source;
-import org.springframework.messaging.SubscribableChannel;
-
-import com.rocketmq.demo.config.RocketMqConfig.MySink;
-
-/**
- * @author zlt
- */
-@EnableBinding({ Source.class, MySink.class })
-public class RocketMqConfig {
- public interface MySink {
- @Input(Sink.INPUT)
- SubscribableChannel input();
-
- @Input("inputDlq")
- SubscribableChannel inputDlq();
- }
-}
diff --git a/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/java/com/rocketmq/demo/controller/OrderController.java b/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/java/com/rocketmq/demo/controller/OrderController.java
index 31c9993f..e896b349 100644
--- a/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/java/com/rocketmq/demo/controller/OrderController.java
+++ b/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/java/com/rocketmq/demo/controller/OrderController.java
@@ -3,8 +3,7 @@ package com.rocketmq.demo.controller;
import cn.hutool.core.util.RandomUtil;
import com.central.common.utils.IdGenerator;
import com.rocketmq.demo.model.Order;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.cloud.stream.messaging.Source;
+import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.web.bind.annotation.GetMapping;
@@ -15,11 +14,11 @@ import org.springframework.web.bind.annotation.RestController;
*/
@RestController
public class OrderController {
- private final Source source;
+ private final static String ORDER_OUT = "order-out-0";
+ private final StreamBridge streamBridge;
- @Autowired
- public OrderController(Source source) {
- this.source = source;
+ public OrderController(StreamBridge streamBridge) {
+ this.streamBridge = streamBridge;
}
/**
@@ -31,12 +30,12 @@ public class OrderController {
order.setOrderId(IdGenerator.getId());
order.setOrderNo(RandomUtil.randomString(4));
- Message message = MessageBuilder
+ Message message = MessageBuilder
.withPayload(order)
.setHeader("orderId", order.getOrderId())
.build();
//发送半消息
- source.output().send(message);
+ streamBridge.send(ORDER_OUT, message);
return "下单成功";
}
@@ -49,13 +48,13 @@ public class OrderController {
order.setOrderId(IdGenerator.getId());
order.setOrderNo(RandomUtil.randomString(4));
- Message message = MessageBuilder
+ Message message = MessageBuilder
.withPayload(order)
.setHeader("orderId", order.getOrderId())
.setHeader("produceError", "1")
.build();
//发送半消息
- source.output().send(message);
+ streamBridge.send(ORDER_OUT, message);
return "发送消息失败";
}
@@ -68,13 +67,13 @@ public class OrderController {
order.setOrderId(IdGenerator.getId());
order.setOrderNo(RandomUtil.randomString(4));
- Message message = MessageBuilder
+ Message message = MessageBuilder
.withPayload(order)
.setHeader("orderId", order.getOrderId())
.setHeader("consumeError", "1")
.build();
//发送半消息
- source.output().send(message);
+ streamBridge.send(ORDER_OUT, message);
return "消费消息失败";
}
}
diff --git a/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/java/com/rocketmq/demo/listener/OrderTransactionListenerImpl.java b/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/java/com/rocketmq/demo/listener/OrderTransactionListenerImpl.java
index 103551bc..f161602e 100644
--- a/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/java/com/rocketmq/demo/listener/OrderTransactionListenerImpl.java
+++ b/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/java/com/rocketmq/demo/listener/OrderTransactionListenerImpl.java
@@ -3,31 +3,32 @@ package com.rocketmq.demo.listener;
import com.central.common.utils.JsonUtil;
import com.rocketmq.demo.model.Order;
import com.rocketmq.demo.service.IOrderService;
-import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
-import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
-import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.messaging.Message;
+import jakarta.annotation.Resource;
+import org.apache.rocketmq.client.producer.LocalTransactionState;
+import org.apache.rocketmq.client.producer.TransactionListener;
+import org.apache.rocketmq.common.message.Message;
+import org.apache.rocketmq.common.message.MessageExt;
+import org.springframework.stereotype.Component;
/**
* @author zlt
*/
-@RocketMQTransactionListener(txProducerGroup = "order-tx-produce-group", corePoolSize = 5, maximumPoolSize = 10)
-public class OrderTransactionListenerImpl implements RocketMQLocalTransactionListener {
- @Autowired
+@Component("myTransactionListener")
+public class OrderTransactionListenerImpl implements TransactionListener {
+ @Resource
private IOrderService orderService;
/**
* 提交本地事务
*/
@Override
- public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
+ public LocalTransactionState executeLocalTransaction(Message message, Object arg) {
//插入订单数据
- String orderJson = new String(((byte[])message.getPayload()));
+ String orderJson = new String((message.getBody()));
Order order = JsonUtil.toObject(orderJson, Order.class);
orderService.save(order);
- String produceError = (String)message.getHeaders().get("produceError");
+ String produceError = message.getProperty("produceError");
if ("1".equals(produceError)) {
System.err.println("============Exception:订单进程挂了,事务消息没提交");
//模拟插入订单后服务器挂了,没有commit事务消息
@@ -35,7 +36,7 @@ public class OrderTransactionListenerImpl implements RocketMQLocalTransactionLis
}
//提交事务消息
- return RocketMQLocalTransactionState.COMMIT;
+ return LocalTransactionState.COMMIT_MESSAGE;
}
/**
@@ -46,13 +47,13 @@ public class OrderTransactionListenerImpl implements RocketMQLocalTransactionLis
* 否:回滚事务消息
*/
@Override
- public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
- String orderId = (String)message.getHeaders().get("orderId");
+ public LocalTransactionState checkLocalTransaction(MessageExt message) {
+ String orderId = message.getProperty("orderId");
System.out.println("============事务回查-orderId:" + orderId);
//判断之前的事务是否已经提交:订单记录是否已经保存
int count = 1;
//select count(1) from t_order where order_id = ${orderId}
System.out.println("============事务回查-订单已生成-提交事务消息");
- return count > 0 ? RocketMQLocalTransactionState.COMMIT : RocketMQLocalTransactionState.ROLLBACK;
+ return count > 0 ? LocalTransactionState.COMMIT_MESSAGE : LocalTransactionState.ROLLBACK_MESSAGE;
}
}
\ No newline at end of file
diff --git a/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/java/com/rocketmq/demo/service/impl/IntegralReceiveService.java b/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/java/com/rocketmq/demo/service/impl/IntegralReceiveService.java
index 509ca48b..3277c37b 100644
--- a/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/java/com/rocketmq/demo/service/impl/IntegralReceiveService.java
+++ b/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/java/com/rocketmq/demo/service/impl/IntegralReceiveService.java
@@ -1,36 +1,42 @@
package com.rocketmq.demo.service.impl;
-import org.springframework.cloud.stream.annotation.StreamListener;
-import org.springframework.cloud.stream.messaging.Sink;
+import com.rocketmq.demo.model.Order;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
-import org.springframework.stereotype.Service;
+
+import java.util.function.Consumer;
/**
* 积分服务的消费者,接收到下单成功后增加积分
*
* @author zlt
*/
-@Service
+@Configuration
public class IntegralReceiveService {
- @StreamListener(Sink.INPUT)
- public void receive(Message message) {
- //模拟消费异常
- String consumeError = (String)message.getHeaders().get("consumeError");
- if ("1".equals(consumeError)) {
- System.err.println("============Exception:积分进程挂了,消费消息失败");
- //模拟插入订单后服务器挂了,没有commit事务消息
- throw new RuntimeException("积分服务器挂了");
- }
+ @Bean
+ public Consumer> receive() {
+ return message -> {
+ //模拟消费异常
+ String consumeError = (String)message.getHeaders().get("consumeError");
+ if ("1".equals(consumeError)) {
+ System.err.println("============Exception:积分进程挂了,消费消息失败");
+ //模拟插入订单后服务器挂了,没有commit事务消息
+ throw new RuntimeException("积分服务器挂了");
+ }
- System.out.println("============收到订单信息,增加积分:" + message);
+ System.out.println("============收到订单信息,增加积分:" + message);
+ };
}
/**
* 消费死信队列
*/
- @StreamListener("inputDlq")
- public void receiveDlq(Message message) {
- String orderId = (String)message.getHeaders().get("orderId");
- System.err.println("============消费死信队列消息,记录日志并预警:" + orderId);
+ @Bean
+ public Consumer> receiveDlq() {
+ return message -> {
+ String orderId = (String)message.getHeaders().get("orderId");
+ System.err.println("============消费死信队列消息,记录日志并预警:" + orderId);
+ };
}
}
diff --git a/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/resources/application.yml b/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/resources/application.yml
index 942a82f7..3fccf697 100644
--- a/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/resources/application.yml
+++ b/zlt-demo/rocketmq-demo/rocketmq-transactional/src/main/resources/application.yml
@@ -6,27 +6,16 @@ spring:
name: rocketmq-tx
cloud:
stream:
- rocketmq:
- binder:
- # RocketMQ 服务器地址
- name-server: 192.168.28.130:9876
- bindings:
- output:
- producer:
- group: order-tx-produce-group
- #开启事务消息
- transactional: true
- input:
- consumer:
- #重试失败直接进入死信队列
- delayLevelWhenNextConsume: -1
+ function:
+ definition: receive;receiveDlq
bindings:
# 生产者
- output:
+ order-out-0:
destination: TransactionTopic
content-type: application/json
+ group: order-tx-produce-group
# 消费者
- input:
+ receive-in-0:
destination: TransactionTopic
content-type: application/json
group: order-tx-consume-group
@@ -35,18 +24,27 @@ spring:
concurrency: 20
#重试1次
maxAttempts: 2
- inputDlq:
- destination: '%DLQ%${spring.cloud.stream.bindings.input.group}'
+ receiveDlq-in-0:
+ destination: '%DLQ%${spring.cloud.stream.bindings.receive-in-0.group}'
content-type: application/json
group: order-dlq-group
consumer:
concurrency: 20
+ rocketmq:
+ binder:
+ # RocketMQ 服务器地址
+ name-server: 192.168.28.130:9876
+ bindings:
+ order-out-0:
+ producer:
+ #开启事务消息
+ transactionListener: myTransactionListener
+ producerType: Trans
+ receive-in-0:
+ consumer:
+ #重试失败直接进入死信队列
+ delayLevelWhenNextConsume: -1
logging:
level:
- org:
- springframework:
- cloud:
- stream:
- binder:
- rocketmq: DEBUG
\ No newline at end of file
+ org.springframework.context.support: debug
\ No newline at end of file
diff --git a/zlt-demo/seata-demo/account-service/pom.xml b/zlt-demo/seata-demo/account-service/pom.xml
index 25508c7f..d827e3f0 100644
--- a/zlt-demo/seata-demo/account-service/pom.xml
+++ b/zlt-demo/seata-demo/account-service/pom.xml
@@ -5,7 +5,7 @@
com.zlt
seata-demo
- 5.6.0
+ 6.0.0
account-service
diff --git a/zlt-demo/seata-demo/business-service/pom.xml b/zlt-demo/seata-demo/business-service/pom.xml
index 85172f65..60bfb77a 100644
--- a/zlt-demo/seata-demo/business-service/pom.xml
+++ b/zlt-demo/seata-demo/business-service/pom.xml
@@ -5,7 +5,7 @@
com.zlt
seata-demo
- 5.6.0
+ 6.0.0
business-service
diff --git a/zlt-demo/seata-demo/order-service/pom.xml b/zlt-demo/seata-demo/order-service/pom.xml
index fb1cfd99..b81dbe6a 100644
--- a/zlt-demo/seata-demo/order-service/pom.xml
+++ b/zlt-demo/seata-demo/order-service/pom.xml
@@ -5,7 +5,7 @@
com.zlt
seata-demo
- 5.6.0
+ 6.0.0
order-service
diff --git a/zlt-demo/seata-demo/pom.xml b/zlt-demo/seata-demo/pom.xml
index d85db458..992aa584 100644
--- a/zlt-demo/seata-demo/pom.xml
+++ b/zlt-demo/seata-demo/pom.xml
@@ -4,7 +4,7 @@
com.zlt
zlt-demo
- 5.6.0
+ 6.0.0
seata-demo
seata分布式事务demo
diff --git a/zlt-demo/seata-demo/seata-common-starter/pom.xml b/zlt-demo/seata-demo/seata-common-starter/pom.xml
index 85597476..960cd675 100644
--- a/zlt-demo/seata-demo/seata-common-starter/pom.xml
+++ b/zlt-demo/seata-demo/seata-common-starter/pom.xml
@@ -5,7 +5,7 @@
com.zlt
seata-demo
- 5.6.0
+ 6.0.0
seata-common-starter
diff --git a/zlt-demo/seata-demo/seata-common-starter/src/main/resources/META-INF/spring.factories b/zlt-demo/seata-demo/seata-common-starter/src/main/resources/META-INF/spring.factories
deleted file mode 100644
index 022c67d4..00000000
--- a/zlt-demo/seata-demo/seata-common-starter/src/main/resources/META-INF/spring.factories
+++ /dev/null
@@ -1,2 +0,0 @@
-org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
-com.central.common.config.DataSourceProxyConfig
diff --git a/zlt-demo/seata-demo/seata-common-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/zlt-demo/seata-demo/seata-common-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
new file mode 100644
index 00000000..bcb00450
--- /dev/null
+++ b/zlt-demo/seata-demo/seata-common-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
@@ -0,0 +1 @@
+com.central.common.config.DataSourceProxyConfig
\ No newline at end of file
diff --git a/zlt-demo/seata-demo/storage-service/pom.xml b/zlt-demo/seata-demo/storage-service/pom.xml
index 3a40b972..94ce973d 100644
--- a/zlt-demo/seata-demo/storage-service/pom.xml
+++ b/zlt-demo/seata-demo/storage-service/pom.xml
@@ -5,7 +5,7 @@
com.zlt
seata-demo
- 5.6.0
+ 6.0.0
storage-service
diff --git a/zlt-demo/sharding-jdbc-demo/pom.xml b/zlt-demo/sharding-jdbc-demo/pom.xml
index 2aa24731..5829d861 100644
--- a/zlt-demo/sharding-jdbc-demo/pom.xml
+++ b/zlt-demo/sharding-jdbc-demo/pom.xml
@@ -4,7 +4,7 @@
com.zlt
zlt-demo
- 5.6.0
+ 6.0.0
sharding-jdbc-demo
sharding-jdbc分库分表demo
diff --git a/zlt-demo/sso-demo/oidc-sso/pom.xml b/zlt-demo/sso-demo/oidc-sso/pom.xml
index b85eb082..352b6350 100644
--- a/zlt-demo/sso-demo/oidc-sso/pom.xml
+++ b/zlt-demo/sso-demo/oidc-sso/pom.xml
@@ -4,7 +4,7 @@
com.zlt
sso-demo
- 5.6.0
+ 6.0.0
oidc-sso
OIDC协议单点登录demo
diff --git a/zlt-demo/sso-demo/oidc-sso/src/main/java/com/sso/demo/OidcSSOApplication.java b/zlt-demo/sso-demo/oidc-sso/src/main/java/com/sso/demo/OidcSSOApplication.java
index 1b5b01d8..9f6bfd5c 100644
--- a/zlt-demo/sso-demo/oidc-sso/src/main/java/com/sso/demo/OidcSSOApplication.java
+++ b/zlt-demo/sso-demo/oidc-sso/src/main/java/com/sso/demo/OidcSSOApplication.java
@@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
* @author zlt
* @date 2020/5/22
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@SpringBootApplication
diff --git a/zlt-demo/sso-demo/oidc-sso/src/main/java/com/sso/demo/controller/ApiController.java b/zlt-demo/sso-demo/oidc-sso/src/main/java/com/sso/demo/controller/ApiController.java
index 74103b05..51a8f37e 100644
--- a/zlt-demo/sso-demo/oidc-sso/src/main/java/com/sso/demo/controller/ApiController.java
+++ b/zlt-demo/sso-demo/oidc-sso/src/main/java/com/sso/demo/controller/ApiController.java
@@ -21,9 +21,9 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
-import sun.misc.BASE64Encoder;
+import org.apache.commons.codec.binary.Base64;
-import javax.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.security.interfaces.RSAPublicKey;
import java.util.*;
@@ -32,7 +32,7 @@ import java.util.*;
* @author zlt
* @date 2020/5/22
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@@ -217,8 +217,7 @@ public class ApiController {
*/
private String getBase64ClientParam() {
byte[] authorization = (clientId + ":" + clientSecret).getBytes(StandardCharsets.UTF_8);
- BASE64Encoder encoder = new BASE64Encoder();
- return encoder.encode(authorization);
+ return Base64.encodeBase64String(authorization);
}
@Data
diff --git a/zlt-demo/sso-demo/pom.xml b/zlt-demo/sso-demo/pom.xml
index ff666f52..c3e4afb2 100644
--- a/zlt-demo/sso-demo/pom.xml
+++ b/zlt-demo/sso-demo/pom.xml
@@ -4,7 +4,7 @@
com.zlt
zlt-demo
- 5.6.0
+ 6.0.0
sso-demo
pom
diff --git a/zlt-demo/sso-demo/ss-sso/pom.xml b/zlt-demo/sso-demo/ss-sso/pom.xml
index cbc27268..390a4c28 100644
--- a/zlt-demo/sso-demo/ss-sso/pom.xml
+++ b/zlt-demo/sso-demo/ss-sso/pom.xml
@@ -4,7 +4,7 @@
com.zlt
sso-demo
- 5.6.0
+ 6.0.0
ss-sso
springSecurity单点登录demo
diff --git a/zlt-demo/sso-demo/ss-sso/src/main/java/com/sso/demo/SSOApplication.java b/zlt-demo/sso-demo/ss-sso/src/main/java/com/sso/demo/SSOApplication.java
index 8213348d..8cecba0b 100644
--- a/zlt-demo/sso-demo/ss-sso/src/main/java/com/sso/demo/SSOApplication.java
+++ b/zlt-demo/sso-demo/ss-sso/src/main/java/com/sso/demo/SSOApplication.java
@@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
* @author zlt
* @date 2020/2/22
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@SpringBootApplication
diff --git a/zlt-demo/sso-demo/ss-sso/src/main/java/com/sso/demo/config/SecurityConfig.java b/zlt-demo/sso-demo/ss-sso/src/main/java/com/sso/demo/config/SecurityConfig.java
index e3d4e19a..838e54b7 100644
--- a/zlt-demo/sso-demo/ss-sso/src/main/java/com/sso/demo/config/SecurityConfig.java
+++ b/zlt-demo/sso-demo/ss-sso/src/main/java/com/sso/demo/config/SecurityConfig.java
@@ -3,9 +3,10 @@ package com.sso.demo.config;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
+import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
-import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import javax.annotation.Resource;
@@ -16,27 +17,28 @@ import javax.annotation.Resource;
* @author zlt
* @date 2020/2/22
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@EnableOAuth2Sso
@Configuration
-public class SecurityConfig extends WebSecurityConfigurerAdapter {
+public class SecurityConfig {
@Value("${security.oauth2.sso.login-path:}")
private String loginPath;
@Resource
private LogoutSuccessHandler ssoLogoutSuccessHandler;
- @Override
- public void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests().anyRequest().authenticated()
+ @Bean
+ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
+ /*http.authorizeHttpRequests().anyRequest().authenticated()
.and()
.csrf().disable()
.logout()
.logoutSuccessHandler(ssoLogoutSuccessHandler);
if (StrUtil.isNotEmpty(loginPath)) {
http.formLogin().loginProcessingUrl(loginPath);
- }
+ }*/
+ return http.build();
}
}
\ No newline at end of file
diff --git a/zlt-demo/sso-demo/ss-sso/src/main/java/com/sso/demo/config/SsoLogoutSuccessHandler.java b/zlt-demo/sso-demo/ss-sso/src/main/java/com/sso/demo/config/SsoLogoutSuccessHandler.java
index 4a591500..658e343b 100644
--- a/zlt-demo/sso-demo/ss-sso/src/main/java/com/sso/demo/config/SsoLogoutSuccessHandler.java
+++ b/zlt-demo/sso-demo/ss-sso/src/main/java/com/sso/demo/config/SsoLogoutSuccessHandler.java
@@ -9,8 +9,8 @@ import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
@@ -19,7 +19,7 @@ import java.io.IOException;
* @author zlt
* @date 2020/3/10
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Component
diff --git a/zlt-demo/sso-demo/ss-sso/src/main/java/com/sso/demo/controller/HomeController.java b/zlt-demo/sso-demo/ss-sso/src/main/java/com/sso/demo/controller/HomeController.java
index c6c485c1..92ad88e8 100644
--- a/zlt-demo/sso-demo/ss-sso/src/main/java/com/sso/demo/controller/HomeController.java
+++ b/zlt-demo/sso-demo/ss-sso/src/main/java/com/sso/demo/controller/HomeController.java
@@ -11,7 +11,7 @@ import org.springframework.web.bind.annotation.GetMapping;
* @author zlt
* @date 2020/2/22
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Controller
diff --git a/zlt-demo/sso-demo/web-sso/pom.xml b/zlt-demo/sso-demo/web-sso/pom.xml
index 190fdbf8..02b67884 100644
--- a/zlt-demo/sso-demo/web-sso/pom.xml
+++ b/zlt-demo/sso-demo/web-sso/pom.xml
@@ -4,7 +4,7 @@
com.zlt
sso-demo
- 5.6.0
+ 6.0.0
web-sso
前后端分离单点登录demo
@@ -22,6 +22,10 @@
org.springframework.cloud
spring-cloud-context
+
+ commons-codec
+ commons-codec
+
diff --git a/zlt-demo/sso-demo/web-sso/src/main/java/com/sso/demo/WebSSOApplication.java b/zlt-demo/sso-demo/web-sso/src/main/java/com/sso/demo/WebSSOApplication.java
index b8551789..4716a0ba 100644
--- a/zlt-demo/sso-demo/web-sso/src/main/java/com/sso/demo/WebSSOApplication.java
+++ b/zlt-demo/sso-demo/web-sso/src/main/java/com/sso/demo/WebSSOApplication.java
@@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
* @author zlt
* @date 2020/3/10
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@SpringBootApplication
diff --git a/zlt-demo/sso-demo/web-sso/src/main/java/com/sso/demo/controller/ApiController.java b/zlt-demo/sso-demo/web-sso/src/main/java/com/sso/demo/controller/ApiController.java
index b5b05066..b9f4b558 100644
--- a/zlt-demo/sso-demo/web-sso/src/main/java/com/sso/demo/controller/ApiController.java
+++ b/zlt-demo/sso-demo/web-sso/src/main/java/com/sso/demo/controller/ApiController.java
@@ -14,9 +14,9 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
-import sun.misc.BASE64Encoder;
+import org.apache.commons.codec.binary.Base64;
-import javax.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.*;
@@ -24,7 +24,7 @@ import java.util.*;
* @author zlt
* @date 2020/3/10
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@@ -73,8 +73,7 @@ public class ApiController {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
byte[] authorization = (clientId + ":" + clientSecret).getBytes("UTF-8");
- BASE64Encoder encoder = new BASE64Encoder();
- String base64Auth = encoder.encode(authorization);
+ String base64Auth = Base64.encodeBase64String(authorization);
headers.add("Authorization", "Basic " + base64Auth);
MultiValueMap param = new LinkedMultiValueMap<>();
diff --git a/zlt-demo/txlcn-demo/README.md b/zlt-demo/txlcn-demo/README.md
deleted file mode 100644
index 73cbd85d..00000000
--- a/zlt-demo/txlcn-demo/README.md
+++ /dev/null
@@ -1,48 +0,0 @@
-[TOC]
-
-## 一、说明
-
-本demo是通过tx-lcn测试lcn模式的分布式事务,主要是模拟以下两个场景
-
-1. `service-a` 调用`service-b`调用`service-c` 都成功
-2. `service-a` 调用`service-b`调用`service-c` 最后`service-a`抛出异常全部回滚
-
-
-
-
-
-## 二、运行步骤
-
-### 1. 初始化TxManager的数据
-
-执行`zlt-doc\sql\tx-manager.sql`和`zlt-doc\sql\tx_logger.sql`脚本
-
-### 2. 修改TxManager的配置
-
-工程目录:`zlt-transaction\txlcn-tm`,修改nacos、数据库和redis
-
-### 2. 启动TxManager
-
-工程目录:`zlt-transaction\txlcn-tm`
-
-### 3. 初始化demo的数据
-
-执行`zlt-demo\txlcn-demo\txlcn-demo.sql`脚本
-
-### 4. 修改3个服务的配置
-
-`nacos`地址和数据库地址
-
-
-
-
-
-## 三、启动模块与测试
-
-### 1. 正常提交事务
-访问 发起方提供的Rest接口 `/txlcn?value=the-value`。发现事务全部提交
-
-
-### 2. 回滚事务
-访问 发起方提供的Rest接口 `/txlcn?value=the-value&ex=throw`。发现发起方由本地事务回滚,而参与方ServiceB、ServiceC,由于TX-LCN的协调,数据也回滚了。
-
\ No newline at end of file
diff --git a/zlt-demo/txlcn-demo/pom.xml b/zlt-demo/txlcn-demo/pom.xml
deleted file mode 100644
index 494d258c..00000000
--- a/zlt-demo/txlcn-demo/pom.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-
- 4.0.0
-
- com.zlt
- zlt-demo
- 5.6.0
-
- txlcn-demo
- txlcn分布式事务demo
- pom
-
-
- txlcn-demo-common
-
- txlcn-demo-spring-service-a
-
- txlcn-demo-spring-service-b
-
- txlcn-demo-spring-service-c
-
-
\ No newline at end of file
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-common/pom.xml b/zlt-demo/txlcn-demo/txlcn-demo-common/pom.xml
deleted file mode 100644
index c3f6c452..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-common/pom.xml
+++ /dev/null
@@ -1,69 +0,0 @@
-
- 4.0.0
-
- com.zlt
- txlcn-demo
- 5.6.0
-
- txlcn-demo-common
- demo-common
- demo-common project for Spring Boot
-
-
-
- com.codingapi.txlcn
- txlcn-tc
-
-
- com.codingapi.txlcn
- txlcn-txmsg-netty
-
-
-
- com.zlt
- zlt-config
-
-
- com.alibaba.cloud
- spring-cloud-starter-alibaba-nacos-config
-
-
-
-
- com.zlt
- zlt-log-spring-boot-starter
-
-
- com.zlt
- zlt-db-spring-boot-starter
-
-
- com.zlt
- zlt-loadbalancer-spring-boot-starter
-
-
- com.zlt
- zlt-sentinel-spring-boot-starter
-
-
-
- com.alibaba.cloud
- spring-cloud-starter-alibaba-nacos-discovery
-
-
- mysql
- mysql-connector-java
-
-
-
- org.springframework.boot
- spring-boot-starter-actuator
-
-
-
- org.springframework.boot
- spring-boot-starter-web
-
-
-
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-common/src/main/java/org/txlcn/demo/common/db/domain/Demo.java b/zlt-demo/txlcn-demo/txlcn-demo-common/src/main/java/org/txlcn/demo/common/db/domain/Demo.java
deleted file mode 100644
index 6178c976..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-common/src/main/java/org/txlcn/demo/common/db/domain/Demo.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package org.txlcn.demo.common.db.domain;
-
-import com.codingapi.txlcn.common.util.id.RandomUtils;
-import lombok.AllArgsConstructor;
-import lombok.Data;
-import lombok.NoArgsConstructor;
-
-import java.util.Date;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-@AllArgsConstructor
-@NoArgsConstructor
-@Data
-public class Demo {
- private Long id;
- private String kid = RandomUtils.randomKey();
- private String demoField;
- private String groupId;
- private Date createTime;
- private String appName;
-
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-common/src/main/java/org/txlcn/demo/common/db/mapper/BaseDemoMapper.java b/zlt-demo/txlcn-demo/txlcn-demo-common/src/main/java/org/txlcn/demo/common/db/mapper/BaseDemoMapper.java
deleted file mode 100644
index 9f925a0b..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-common/src/main/java/org/txlcn/demo/common/db/mapper/BaseDemoMapper.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package org.txlcn.demo.common.db.mapper;
-
-import org.txlcn.demo.common.db.domain.Demo;
-import org.apache.ibatis.annotations.Delete;
-import org.apache.ibatis.annotations.Insert;
-import org.apache.ibatis.annotations.Mapper;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-@Mapper
-public interface BaseDemoMapper {
-
- @Insert("insert into t_demo(kid, demo_field, group_id, create_time,app_name) values(#{kid}, #{demoField}, #{groupId}, #{createTime},#{appName})")
- void save(Demo demo);
-
- @Delete("delete from t_demo where id=#{id}")
- void deleteById(Long id);
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-common/src/main/java/org/txlcn/demo/common/spring/FeignConfiguration.java b/zlt-demo/txlcn-demo/txlcn-demo-common/src/main/java/org/txlcn/demo/common/spring/FeignConfiguration.java
deleted file mode 100644
index df3148df..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-common/src/main/java/org/txlcn/demo/common/spring/FeignConfiguration.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package org.txlcn.demo.common.spring;
-
-import org.springframework.cloud.openfeign.EnableFeignClients;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-@ComponentScan
-@Configuration
-@EnableFeignClients
-public class FeignConfiguration {
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-common/src/main/java/org/txlcn/demo/common/spring/ServiceBClient.java b/zlt-demo/txlcn-demo/txlcn-demo-common/src/main/java/org/txlcn/demo/common/spring/ServiceBClient.java
deleted file mode 100644
index bee92637..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-common/src/main/java/org/txlcn/demo/common/spring/ServiceBClient.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package org.txlcn.demo.common.spring;
-
-import org.springframework.cloud.openfeign.FeignClient;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-@FeignClient(value = "txlcn-demo-spring-service-b")
-public interface ServiceBClient {
-
- @GetMapping("/rpc")
- String rpc(@RequestParam("value") String name);
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-common/src/main/java/org/txlcn/demo/common/spring/ServiceCClient.java b/zlt-demo/txlcn-demo/txlcn-demo-common/src/main/java/org/txlcn/demo/common/spring/ServiceCClient.java
deleted file mode 100644
index 7c9cb023..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-common/src/main/java/org/txlcn/demo/common/spring/ServiceCClient.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package org.txlcn.demo.common.spring;
-
-import org.springframework.cloud.openfeign.FeignClient;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-@FeignClient(value = "txlcn-demo-spring-service-c")
-public interface ServiceCClient {
-
- @GetMapping("/rpc")
- String rpc(@RequestParam("value") String name);
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-common/src/main/resources/META-INF/spring.factories b/zlt-demo/txlcn-demo/txlcn-demo-common/src/main/resources/META-INF/spring.factories
deleted file mode 100644
index 086747a2..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-common/src/main/resources/META-INF/spring.factories
+++ /dev/null
@@ -1 +0,0 @@
-org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.txlcn.demo.common.spring.FeignConfiguration
\ No newline at end of file
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/pom.xml b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/pom.xml
deleted file mode 100644
index da9b422d..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/pom.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
- com.zlt
- txlcn-demo
- 5.6.0
-
- 4.0.0
-
- txlcn-demo-spring-service-a
- txlcn-demo-spring-service-a
-
-
-
- com.zlt
- txlcn-demo-common
- ${project.version}
-
-
-
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
-
-
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/java/org/txlcn/demo/ServiceAApplication.java b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/java/org/txlcn/demo/ServiceAApplication.java
deleted file mode 100644
index cdbd24a5..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/java/org/txlcn/demo/ServiceAApplication.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package org.txlcn.demo;
-
-import com.central.common.lb.annotation.EnableFeignInterceptor;
-import com.codingapi.txlcn.tc.config.EnableDistributedTransaction;
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-@SpringBootApplication
-@EnableDiscoveryClient
-@EnableDistributedTransaction
-@EnableFeignInterceptor
-public class ServiceAApplication {
- public static void main(String[] args) {
- SpringApplication.run(ServiceAApplication.class, args);
- }
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/java/org/txlcn/demo/servicea/DemoController.java b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/java/org/txlcn/demo/servicea/DemoController.java
deleted file mode 100644
index 3d75f2bc..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/java/org/txlcn/demo/servicea/DemoController.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package org.txlcn.demo.servicea;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-@RestController
-public class DemoController {
-
- private final DemoService demoService;
-
- @Autowired
- public DemoController(DemoService demoService) {
- this.demoService = demoService;
- }
-
- @RequestMapping("/txlcn")
- public String execute(@RequestParam("value") String value, @RequestParam(value = "ex", required = false) String exFlag
- , @RequestParam(value = "f", required = false) String flag) {
- return demoService.execute(value, exFlag, flag);
- }
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/java/org/txlcn/demo/servicea/DemoMapper.java b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/java/org/txlcn/demo/servicea/DemoMapper.java
deleted file mode 100644
index caeed6f4..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/java/org/txlcn/demo/servicea/DemoMapper.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package org.txlcn.demo.servicea;
-
-import org.apache.ibatis.annotations.Mapper;
-import org.txlcn.demo.common.db.mapper.BaseDemoMapper;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-@Mapper
-public interface DemoMapper extends BaseDemoMapper {
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/java/org/txlcn/demo/servicea/DemoService.java b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/java/org/txlcn/demo/servicea/DemoService.java
deleted file mode 100644
index a3d20e8e..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/java/org/txlcn/demo/servicea/DemoService.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package org.txlcn.demo.servicea;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-public interface DemoService {
-
- String execute(String value, String ex, String flag);
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/java/org/txlcn/demo/servicea/DemoServiceImpl.java b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/java/org/txlcn/demo/servicea/DemoServiceImpl.java
deleted file mode 100644
index 366fde3b..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/java/org/txlcn/demo/servicea/DemoServiceImpl.java
+++ /dev/null
@@ -1,55 +0,0 @@
-package org.txlcn.demo.servicea;
-
-import com.codingapi.txlcn.common.util.Transactions;
-import com.codingapi.txlcn.tc.annotation.LcnTransaction;
-import com.codingapi.txlcn.tracing.TracingContext;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-import org.txlcn.demo.common.db.domain.Demo;
-import org.txlcn.demo.common.spring.ServiceBClient;
-import org.txlcn.demo.common.spring.ServiceCClient;
-
-import javax.annotation.Resource;
-import java.util.Date;
-import java.util.Objects;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-@Service
-@Slf4j
-public class DemoServiceImpl implements DemoService {
- @Resource
- private DemoMapper demoMapper;
- @Resource
- private ServiceBClient serviceBClient;
- @Resource
- private ServiceCClient serviceCClient;
-
- @LcnTransaction
- @Transactional(rollbackFor = Exception.class)
- @Override
- public String execute(String value, String exFlag, String flag) {
- String dResp = serviceBClient.rpc(value);
- // step2. call remote ServiceB
- String eResp = serviceCClient.rpc(value);
- // step3. execute local transaction
- Demo demo = new Demo();
- demo.setGroupId(TracingContext.tracing().groupId());
- demo.setDemoField(value);
- demo.setCreateTime(new Date());
- demo.setAppName(Transactions.getApplicationId());
- demoMapper.save(demo);
-
- // 置异常标志,DTX 回滚
- if (Objects.nonNull(exFlag)) {
- throw new IllegalStateException("by exFlag");
- }
-
- return dResp + " > " + eResp + " > " + "ok-service-a";
- }
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/resources/application.yml b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/resources/application.yml
deleted file mode 100644
index 7133edbd..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/resources/application.yml
+++ /dev/null
@@ -1,25 +0,0 @@
-spring:
- datasource:
- driver-class-name: com.mysql.cj.jdbc.Driver
- url: jdbc:mysql://${zlt.datasource.ip}:3306/txlcn-demo?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull
- username: ${zlt.datasource.username}
- password: ${zlt.datasource.password}
-
-## tx-manager 配置
-tx-lcn:
- ribbon:
- loadbalancer:
- dtx:
- enabled: true
- logger:
- enabled: true
- driver-class-name: com.mysql.cj.jdbc.Driver
- jdbc-url: jdbc:mysql://${zlt.datasource.ip}:3306/tx_logger?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull
- username: ${zlt.datasource.username}
- password: ${zlt.datasource.password}
-zlt:
- loadbalance:
- version: test
- isolation:
- enabled: true
- chooser: com.central.common.lb.chooser.RandomRuleChooser
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/resources/bootstrap.yml b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/resources/bootstrap.yml
deleted file mode 100644
index 288bff66..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-a/src/main/resources/bootstrap.yml
+++ /dev/null
@@ -1,6 +0,0 @@
-server:
- port: 12011
-
-spring:
- application:
- name: txlcn-demo-spring-service-a
\ No newline at end of file
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/pom.xml b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/pom.xml
deleted file mode 100644
index 3b3ddbf4..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/pom.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-
-
- com.zlt
- txlcn-demo
- 5.6.0
-
- 4.0.0
- txlcn-demo-spring-service-b
- txlcn-demo-spring-service-b
-
-
-
- com.zlt
- txlcn-demo-common
- ${project.version}
-
-
-
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
-
-
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/java/org/txlcn/demo/ServiceBApplication.java b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/java/org/txlcn/demo/ServiceBApplication.java
deleted file mode 100644
index a2ba3e6d..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/java/org/txlcn/demo/ServiceBApplication.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package org.txlcn.demo;
-
-import com.codingapi.txlcn.tc.config.EnableDistributedTransaction;
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-@SpringBootApplication
-@EnableDiscoveryClient
-@EnableDistributedTransaction
-public class ServiceBApplication {
- public static void main(String[] args) {
- SpringApplication.run(ServiceBApplication.class, args);
- }
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/java/org/txlcn/demo/serviceb/DemoController.java b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/java/org/txlcn/demo/serviceb/DemoController.java
deleted file mode 100644
index a6ede52a..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/java/org/txlcn/demo/serviceb/DemoController.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package org.txlcn.demo.serviceb;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
-
-import javax.servlet.http.HttpServletRequest;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-@RestController
-public class DemoController {
-
- @Autowired
- private DemoService demoService;
-
- @GetMapping("/rpc")
- public String rpc(@RequestParam("value") String value, HttpServletRequest servletRequest) {
- return demoService.rpc(value);
- }
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/java/org/txlcn/demo/serviceb/DemoMapper.java b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/java/org/txlcn/demo/serviceb/DemoMapper.java
deleted file mode 100644
index a0453e25..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/java/org/txlcn/demo/serviceb/DemoMapper.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package org.txlcn.demo.serviceb;
-
-import org.apache.ibatis.annotations.Mapper;
-import org.txlcn.demo.common.db.mapper.BaseDemoMapper;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-@Mapper
-public interface DemoMapper extends BaseDemoMapper {
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/java/org/txlcn/demo/serviceb/DemoService.java b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/java/org/txlcn/demo/serviceb/DemoService.java
deleted file mode 100644
index 586e56d9..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/java/org/txlcn/demo/serviceb/DemoService.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package org.txlcn.demo.serviceb;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-public interface DemoService {
-
- String rpc(String value);
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/java/org/txlcn/demo/serviceb/DemoServiceImpl.java b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/java/org/txlcn/demo/serviceb/DemoServiceImpl.java
deleted file mode 100644
index c26e3ddc..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/java/org/txlcn/demo/serviceb/DemoServiceImpl.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package org.txlcn.demo.serviceb;
-
-import com.codingapi.txlcn.common.util.Transactions;
-import com.codingapi.txlcn.tc.annotation.DTXPropagation;
-import com.codingapi.txlcn.tc.annotation.LcnTransaction;
-import com.codingapi.txlcn.tc.annotation.TxcTransaction;
-import com.codingapi.txlcn.tracing.TracingContext;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-import org.txlcn.demo.common.db.domain.Demo;
-
-import javax.annotation.Resource;
-import java.util.Date;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-@Service
-@Slf4j
-public class DemoServiceImpl implements DemoService {
- @Resource
- private DemoMapper demoMapper;
-
- @Override
- @LcnTransaction
- @Transactional(rollbackFor = Exception.class)
- public String rpc(String value) {
- Demo demo = new Demo();
- demo.setGroupId(TracingContext.tracing().groupId());
- demo.setDemoField(value);
- demo.setAppName(Transactions.getApplicationId());
- demo.setCreateTime(new Date());
- demoMapper.save(demo);
- return "ok-service-b";
- }
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/resources/application.yml b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/resources/application.yml
deleted file mode 100644
index 68d7e81d..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/resources/application.yml
+++ /dev/null
@@ -1,24 +0,0 @@
-spring:
- datasource:
- driver-class-name: com.mysql.cj.jdbc.Driver
- url: jdbc:mysql://${zlt.datasource.ip}:3306/txlcn-demo?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull
- username: ${zlt.datasource.username}
- password: ${zlt.datasource.password}
-
-## tx-manager 配置
-tx-lcn:
- ribbon:
- loadbalancer:
- dtx:
- enabled: true
- logger:
- enabled: true
- driver-class-name: com.mysql.cj.jdbc.Driver
- jdbc-url: jdbc:mysql://${zlt.datasource.ip}:3306/tx_logger?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull
- username: ${zlt.datasource.username}
- password: ${zlt.datasource.password}
-zlt:
- loadbalance:
- version: test
- isolation:
- enabled: true
\ No newline at end of file
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/resources/bootstrap.yml b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/resources/bootstrap.yml
deleted file mode 100644
index c3d532dc..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-b/src/main/resources/bootstrap.yml
+++ /dev/null
@@ -1,6 +0,0 @@
-server:
- port: 12002
-
-spring:
- application:
- name: txlcn-demo-spring-service-b
\ No newline at end of file
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/pom.xml b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/pom.xml
deleted file mode 100644
index 38ba0aaa..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/pom.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-
-
- com.zlt
- txlcn-demo
- 5.6.0
-
- 4.0.0
- txlcn-demo-spring-service-c
- txlcn-demo-spring-service-c
-
-
-
- com.zlt
- txlcn-demo-common
- ${project.version}
-
-
-
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
-
-
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/java/org/txlcn/demo/ServiceCApplication.java b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/java/org/txlcn/demo/ServiceCApplication.java
deleted file mode 100644
index fb0c4058..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/java/org/txlcn/demo/ServiceCApplication.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package org.txlcn.demo;
-
-import com.codingapi.txlcn.tc.config.EnableDistributedTransaction;
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-@SpringBootApplication
-@EnableDiscoveryClient
-@EnableDistributedTransaction
-public class ServiceCApplication {
- public static void main(String[] args) {
- SpringApplication.run(ServiceCApplication.class, args);
- }
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/java/org/txlcn/demo/servicec/DemoController.java b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/java/org/txlcn/demo/servicec/DemoController.java
deleted file mode 100644
index dc2ae653..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/java/org/txlcn/demo/servicec/DemoController.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package org.txlcn.demo.servicec;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-@RestController
-public class DemoController {
-
- @Autowired
- private DemoService demoService;
-
- @GetMapping("/rpc")
- public String rpc(@RequestParam("value") String value) {
- return demoService.rpc(value);
- }
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/java/org/txlcn/demo/servicec/DemoMapper.java b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/java/org/txlcn/demo/servicec/DemoMapper.java
deleted file mode 100644
index 4b7747e7..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/java/org/txlcn/demo/servicec/DemoMapper.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package org.txlcn.demo.servicec;
-
-import org.apache.ibatis.annotations.Mapper;
-import org.txlcn.demo.common.db.mapper.BaseDemoMapper;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-@Mapper
-public interface DemoMapper extends BaseDemoMapper {
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/java/org/txlcn/demo/servicec/DemoService.java b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/java/org/txlcn/demo/servicec/DemoService.java
deleted file mode 100644
index 3be9ce68..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/java/org/txlcn/demo/servicec/DemoService.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package org.txlcn.demo.servicec;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-public interface DemoService {
-
- String rpc(String value);
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/java/org/txlcn/demo/servicec/DemoServiceImpl.java b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/java/org/txlcn/demo/servicec/DemoServiceImpl.java
deleted file mode 100644
index c137f302..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/java/org/txlcn/demo/servicec/DemoServiceImpl.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package org.txlcn.demo.servicec;
-
-import com.codingapi.txlcn.common.util.Transactions;
-import com.codingapi.txlcn.tc.annotation.DTXPropagation;
-import com.codingapi.txlcn.tc.annotation.LcnTransaction;
-import com.codingapi.txlcn.tc.annotation.TccTransaction;
-import com.codingapi.txlcn.tc.support.DTXUserControls;
-import com.codingapi.txlcn.tracing.TracingContext;
-import com.google.common.collect.Sets;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-import org.txlcn.demo.common.db.domain.Demo;
-
-import javax.annotation.Resource;
-import java.util.Date;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * Description:
- * Date: 2018/12/25
- *
- * @author ujued
- */
-@Service
-@Slf4j
-public class DemoServiceImpl implements DemoService {
- @Resource
- private DemoMapper demoMapper;
-
- @Override
- @LcnTransaction
- @Transactional(rollbackFor = Exception.class)
- public String rpc(String value) {
- Demo demo = new Demo();
- demo.setDemoField(value);
- demo.setCreateTime(new Date());
- demo.setAppName(Transactions.getApplicationId());
- demo.setGroupId(TracingContext.tracing().groupId());
- demoMapper.save(demo);
- if ("456".equals(value)) {
- throw new IllegalStateException("by test");
- }
- return "ok-service-c";
- }
-}
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/resources/application.yml b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/resources/application.yml
deleted file mode 100644
index cd402049..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/resources/application.yml
+++ /dev/null
@@ -1,19 +0,0 @@
-spring:
- datasource:
- driver-class-name: com.mysql.cj.jdbc.Driver
- url: jdbc:mysql://${zlt.datasource.ip}:3306/txlcn-demo?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull
- username: ${zlt.datasource.username}
- password: ${zlt.datasource.password}
-
-## tx-manager 配置
-tx-lcn:
- ribbon:
- loadbalancer:
- dtx:
- enabled: true
- logger:
- enabled: true
- driver-class-name: com.mysql.cj.jdbc.Driver
- jdbc-url: jdbc:mysql://${zlt.datasource.ip}:3306/tx_logger?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull
- username: ${zlt.datasource.username}
- password: ${zlt.datasource.password}
\ No newline at end of file
diff --git a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/resources/bootstrap.yml b/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/resources/bootstrap.yml
deleted file mode 100644
index e3bb0cb0..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo-spring-service-c/src/main/resources/bootstrap.yml
+++ /dev/null
@@ -1,6 +0,0 @@
-server:
- port: 12003
-
-spring:
- application:
- name: txlcn-demo-spring-service-c
\ No newline at end of file
diff --git a/zlt-demo/txlcn-demo/txlcn-demo.sql b/zlt-demo/txlcn-demo/txlcn-demo.sql
deleted file mode 100644
index a74c9564..00000000
--- a/zlt-demo/txlcn-demo/txlcn-demo.sql
+++ /dev/null
@@ -1,23 +0,0 @@
---
--- Current Database: `txlcn-demo`
---
-
-CREATE DATABASE `txlcn-demo` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-
-USE `txlcn-demo`;
-
---
--- Table structure for table `t_demo`
---
-
-DROP TABLE IF EXISTS `t_demo`;
-CREATE TABLE `t_demo` (
- `id` bigint(20) NOT NULL AUTO_INCREMENT,
- `kid` varchar(45) DEFAULT NULL,
- `demo_field` varchar(255) DEFAULT NULL,
- `group_id` varchar(64) DEFAULT NULL,
- `unit_id` varchar(32) DEFAULT NULL,
- `app_name` varchar(128) DEFAULT NULL,
- `create_time` datetime DEFAULT NULL,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
diff --git a/zlt-demo/websocket-demo/pom.xml b/zlt-demo/websocket-demo/pom.xml
index 5826519c..eb4dc911 100644
--- a/zlt-demo/websocket-demo/pom.xml
+++ b/zlt-demo/websocket-demo/pom.xml
@@ -6,7 +6,7 @@
com.zlt
zlt-demo
- 5.6.0
+ 6.0.0
websocket-demo
diff --git a/zlt-demo/websocket-demo/src/main/java/org/zlt/WebSocketApp.java b/zlt-demo/websocket-demo/src/main/java/org/zlt/WebSocketApp.java
index bab8a72c..c6dd2246 100644
--- a/zlt-demo/websocket-demo/src/main/java/org/zlt/WebSocketApp.java
+++ b/zlt-demo/websocket-demo/src/main/java/org/zlt/WebSocketApp.java
@@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
* @author zlt
* @date 2022/5/8
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@SpringBootApplication
diff --git a/zlt-demo/websocket-demo/src/main/java/org/zlt/config/MyResourceConfig.java b/zlt-demo/websocket-demo/src/main/java/org/zlt/config/MyResourceConfig.java
index 93a4f3ff..6a4ac97a 100644
--- a/zlt-demo/websocket-demo/src/main/java/org/zlt/config/MyResourceConfig.java
+++ b/zlt-demo/websocket-demo/src/main/java/org/zlt/config/MyResourceConfig.java
@@ -1,8 +1,6 @@
package org.zlt.config;
-import com.central.oauth2.common.config.DefaultResourceServerConf;
import org.springframework.context.annotation.Configuration;
-import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
/**
* security资源服务器配置
@@ -11,10 +9,12 @@ import org.springframework.security.oauth2.config.annotation.web.configuration.E
* @version 1.0
* @date 2022/5/9
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
+/*
@Configuration
@EnableResourceServer
public class MyResourceConfig extends DefaultResourceServerConf {
}
+*/
diff --git a/zlt-demo/websocket-demo/src/main/java/org/zlt/config/WebSocketConfig.java b/zlt-demo/websocket-demo/src/main/java/org/zlt/config/WebSocketConfig.java
index c25ef1c7..3dcbe65b 100644
--- a/zlt-demo/websocket-demo/src/main/java/org/zlt/config/WebSocketConfig.java
+++ b/zlt-demo/websocket-demo/src/main/java/org/zlt/config/WebSocketConfig.java
@@ -11,7 +11,7 @@ import org.springframework.web.socket.server.standard.ServerEndpointExporter;
* @version 1.0
* @date 2022/5/8
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Configuration
diff --git a/zlt-demo/websocket-demo/src/main/java/org/zlt/controller/TestWebSocketController.java b/zlt-demo/websocket-demo/src/main/java/org/zlt/controller/TestWebSocketController.java
index d14f94d3..d384018a 100644
--- a/zlt-demo/websocket-demo/src/main/java/org/zlt/controller/TestWebSocketController.java
+++ b/zlt-demo/websocket-demo/src/main/java/org/zlt/controller/TestWebSocketController.java
@@ -1,19 +1,19 @@
package org.zlt.controller;
import com.central.oauth2.common.config.WcAuthConfigurator;
+import jakarta.websocket.OnOpen;
+import jakarta.websocket.Session;
+import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
-import javax.websocket.OnOpen;
-import javax.websocket.Session;
-import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
/**
* @author zlt
* @date 2022/5/8
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
diff --git a/zlt-doc/sql/oauth-center.sql b/zlt-doc/sql/oauth-center.sql
index 627de1d8..a5715580 100644
--- a/zlt-doc/sql/oauth-center.sql
+++ b/zlt-doc/sql/oauth-center.sql
@@ -22,8 +22,7 @@ CREATE TABLE `oauth_client_details` (
`create_time` datetime(0) NULL DEFAULT NULL,
`update_time` datetime(0) NULL DEFAULT NULL,
`client_name` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT '' COMMENT '应用名称',
- `support_id_token` tinyint(1) DEFAULT 1 COMMENT '是否支持id_token',
- `id_token_validity` int(11) DEFAULT 60 COMMENT 'id_token有效期',
+ `token_format` varchar(20) not null DEFAULT 'reference' COMMENT 'token格式: reference 引用令牌(不透明), self-contained 自包含令牌(jwt))',
`creator_id` int(11) COMMENT '创建人id',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
@@ -31,6 +30,6 @@ CREATE TABLE `oauth_client_details` (
-- ----------------------------
-- Records of oauth_client_details
-- ----------------------------
-INSERT INTO `oauth_client_details` VALUES (1, 'webApp', NULL, '$2a$10$06msMGYRH8nrm4iVnKFNKOoddB8wOwymVhbUzw/d3ZixD7Nq8ot72', 'webApp', 'app', 'authorization_code,password,refresh_token,client_credentials,implicit,password_code,openId,mobile_password', 'http://127.0.0.1:8082/callback.html', NULL, 3600, NULL, '{"LOGOUT_NOTIFY_URL_LIST":"http://127.0.0.1:8082/logoutNotify"}', 'true', NULL, NULL, 'pc端', 1, 60, 1);
-INSERT INTO `oauth_client_details` VALUES (2, 'app', NULL, '$2a$10$i3F515wEDiB4Gvj9ym9Prui0dasRttEUQ9ink4Wpgb4zEDCAlV8zO', 'app', 'app', 'authorization_code,password,refresh_token', 'http://127.0.0.1:8081/callback.html', NULL, 3600, NULL, '{"LOGOUT_NOTIFY_URL_LIST":"http://127.0.0.1:8081/logoutNotify"}', 'true', NULL, NULL, '移动端', 1, 60, 1);
-INSERT INTO `oauth_client_details` VALUES (3, 'zlt', NULL, '$2a$10$/o.wuORzVcXaezmYVzwYMuoY7qeWXBALwQmkskXD/7C6rqfCyPrna', 'zlt', 'all', 'authorization_code,password,refresh_token,client_credentials', 'http://127.0.0.1:8080/singleLogin', NULL, 3600, 28800, '{}', 'true', '2018-12-27 00:50:30', '2018-12-27 00:50:30', '第三方应用', 1, 60, 1);
\ No newline at end of file
+INSERT INTO `oauth_client_details` VALUES (1, 'webApp', NULL, '$2a$10$06msMGYRH8nrm4iVnKFNKOoddB8wOwymVhbUzw/d3ZixD7Nq8ot72', 'webApp', 'app,openid,profile', 'authorization_code,password,refresh_token,client_credentials,implicit,password_code,openId,mobile_password', 'http://127.0.0.1:8082/callback.html', NULL, 3600, NULL, '{"LOGOUT_NOTIFY_URL_LIST":"http://127.0.0.1:8082/logoutNotify"}', 'true', NULL, NULL, 'pc端', 'reference', 1);
+INSERT INTO `oauth_client_details` VALUES (2, 'app', NULL, '$2a$10$i3F515wEDiB4Gvj9ym9Prui0dasRttEUQ9ink4Wpgb4zEDCAlV8zO', 'app', 'app', 'authorization_code,password,refresh_token', 'http://127.0.0.1:8081/callback.html', NULL, 3600, NULL, '{"LOGOUT_NOTIFY_URL_LIST":"http://127.0.0.1:8081/logoutNotify"}', 'true', NULL, NULL, '移动端', 'reference', 1);
+INSERT INTO `oauth_client_details` VALUES (3, 'zlt', NULL, '$2a$10$/o.wuORzVcXaezmYVzwYMuoY7qeWXBALwQmkskXD/7C6rqfCyPrna', 'zlt', 'all,openid,profile', 'authorization_code,password,refresh_token,client_credentials', 'http://127.0.0.1:8080/singleLogin', NULL, 3600, 28800, '{}', 'true', '2018-12-27 00:50:30', '2018-12-27 00:50:30', '第三方应用', 'reference', 1);
\ No newline at end of file
diff --git a/zlt-doc/版本升级_sql/旧版本升级v6.0.0.sql b/zlt-doc/版本升级_sql/旧版本升级v6.0.0.sql
new file mode 100644
index 00000000..b442782a
--- /dev/null
+++ b/zlt-doc/版本升级_sql/旧版本升级v6.0.0.sql
@@ -0,0 +1,8 @@
+------------更新语句
+Use `oauth-center`;
+alter table oauth_client_details add token_format varchar(20) not null DEFAULT 'reference' COMMENT 'token格式: reference 引用令牌(不透明), self-contained 自包含令牌(jwt))';
+alter table oauth_client_details drop column support_id_token;
+alter table oauth_client_details drop column id_token_validity;
+
+UPDATE oauth_client_details set scope = 'app,openid,profile' where client_id = 'webApp';
+UPDATE oauth_client_details set scope = 'all,openid,profile' where client_id = 'zlt';
\ No newline at end of file
diff --git a/zlt-gateway/pom.xml b/zlt-gateway/pom.xml
index e7ce60b7..5184b57b 100644
--- a/zlt-gateway/pom.xml
+++ b/zlt-gateway/pom.xml
@@ -4,7 +4,7 @@
com.zlt
central-platform
- 5.6.0
+ 6.0.0
zlt-gateway
pom
diff --git a/zlt-gateway/sc-gateway/pom.xml b/zlt-gateway/sc-gateway/pom.xml
index b9154083..03f27f67 100644
--- a/zlt-gateway/sc-gateway/pom.xml
+++ b/zlt-gateway/sc-gateway/pom.xml
@@ -4,12 +4,13 @@
com.zlt
zlt-gateway
- 5.6.0
+ 6.0.0
sc-gateway
spring cloud gateway网关
+
com.zlt
zlt-config
@@ -18,6 +19,7 @@
com.zlt
zlt-log-spring-boot-starter
+
com.zlt
zlt-loadbalancer-spring-boot-starter
@@ -26,26 +28,10 @@
com.zlt
zlt-sentinel-spring-boot-starter
-
-
- com.zlt
- zlt-auth-client-spring-boot-starter
-
-
- com.zlt
- zlt-redis-spring-boot-starter
-
-
- org.springframework.boot
- spring-boot-starter-web
-
-
-
-
org.springframework.cloud
spring-cloud-starter-gateway
@@ -58,6 +44,22 @@
org.springframework.boot
spring-boot-starter-webflux
+
+ com.zlt
+ zlt-redis-spring-boot-starter
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+
+
+
+ com.zlt
+ zlt-auth-client-spring-boot-starter
+
+
org.springframework.cloud
spring-cloud-starter-openfeign
@@ -74,13 +76,9 @@
com.github.xiaoymin
- knife4j-spring-boot-starter
+ knife4j-gateway-spring-boot-starter
-
- org.springframework.security
- spring-security-oauth2-resource-server
-
com.baomidou
mybatis-plus-extension
@@ -93,10 +91,6 @@
eu.bitwalker
UserAgentUtils
-
- org.springframework.security.oauth
- spring-security-oauth2
-
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/SCGatewayApp.java b/zlt-gateway/sc-gateway/src/main/java/com/central/SCGatewayApp.java
index c2ecc2bd..9f781ea8 100644
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/SCGatewayApp.java
+++ b/zlt-gateway/sc-gateway/src/main/java/com/central/SCGatewayApp.java
@@ -10,7 +10,7 @@ import org.springframework.cloud.openfeign.EnableFeignClients;
* @author zlt
* @date 2019/10/5
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@EnableFeignClients
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/CustomAuthenticationManager.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/CustomAuthenticationManager.java
deleted file mode 100644
index e2d5019a..00000000
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/CustomAuthenticationManager.java
+++ /dev/null
@@ -1,49 +0,0 @@
-package com.central.gateway.auth;
-
-import org.springframework.security.authentication.ReactiveAuthenticationManager;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.oauth2.common.OAuth2AccessToken;
-import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
-import org.springframework.security.oauth2.provider.OAuth2Authentication;
-import org.springframework.security.oauth2.provider.token.TokenStore;
-import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken;
-import reactor.core.publisher.Mono;
-
-/**
- * @author zlt
- * @date 2019/10/6
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-public class CustomAuthenticationManager implements ReactiveAuthenticationManager {
- private TokenStore tokenStore;
-
- public CustomAuthenticationManager(TokenStore tokenStore) {
- this.tokenStore = tokenStore;
- }
-
- @Override
- public Mono authenticate(Authentication authentication) {
- return Mono.justOrEmpty(authentication)
- .filter(a -> a instanceof BearerTokenAuthenticationToken)
- .cast(BearerTokenAuthenticationToken.class)
- .map(BearerTokenAuthenticationToken::getToken)
- .flatMap((accessTokenValue -> {
- OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue);
- if (accessToken == null) {
- return Mono.error(new InvalidTokenException("Invalid access token: " + accessTokenValue));
- } else if (accessToken.isExpired()) {
- tokenStore.removeAccessToken(accessToken);
- return Mono.error(new InvalidTokenException("Access token expired: " + accessTokenValue));
- }
-
- OAuth2Authentication result = tokenStore.readAuthentication(accessToken);
- if (result == null) {
- return Mono.error(new InvalidTokenException("Invalid access token: " + accessTokenValue));
- }
- return Mono.just(result);
- }))
- .cast(Authentication.class);
- }
-}
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/CustomServerWebExchangeMatchers.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/CustomServerWebExchangeMatchers.java
deleted file mode 100644
index 23e02a43..00000000
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/CustomServerWebExchangeMatchers.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package com.central.gateway.auth;
-
-import com.central.oauth2.common.properties.SecurityProperties;
-import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
-import org.springframework.util.AntPathMatcher;
-import org.springframework.web.server.ServerWebExchange;
-import reactor.core.publisher.Mono;
-
-/**
- * 自定义 ServerWebExchangeMatcher
- * 解决只要请求携带access_token,排除鉴权的url依然会被拦截
- *
- * @author zlt
- * @version 1.0
- * @date 2022/6/10
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-public class CustomServerWebExchangeMatchers implements ServerWebExchangeMatcher {
- private final SecurityProperties securityProperties;
-
- private final AntPathMatcher antPathMatcher = new AntPathMatcher();
-
- public CustomServerWebExchangeMatchers(SecurityProperties securityProperties) {
- this.securityProperties = securityProperties;
- }
-
- @Override
- public Mono matches(ServerWebExchange exchange) {
- for (String url : securityProperties.getIgnore().getUrls()) {
- if (antPathMatcher.match(url, exchange.getRequest().getURI().getPath())) {
- return MatchResult.notMatch();
- }
- }
- return MatchResult.match();
- }
-}
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/JsonAccessDeniedHandler.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/JsonAccessDeniedHandler.java
deleted file mode 100644
index 8a213b8f..00000000
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/JsonAccessDeniedHandler.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package com.central.gateway.auth;
-
-import com.central.common.utils.WebfluxResponseUtil;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.http.HttpStatus;
-import org.springframework.security.access.AccessDeniedException;
-import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
-import org.springframework.web.server.ServerWebExchange;
-import reactor.core.publisher.Mono;
-
-/**
- * 403拒绝访问异常处理,转换为JSON
- *
- * @author zlt
- * @date 2019/10/7
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Slf4j
-public class JsonAccessDeniedHandler implements ServerAccessDeniedHandler {
- @Override
- public Mono handle(ServerWebExchange exchange, AccessDeniedException e) {
- return WebfluxResponseUtil.responseFailed(exchange, HttpStatus.FORBIDDEN.value(), e.getMessage());
- }
-}
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/JsonAuthenticationEntryPoint.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/JsonAuthenticationEntryPoint.java
deleted file mode 100644
index 52dddddc..00000000
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/JsonAuthenticationEntryPoint.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package com.central.gateway.auth;
-
-import com.central.common.utils.WebfluxResponseUtil;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.http.HttpStatus;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
-import org.springframework.web.server.ServerWebExchange;
-import reactor.core.publisher.Mono;
-
-/**
- * 401未授权异常处理,转换为JSON
- *
- * @author zlt
- * @date 2019/10/7
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Slf4j
-public class JsonAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {
- @Override
- public Mono commence(ServerWebExchange exchange, AuthenticationException e) {
- return WebfluxResponseUtil.responseFailed(exchange, HttpStatus.UNAUTHORIZED.value(), e.getMessage());
- }
-}
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2AuthSuccessHandler.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2ServerAuthSuccessHandler.java
similarity index 53%
rename from zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2AuthSuccessHandler.java
rename to zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2ServerAuthSuccessHandler.java
index ea1b1e8f..a86dd697 100644
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2AuthSuccessHandler.java
+++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2ServerAuthSuccessHandler.java
@@ -1,20 +1,23 @@
package com.central.gateway.auth;
import cn.hutool.core.collection.CollectionUtil;
-import cn.hutool.core.util.StrUtil;
import com.central.common.constant.SecurityConstants;
-import com.central.common.model.SysUser;
-import com.central.oauth2.common.util.AuthUtils;
+import com.central.common.model.LoginAppUser;
+import com.central.common.utils.LoginUserUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.core.Authentication;
-import org.springframework.security.oauth2.provider.OAuth2Authentication;
+import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
+import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
+import java.security.Principal;
+import java.util.Map;
+
/**
* 认证成功处理类
*
@@ -24,25 +27,27 @@ import reactor.core.publisher.Mono;
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
-public class Oauth2AuthSuccessHandler implements ServerAuthenticationSuccessHandler {
+@Component
+public class Oauth2ServerAuthSuccessHandler implements ServerAuthenticationSuccessHandler {
@Override
public Mono onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
MultiValueMap headerValues = new LinkedMultiValueMap<>(4);
Object principal = authentication.getPrincipal();
- //客户端模式只返回一个clientId
- if (principal instanceof SysUser) {
- SysUser user = (SysUser)authentication.getPrincipal();
- headerValues.add(SecurityConstants.USER_ID_HEADER, String.valueOf(user.getId()));
- headerValues.add(SecurityConstants.USER_HEADER, user.getUsername());
- }
- OAuth2Authentication oauth2Authentication = (OAuth2Authentication)authentication;
- String clientId = oauth2Authentication.getOAuth2Request().getClientId();
- headerValues.add(SecurityConstants.TENANT_HEADER, clientId);
- headerValues.add(SecurityConstants.ROLE_HEADER, CollectionUtil.join(authentication.getAuthorities(), ","));
- String accountType = AuthUtils.getAccountType(oauth2Authentication.getUserAuthentication());
- if (StrUtil.isNotEmpty(accountType)) {
- headerValues.add(SecurityConstants.ACCOUNT_TYPE_HEADER, accountType);
+
+ if (principal instanceof OAuth2IntrospectionAuthenticatedPrincipal authenticatedPrincipal) {
+ Map claims = authenticatedPrincipal.getAttributes();
+ Authentication auth = (Authentication)claims.get(Principal.class.getName());
+ LoginAppUser user = LoginUserUtils.getUser(auth);
+ if (user != null) {
+ headerValues.add(SecurityConstants.USER_ID_HEADER, String.valueOf(user.getId()));
+ headerValues.add(SecurityConstants.USER_HEADER, user.getUsername());
+ }
+
+ headerValues.add(SecurityConstants.ROLE_HEADER, CollectionUtil.join(authentication.getAuthorities(), ","));
+ headerValues.add(SecurityConstants.TENANT_HEADER, (String)claims.get(SecurityConstants.CLIENT_ID));
+ headerValues.add(SecurityConstants.ACCOUNT_TYPE_HEADER, (String)claims.get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME));
}
+
ServerWebExchange exchange = webFilterExchange.getExchange();
ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate()
.headers(h -> h.addAll(headerValues))
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/PermissionAuthManager.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/PermissionAuthManager.java
index 1afb01b4..15987deb 100644
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/PermissionAuthManager.java
+++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/PermissionAuthManager.java
@@ -38,7 +38,7 @@ public class PermissionAuthManager extends DefaultPermissionServiceImpl implemen
return authentication.map(auth -> {
ServerWebExchange exchange = authorizationContext.getExchange();
ServerHttpRequest request = exchange.getRequest();
- boolean isPermission = super.hasPermission(auth, request.getMethodValue(), request.getURI().getPath());
+ boolean isPermission = super.hasPermission(auth, request.getMethod().name(), request.getURI().getPath());
return new AuthorizationDecision(isPermission);
}).defaultIfEmpty(new AuthorizationDecision(false));
}
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/AsycTaskExecutorConfig.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/AsycTaskExecutorConfig.java
index 49ab7e6d..81e42ae1 100644
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/AsycTaskExecutorConfig.java
+++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/AsycTaskExecutorConfig.java
@@ -10,7 +10,7 @@ import org.springframework.context.annotation.Configuration;
* @version 1.0
* @date 2021/8/8
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Configuration
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/CorsConfig.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/CorsConfig.java
index 7e2ea488..4ff65b4a 100644
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/CorsConfig.java
+++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/CorsConfig.java
@@ -15,7 +15,7 @@ import org.springframework.web.util.pattern.PathPatternParser;
* @author zlt
* @date 2019/10/5
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Configuration
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/DynamicRouteConfig.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/DynamicRouteConfig.java
index 5720d863..46ab8596 100644
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/DynamicRouteConfig.java
+++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/DynamicRouteConfig.java
@@ -14,7 +14,7 @@ import org.springframework.context.annotation.Configuration;
* @author zlt
* @date 2019/10/7
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Configuration
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/FeignConfig.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/FeignConfig.java
index 9f4d343d..4ffa0f3d 100644
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/FeignConfig.java
+++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/FeignConfig.java
@@ -20,7 +20,7 @@ import java.util.List;
* @author zlt
* @date 2020/7/26
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Configuration
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java
index 5f8edf6a..dcc7373c 100644
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java
+++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java
@@ -1,78 +1,19 @@
package com.central.gateway.config;
-import com.central.gateway.auth.*;
-import com.central.oauth2.common.properties.SecurityProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
+import com.central.oauth2.common.config.DefaultWebFluxResourceServerConf;
+
import org.springframework.context.annotation.Configuration;
-import org.springframework.http.HttpMethod;
-import org.springframework.security.authentication.ReactiveAuthenticationManager;
-import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
-import org.springframework.security.config.web.server.ServerHttpSecurity;
-import org.springframework.security.oauth2.provider.token.TokenStore;
-import org.springframework.security.oauth2.server.resource.web.server.ServerBearerTokenAuthenticationConverter;
-import org.springframework.security.web.server.SecurityWebFilterChain;
-import org.springframework.security.web.server.authentication.AuthenticationWebFilter;
-import org.springframework.security.web.server.authentication.ServerAuthenticationEntryPointFailureHandler;
/**
- * 资源服务器配置
+ * 资源服务器
*
- * @author zlt
- * @date 2019/10/5
+ * @author: zlt
+ * @date: 2023/11/25
*
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Configuration
-public class ResourceServerConfiguration {
- @Autowired
- private SecurityProperties securityProperties;
+public class ResourceServerConfiguration extends DefaultWebFluxResourceServerConf {
- @Autowired
- private TokenStore tokenStore;
-
- @Autowired
- private PermissionAuthManager permissionAuthManager;
-
- @Bean
- SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
- //认证处理器
- ReactiveAuthenticationManager customAuthenticationManager = new CustomAuthenticationManager(tokenStore);
- JsonAuthenticationEntryPoint entryPoint = new JsonAuthenticationEntryPoint();
- //token转换器
- ServerBearerTokenAuthenticationConverter tokenAuthenticationConverter = new ServerBearerTokenAuthenticationConverter();
- tokenAuthenticationConverter.setAllowUriQueryParameter(true);
- //oauth2认证过滤器
- AuthenticationWebFilter oauth2Filter = new AuthenticationWebFilter(customAuthenticationManager);
- oauth2Filter.setServerAuthenticationConverter(tokenAuthenticationConverter);
- oauth2Filter.setAuthenticationFailureHandler(new ServerAuthenticationEntryPointFailureHandler(entryPoint));
- oauth2Filter.setAuthenticationSuccessHandler(new Oauth2AuthSuccessHandler());
- oauth2Filter.setRequiresAuthenticationMatcher(new CustomServerWebExchangeMatchers(securityProperties));
- http.addFilterAt(oauth2Filter, SecurityWebFiltersOrder.AUTHENTICATION);
-
- ServerHttpSecurity.AuthorizeExchangeSpec authorizeExchange = http.authorizeExchange();
- if (securityProperties.getAuth().getHttpUrls().length > 0) {
- authorizeExchange.pathMatchers(securityProperties.getAuth().getHttpUrls()).authenticated();
- }
- if (securityProperties.getIgnore().getUrls().length > 0) {
- authorizeExchange.pathMatchers(securityProperties.getIgnore().getUrls()).permitAll();
- }
- authorizeExchange
- .pathMatchers(HttpMethod.OPTIONS).permitAll()
- .anyExchange()
- .access(permissionAuthManager)
- .and()
- .exceptionHandling()
- .accessDeniedHandler(new JsonAccessDeniedHandler())
- .authenticationEntryPoint(entryPoint)
- .and()
- .headers()
- .frameOptions()
- .disable()
- .and()
- .httpBasic().disable()
- .csrf().disable();
- return http.build();
- }
}
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/error/CustomErrorWebFluxAutoConfiguration.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/error/CustomErrorWebFluxAutoConfiguration.java
index 174d70c0..2856b36f 100644
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/error/CustomErrorWebFluxAutoConfiguration.java
+++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/error/CustomErrorWebFluxAutoConfiguration.java
@@ -1,7 +1,7 @@
package com.central.gateway.error;
import org.springframework.beans.factory.ObjectProvider;
-import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.web.ServerProperties;
@@ -12,64 +12,42 @@ import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.config.WebFluxConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;
-import java.util.Collections;
-import java.util.List;
-
/**
* 自定义异常处理
*
* @author zlt
* @date 2020/3/30
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
-@Configuration
+@AutoConfiguration(before = WebFluxAutoConfiguration.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@ConditionalOnClass(WebFluxConfigurer.class)
-@AutoConfigureBefore(WebFluxAutoConfiguration.class)
-@EnableConfigurationProperties({ServerProperties.class, WebProperties.class})
+@EnableConfigurationProperties({ ServerProperties.class, WebProperties.class })
public class CustomErrorWebFluxAutoConfiguration {
private final ServerProperties serverProperties;
- private final ApplicationContext applicationContext;
-
- private final WebProperties webProperties;
-
- private final List viewResolvers;
-
- private final ServerCodecConfigurer serverCodecConfigurer;
-
- public CustomErrorWebFluxAutoConfiguration(ServerProperties serverProperties,
- WebProperties webProperties,
- ObjectProvider> viewResolversProvider,
- ServerCodecConfigurer serverCodecConfigurer,
- ApplicationContext applicationContext) {
+ public CustomErrorWebFluxAutoConfiguration(ServerProperties serverProperties) {
this.serverProperties = serverProperties;
- this.applicationContext = applicationContext;
- this.webProperties = webProperties;
- this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
- this.serverCodecConfigurer = serverCodecConfigurer;
}
@Bean
- @Order(Ordered.HIGHEST_PRECEDENCE)
- public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) {
- JsonErrorWebExceptionHandler exceptionHandler = new JsonErrorWebExceptionHandler(
- errorAttributes,
- this.webProperties.getResources(),
- this.serverProperties.getError(),
- this.applicationContext);
- exceptionHandler.setViewResolvers(this.viewResolvers);
- exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());
- exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());
+ @Order(-1)
+ public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes,
+ WebProperties webProperties, ObjectProvider viewResolvers,
+ ServerCodecConfigurer serverCodecConfigurer, ApplicationContext applicationContext) {
+ JsonErrorWebExceptionHandler exceptionHandler = new JsonErrorWebExceptionHandler(errorAttributes,
+ webProperties.getResources(), this.serverProperties.getError(), applicationContext);
+ exceptionHandler.setViewResolvers(viewResolvers.orderedStream().toList());
+ exceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
+ exceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
return exceptionHandler;
}
+
}
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/error/JsonErrorWebExceptionHandler.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/error/JsonErrorWebExceptionHandler.java
index 93814e37..c22adee6 100644
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/error/JsonErrorWebExceptionHandler.java
+++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/error/JsonErrorWebExceptionHandler.java
@@ -7,7 +7,6 @@ import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
-import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.web.reactive.function.server.*;
import java.util.HashMap;
@@ -19,7 +18,7 @@ import java.util.Map;
* @author zlt
* @date 2020/3/30
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class JsonErrorWebExceptionHandler extends DefaultErrorWebExceptionHandler {
@@ -80,7 +79,7 @@ public class JsonErrorWebExceptionHandler extends DefaultErrorWebExceptionHandle
*/
private Map responseError(ServerRequest request, Throwable error) {
String errorMessage = buildMessage(request, error);
- int httpStatus = getHttpStatus(error);
+ int httpStatus = 200;//getHttpStatus(error);
Map map = new HashMap<>();
map.put("resp_code", 1);
map.put("resp_msg", errorMessage);
@@ -91,12 +90,13 @@ public class JsonErrorWebExceptionHandler extends DefaultErrorWebExceptionHandle
private int getHttpStatus(Throwable error) {
int httpStatus;
- if (error instanceof InvalidTokenException) {
+ /*if (error instanceof InvalidTokenException) {
InvalidTokenException ex = (InvalidTokenException)error;
httpStatus = ex.getHttpErrorCode();
} else {
httpStatus = HttpStatus.INTERNAL_SERVER_ERROR.value();
- }
+ }*/
+ httpStatus = HttpStatus.INTERNAL_SERVER_ERROR.value();
return httpStatus;
}
}
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/feign/AsynMenuService.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/feign/AsynMenuService.java
index b6577abd..b9670e54 100644
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/feign/AsynMenuService.java
+++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/feign/AsynMenuService.java
@@ -1,13 +1,12 @@
package com.central.gateway.feign;
import com.central.common.model.SysMenu;
-import org.springframework.beans.factory.annotation.Autowired;
+import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
-import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.Future;
@@ -18,7 +17,7 @@ import java.util.concurrent.Future;
* @version 1.0
* @date 2021/8/8
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Component
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/feign/MenuService.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/feign/MenuService.java
index 59781589..9253ba0b 100644
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/feign/MenuService.java
+++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/feign/MenuService.java
@@ -12,7 +12,7 @@ import java.util.List;
/**
* @author zlt
*/
-@FeignClient(name = ServiceNameConstants.USER_SERVICE, fallbackFactory = MenuServiceFallbackFactory.class, decode404 = true)
+@FeignClient(name = ServiceNameConstants.USER_SERVICE, fallbackFactory = MenuServiceFallbackFactory.class, dismiss404 = true)
public interface MenuService {
/**
* 角色菜单列表
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/LbIsolationFilter.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/LbIsolationFilter.java
index 74f964d3..b7c69285 100644
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/LbIsolationFilter.java
+++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/LbIsolationFilter.java
@@ -22,7 +22,7 @@ import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.G
* @author zlt
* @date 2019/10/7
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
/*
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/RequestStatisticsFilter.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/RequestStatisticsFilter.java
index ce3e88cb..bf319311 100644
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/RequestStatisticsFilter.java
+++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/RequestStatisticsFilter.java
@@ -20,7 +20,7 @@ import java.util.Map;
* @author zlt
* @date 2019/10/7
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Component
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/TraceFilter.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/TraceFilter.java
index 89bf0f0b..1a10ff51 100644
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/TraceFilter.java
+++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/TraceFilter.java
@@ -17,7 +17,7 @@ import reactor.core.publisher.Mono;
* @author zlt
* @date 2019/10/7
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Component
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/route/NacosRouteDefinitionRepository.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/route/NacosRouteDefinitionRepository.java
index 155fc18c..4468e871 100644
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/route/NacosRouteDefinitionRepository.java
+++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/route/NacosRouteDefinitionRepository.java
@@ -24,7 +24,7 @@ import java.util.concurrent.Executor;
* @author zlt
* @date 2019/10/7
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerAggProperties.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerAggProperties.java
deleted file mode 100644
index df7762d8..00000000
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerAggProperties.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package com.central.gateway.swagger;
-
-import lombok.Getter;
-import lombok.Setter;
-import org.springframework.boot.context.properties.ConfigurationProperties;
-import org.springframework.cloud.context.config.annotation.RefreshScope;
-
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * swagger聚合配置
- *
- * @author zlt
- * @date 2019/10/5
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Setter
-@Getter
-@ConfigurationProperties("zlt.swagger-agg")
-@RefreshScope
-public class SwaggerAggProperties {
- /**
- * Swagger返回JSON文档的接口路径(全局配置)
- */
- private String apiDocsPath = "/v2/api-docs";
-
- /**
- * Swagger文档版本(全局配置)
- */
- private String swaggerVersion = "2.0";
-
- /**
- * 自动生成文档的路由名称,设置了generateRoutes之后,ignoreRoutes不生效
- */
- private Set generateRoutes = new HashSet<>();
-
- /**
- * 不自动生成文档的路由名称,设置了generateRoutes之后,本配置不生效
- */
- private Set ignoreRoutes = new HashSet<>();
-
- /**
- * 是否显示该路由
- */
- public boolean isShow(String route) {
- int generateRoutesSize = generateRoutes.size();
- int ignoreRoutesSize = ignoreRoutes.size();
-
- if(generateRoutesSize > 0 && !generateRoutes.contains(route)) {
- return false;
- }
-
- if(ignoreRoutesSize > 0 && ignoreRoutes.contains(route)) {
- return false;
- }
-
- return true;
- }
-}
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerHandler.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerHandler.java
deleted file mode 100644
index f9be8322..00000000
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerHandler.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package com.central.gateway.swagger;
-
-import org.springframework.beans.factory.annotation.Autowired;
-
-import java.util.Optional;
-
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
-
-import reactor.core.publisher.Mono;
-import springfox.documentation.swagger.web.SecurityConfiguration;
-import springfox.documentation.swagger.web.SecurityConfigurationBuilder;
-import springfox.documentation.swagger.web.SwaggerResourcesProvider;
-import springfox.documentation.swagger.web.UiConfiguration;
-import springfox.documentation.swagger.web.UiConfigurationBuilder;
-
-/**
- * @author zlt
- * @date 2019/10/5
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@RestController
-@RequestMapping("/swagger-resources" )
-public class SwaggerHandler {
- private final SwaggerResourcesProvider swaggerResources;
- @Autowired(required = false)
- private SecurityConfiguration securityConfiguration;
- @Autowired(required = false)
- private UiConfiguration uiConfiguration;
-
- @Autowired
- public SwaggerHandler(SwaggerResourcesProvider swaggerResources) {
- this.swaggerResources = swaggerResources;
- }
-
- @GetMapping("/configuration/security" )
- public Mono> securityConfiguration() {
- return Mono.just(new ResponseEntity<>(
- Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK));
- }
-
- @GetMapping("/configuration/ui" )
- public Mono> uiConfiguration() {
- return Mono.just(new ResponseEntity<>(
- Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));
- }
-
- @GetMapping
- public Mono swaggerResources() {
- return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
- }
-}
\ No newline at end of file
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerProvider.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerProvider.java
deleted file mode 100644
index 5156a077..00000000
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerProvider.java
+++ /dev/null
@@ -1,73 +0,0 @@
-package com.central.gateway.swagger;
-
-import org.springframework.boot.context.properties.EnableConfigurationProperties;
-import org.springframework.cloud.gateway.config.GatewayProperties;
-import org.springframework.cloud.gateway.route.RouteLocator;
-import org.springframework.cloud.gateway.support.NameUtils;
-import org.springframework.context.annotation.Primary;
-import org.springframework.stereotype.Component;
-import springfox.documentation.swagger.web.SwaggerResource;
-import springfox.documentation.swagger.web.SwaggerResourcesProvider;
-
-import javax.annotation.Resource;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * 跨域配置
- *
- * @author zlt
- * @date 2019/10/5
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Component
-@EnableConfigurationProperties(SwaggerAggProperties.class)
-@Primary
-public class SwaggerProvider implements SwaggerResourcesProvider {
- private final RouteLocator routeLocator;
- private final GatewayProperties gatewayProperties;
-
- @Resource
- private SwaggerAggProperties swaggerAggProperties;
-
- public SwaggerProvider(RouteLocator routeLocator, GatewayProperties gatewayProperties) {
- this.routeLocator = routeLocator;
- this.gatewayProperties = gatewayProperties;
- }
-
- @Override
- public List get() {
- List resources = new ArrayList<>();
- Set routes = new HashSet<>();
- //取出Spring Cloud Gateway中的route
- routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
- //结合application.yml中的路由配置,只获取有效的route节点
- gatewayProperties.getRoutes().stream().filter(
- routeDefinition -> (
- routes.contains(routeDefinition.getId()) && swaggerAggProperties.isShow(routeDefinition.getId())
- )
- ).forEach(routeDefinition -> routeDefinition.getPredicates().stream()
- .filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
- .forEach(predicateDefinition -> resources.add(
- swaggerResource(
- routeDefinition.getId(),
- predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("/**", swaggerAggProperties.getApiDocsPath())
- )
- )
- )
- );
- return resources;
- }
-
- private SwaggerResource swaggerResource(String name, String location) {
- SwaggerResource swaggerResource = new SwaggerResource();
- swaggerResource.setName(name);
- swaggerResource.setLocation(location);
- swaggerResource.setSwaggerVersion(swaggerAggProperties.getSwaggerVersion());
- return swaggerResource;
- }
-}
\ No newline at end of file
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/utils/ReactiveAddrUtil.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/utils/ReactiveAddrUtil.java
index 181d8ac5..0ab906dd 100644
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/utils/ReactiveAddrUtil.java
+++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/utils/ReactiveAddrUtil.java
@@ -12,7 +12,7 @@ import java.util.Map;
* @author zlt
* @date 2019/10/7
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
diff --git a/zlt-gateway/sc-gateway/src/main/resources/application.yml b/zlt-gateway/sc-gateway/src/main/resources/application.yml
index f7f69bf3..541e24bd 100644
--- a/zlt-gateway/sc-gateway/src/main/resources/application.yml
+++ b/zlt-gateway/sc-gateway/src/main/resources/application.yml
@@ -82,13 +82,29 @@ spring:
# filter:
# enabled: true
+knife4j:
+ gateway:
+ enabled: true
+ strategy: manual
+ routes:
+ - name: 用户服务
+ service-name: user-center
+ url: /api-user/v3/api-docs/default
+ context-path: /api-user
+ - name: 授权服务
+ service-name: uaa-server
+ url: /api-uaa/v3/api-docs/default
+ context-path: /api-uaa
+ - name: 搜索服务
+ service-name: search-center
+ url: /api-search/v3/api-docs/default
+ context-path: /api-search
+ - name: 文件服务
+ service-name: file-center
+ url: /api-file/v3/api-docs/default
+ context-path: /api-file
+
zlt:
- swagger-agg:
- generate-routes: user,file
- oauth2:
- token:
- store:
- type: redis
security:
ignore:
# 忽略认证的地址
@@ -99,8 +115,9 @@ zlt:
/api-uaa/images/**,
/api-uaa/js/**,
/login.html,
- /user/login,
- /api-uaa/tokens/key
+ /user/login, /oauth/authorize,
+ /api-uaa/tokens/key,
+ /*/v3/api-docs/**
auth:
urlPermission:
#是否开启url级别权限
diff --git a/zlt-gateway/sc-gateway/src/main/resources/bootstrap.yml b/zlt-gateway/sc-gateway/src/main/resources/bootstrap.yml
index a41f0b3d..02691bb3 100644
--- a/zlt-gateway/sc-gateway/src/main/resources/bootstrap.yml
+++ b/zlt-gateway/sc-gateway/src/main/resources/bootstrap.yml
@@ -3,4 +3,6 @@ server:
spring:
application:
- name: sc-gateway
\ No newline at end of file
+ name: sc-gateway
+ main:
+ web-application-type: reactive
\ No newline at end of file
diff --git a/zlt-monitor/log-center/pom.xml b/zlt-monitor/log-center/pom.xml
index eb2d27bf..627164b8 100644
--- a/zlt-monitor/log-center/pom.xml
+++ b/zlt-monitor/log-center/pom.xml
@@ -4,7 +4,7 @@
com.zlt
zlt-monitor
- 5.6.0
+ 6.0.0
log-center
@@ -23,8 +23,8 @@
- com.zlt
- zlt-swagger2-spring-boot-starter
+ com.github.xiaoymin
+ knife4j-openapi3-jakarta-spring-boot-starter
com.zlt
diff --git a/zlt-monitor/log-center/src/main/java/com/central/log/controller/AggregationController.java b/zlt-monitor/log-center/src/main/java/com/central/log/controller/AggregationController.java
index 8dc77caa..203f544e 100644
--- a/zlt-monitor/log-center/src/main/java/com/central/log/controller/AggregationController.java
+++ b/zlt-monitor/log-center/src/main/java/com/central/log/controller/AggregationController.java
@@ -1,7 +1,8 @@
package com.central.log.controller;
import com.central.search.client.service.IQueryService;
-import io.swagger.annotations.ApiOperation;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -14,12 +15,13 @@ import java.util.Map;
* @author zlt
* @date 2019/5/8
*/
+@Tag(name = "访问统计")
@RestController
public class AggregationController {
@Autowired
private IQueryService queryService;
- @ApiOperation(value = "访问统计")
+ @Operation(summary = "访问统计")
@GetMapping(value = "/requestStat")
public Map requestStatAgg() {
return queryService.requestStatAgg("point-log-*","request-statistics");
diff --git a/zlt-monitor/log-center/src/main/java/com/central/log/controller/AuditLogController.java b/zlt-monitor/log-center/src/main/java/com/central/log/controller/AuditLogController.java
index 1b03ce25..4d3bce74 100644
--- a/zlt-monitor/log-center/src/main/java/com/central/log/controller/AuditLogController.java
+++ b/zlt-monitor/log-center/src/main/java/com/central/log/controller/AuditLogController.java
@@ -4,9 +4,8 @@ import com.central.common.model.PageResult;
import com.central.search.client.service.IQueryService;
import com.central.search.model.SearchDto;
import com.fasterxml.jackson.databind.JsonNode;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -16,9 +15,10 @@ import org.springframework.web.bind.annotation.RestController;
* @author zlt
* @date 2020/2/4
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
+@Tag(name = "审计日志")
@RestController
public class AuditLogController {
private final IQueryService queryService;
@@ -27,12 +27,7 @@ public class AuditLogController {
this.queryService = queryService;
}
- @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 = "审计日志全文搜索列表")
@GetMapping(value = "/auditLog")
public PageResult getPage(SearchDto searchDto) {
searchDto.setIsHighlighter(true);
diff --git a/zlt-monitor/log-center/src/main/java/com/central/log/controller/SlowQueryLogController.java b/zlt-monitor/log-center/src/main/java/com/central/log/controller/SlowQueryLogController.java
index 99d5a3f6..6ba0fae7 100644
--- a/zlt-monitor/log-center/src/main/java/com/central/log/controller/SlowQueryLogController.java
+++ b/zlt-monitor/log-center/src/main/java/com/central/log/controller/SlowQueryLogController.java
@@ -4,9 +4,8 @@ import com.central.common.model.PageResult;
import com.central.search.client.service.IQueryService;
import com.central.search.model.SearchDto;
import com.fasterxml.jackson.databind.JsonNode;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -16,17 +15,13 @@ import org.springframework.web.bind.annotation.RestController;
*
* @author zlt
*/
+@Tag(name = "慢查询日志")
@RestController
public class SlowQueryLogController {
@Autowired
private IQueryService queryService;
- @ApiOperation(value = "慢sql日志全文搜索列表")
- @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 = "慢sql日志全文搜索列表")
@GetMapping(value = "/slowQueryLog")
public PageResult getPage(SearchDto searchDto) {
searchDto.setIsHighlighter(true);
diff --git a/zlt-monitor/log-center/src/main/java/com/central/log/controller/SysLogController.java b/zlt-monitor/log-center/src/main/java/com/central/log/controller/SysLogController.java
index 1a483ee2..6869e882 100644
--- a/zlt-monitor/log-center/src/main/java/com/central/log/controller/SysLogController.java
+++ b/zlt-monitor/log-center/src/main/java/com/central/log/controller/SysLogController.java
@@ -6,9 +6,8 @@ import com.central.log.service.TraceLogService;
import com.central.search.client.service.IQueryService;
import com.central.search.model.SearchDto;
import com.fasterxml.jackson.databind.JsonNode;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -20,6 +19,7 @@ import java.util.*;
*
* @author zlt
*/
+@Tag(name = "系统日志")
@RestController
public class SysLogController {
/**
@@ -33,27 +33,13 @@ public class SysLogController {
@Resource
private TraceLogService traceLogService;
- @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"),
- @ApiImplicitParam(name = "sortCol", value = "排序字段", dataType = "String"),
- @ApiImplicitParam(name = "sortOrder", value = "排序顺序", dataType = "String"),
- @ApiImplicitParam(name = "isHighlighter", value = "是否显示高亮", dataType = "String")
- })
+ @Operation(summary = "系统日志全文搜索列表")
@GetMapping(value = "/sysLog")
public PageResult sysLog(SearchDto searchDto) {
return queryService.strQuery(SYS_LOG_INDEXNAME, searchDto);
}
- @ApiOperation(value = "系统日志链路列表")
- @ApiImplicitParams({
- @ApiImplicitParam(name = "queryStr", value = "搜索关键字", dataType = "String"),
- @ApiImplicitParam(name = "sortCol", value = "排序字段", dataType = "String"),
- @ApiImplicitParam(name = "sortOrder", value = "排序顺序", dataType = "String"),
- @ApiImplicitParam(name = "isHighlighter", value = "是否显示高亮", dataType = "String")
- })
+ @Operation(summary = "系统日志链路列表")
@GetMapping(value = "/traceLog")
public PageResult traceLog(SearchDto searchDto) {
PageResult pageResult = queryService.strQuery(SYS_LOG_INDEXNAME, searchDto);
diff --git a/zlt-monitor/log-center/src/main/java/com/central/log/model/TraceLog.java b/zlt-monitor/log-center/src/main/java/com/central/log/model/TraceLog.java
index ee508ed3..78020b17 100644
--- a/zlt-monitor/log-center/src/main/java/com/central/log/model/TraceLog.java
+++ b/zlt-monitor/log-center/src/main/java/com/central/log/model/TraceLog.java
@@ -10,7 +10,7 @@ import lombok.Setter;
* @version 1.0
* @date 2022/1/27
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
diff --git a/zlt-monitor/log-center/src/main/java/com/central/log/service/TraceLogService.java b/zlt-monitor/log-center/src/main/java/com/central/log/service/TraceLogService.java
index f7c094d1..afad0090 100644
--- a/zlt-monitor/log-center/src/main/java/com/central/log/service/TraceLogService.java
+++ b/zlt-monitor/log-center/src/main/java/com/central/log/service/TraceLogService.java
@@ -18,7 +18,7 @@ import java.util.Set;
* @version 1.0
* @date 2022/1/27
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Service
diff --git a/zlt-monitor/pom.xml b/zlt-monitor/pom.xml
index db74570a..50081b82 100644
--- a/zlt-monitor/pom.xml
+++ b/zlt-monitor/pom.xml
@@ -3,7 +3,7 @@
com.zlt
central-platform
- 5.6.0
+ 6.0.0
zlt-monitor
pom
diff --git a/zlt-monitor/sc-admin/pom.xml b/zlt-monitor/sc-admin/pom.xml
index 58d8b6db..76c6fcda 100644
--- a/zlt-monitor/sc-admin/pom.xml
+++ b/zlt-monitor/sc-admin/pom.xml
@@ -4,7 +4,7 @@
com.zlt
zlt-monitor
- 5.6.0
+ 6.0.0
sc-admin
diff --git a/zlt-monitor/sc-admin/src/main/java/com/central/gateway/MonitorApp.java b/zlt-monitor/sc-admin/src/main/java/com/central/gateway/MonitorApp.java
index 48bb261e..9af42233 100644
--- a/zlt-monitor/sc-admin/src/main/java/com/central/gateway/MonitorApp.java
+++ b/zlt-monitor/sc-admin/src/main/java/com/central/gateway/MonitorApp.java
@@ -1,15 +1,18 @@
package com.central.gateway;
+import de.codecentric.boot.admin.server.config.AdminServerProperties;
import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* @author zlt
*/
@EnableAdminServer
-@EnableDiscoveryClient
+@EnableDiscoveryClient
+@EnableConfigurationProperties(AdminServerProperties.class)
@SpringBootApplication
public class MonitorApp {
public static void main(String[] args) {
diff --git a/zlt-monitor/sc-admin/src/main/java/com/central/gateway/monitor/config/SecuritySecureConfig.java b/zlt-monitor/sc-admin/src/main/java/com/central/gateway/monitor/config/SecuritySecureConfig.java
index f178536d..817dda02 100644
--- a/zlt-monitor/sc-admin/src/main/java/com/central/gateway/monitor/config/SecuritySecureConfig.java
+++ b/zlt-monitor/sc-admin/src/main/java/com/central/gateway/monitor/config/SecuritySecureConfig.java
@@ -1,9 +1,13 @@
package com.central.gateway.monitor.config;
import de.codecentric.boot.admin.server.config.AdminServerProperties;
+import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
-import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
+import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
+import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
/**
@@ -11,32 +15,32 @@ import org.springframework.security.web.authentication.SavedRequestAwareAuthenti
* @date 2019/1/8
*/
@Configuration
-public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
+public class SecuritySecureConfig {
private final String adminContextPath;
public SecuritySecureConfig(AdminServerProperties adminServerProperties) {
this.adminContextPath = adminServerProperties.getContextPath();
}
- @Override
- protected void configure(HttpSecurity http) throws Exception {
+ @Bean
+ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(adminContextPath + "/");
- http.authorizeRequests()
- .antMatchers(adminContextPath + "/assets/**").permitAll()
- .antMatchers(adminContextPath + "/login").permitAll()
- .anyRequest().authenticated()
- .and()
- .formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and()
- .logout().logoutUrl(adminContextPath + "/logout").and()
- .httpBasic()
- .and()
- .headers()
- .frameOptions()
- .disable()
- .and()
- .csrf().disable();
+ http.authorizeHttpRequests(authorizeRequests -> {
+ // 授权服务器关闭basic认证
+ authorizeRequests
+ .requestMatchers(adminContextPath + "/assets/**").permitAll()
+ .requestMatchers(adminContextPath + "/login").permitAll()
+ .anyRequest().authenticated();
+ })
+ .formLogin(formLogin -> formLogin.loginPage(adminContextPath + "/login").successHandler(successHandler))
+ .logout(logout -> logout.logoutUrl(adminContextPath + "/logout"))
+ .httpBasic(Customizer.withDefaults())
+ .headers(header -> header.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin))
+ .csrf(AbstractHttpConfigurer::disable);
+
+ return http.build();
}
}
diff --git a/zlt-uaa/pom.xml b/zlt-uaa/pom.xml
index 59d3d274..6c01eaf0 100644
--- a/zlt-uaa/pom.xml
+++ b/zlt-uaa/pom.xml
@@ -4,7 +4,7 @@
com.zlt
central-platform
- 5.6.0
+ 6.0.0
zlt-uaa
认证中心
@@ -34,8 +34,8 @@
zlt-loadbalancer-spring-boot-starter
- com.zlt
- zlt-swagger2-spring-boot-starter
+ com.github.xiaoymin
+ knife4j-openapi3-jakarta-spring-boot-starter
com.zlt
@@ -50,10 +50,6 @@
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
-
- org.springframework.social
- spring-social-security
-
org.springframework.boot
spring-boot-starter-web
@@ -62,21 +58,11 @@
commons-io
commons-io
-
-
- com.github.whvcse
- easy-captcha
-
org.springframework.boot
spring-boot-starter-actuator
-
- org.springframework.session
- spring-session-data-redis
-
-
mysql
mysql-connector-java
@@ -102,6 +88,10 @@
junit
test
+
+ org.apache.tomcat.embed
+ tomcat-embed-core
+
diff --git a/zlt-uaa/src/main/java/com/central/UaaServerApp.java b/zlt-uaa/src/main/java/com/central/UaaServerApp.java
index b3ac5a29..04738baf 100644
--- a/zlt-uaa/src/main/java/com/central/UaaServerApp.java
+++ b/zlt-uaa/src/main/java/com/central/UaaServerApp.java
@@ -1,6 +1,7 @@
package com.central;
import com.central.common.lb.annotation.EnableFeignInterceptor;
+import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@@ -10,9 +11,9 @@ import org.springframework.cloud.openfeign.EnableFeignClients;
* @author zlt
*/
@EnableFeignClients
+@MapperScan(basePackages = "com.central.oauth.mapper")
@EnableFeignInterceptor
@EnableDiscoveryClient
-//@EnableRedisHttpSession
@SpringBootApplication
public class UaaServerApp {
public static void main(String[] args) {
diff --git a/zlt-uaa/src/main/java/com/central/oauth/component/CustomAccessTokenResponseHttpMessageConverter.java b/zlt-uaa/src/main/java/com/central/oauth/component/CustomAccessTokenResponseHttpMessageConverter.java
new file mode 100644
index 00000000..8fe29bce
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/component/CustomAccessTokenResponseHttpMessageConverter.java
@@ -0,0 +1,48 @@
+package com.central.oauth.component;
+
+import com.central.common.model.Result;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.springframework.core.ParameterizedTypeReference;
+import org.springframework.core.convert.converter.Converter;
+import org.springframework.http.HttpOutputMessage;
+import org.springframework.http.MediaType;
+import org.springframework.http.converter.GenericHttpMessageConverter;
+import org.springframework.http.converter.HttpMessageNotWritableException;
+import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
+import org.springframework.security.oauth2.core.endpoint.DefaultOAuth2AccessTokenResponseMapConverter;
+import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
+import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter;
+
+import java.util.Map;
+
+/**
+ * @author zlt
+ * @version 1.0
+ * @date 2023/12/6
+ *
+ * Blog: http://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+public class CustomAccessTokenResponseHttpMessageConverter extends OAuth2AccessTokenResponseHttpMessageConverter {
+ private Converter> accessTokenResponseParametersConverter = new DefaultOAuth2AccessTokenResponseMapConverter();
+ private static final ParameterizedTypeReference>> STRING_OBJECT_MAP = new ParameterizedTypeReference<>() {};
+
+ private final ObjectMapper objectMapper;
+ public CustomAccessTokenResponseHttpMessageConverter(ObjectMapper objectMapper) {
+ this.objectMapper = objectMapper;
+ }
+
+ @Override
+ protected void writeInternal(OAuth2AccessTokenResponse tokenResponse, HttpOutputMessage outputMessage)
+ throws HttpMessageNotWritableException {
+ try {
+ Map tokenResponseParameters = this.accessTokenResponseParametersConverter.convert(tokenResponse);
+ GenericHttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter(objectMapper);
+ jsonMessageConverter.write(Result.succeed(tokenResponseParameters), STRING_OBJECT_MAP.getType(), MediaType.APPLICATION_JSON, outputMessage);
+ }
+ catch (Exception ex) {
+ throw new HttpMessageNotWritableException(
+ "An error occurred writing the OAuth 2.0 Access Token Response: " + ex.getMessage(), ex);
+ }
+ }
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/component/CustomeOAuth2TokenCustomizer.java b/zlt-uaa/src/main/java/com/central/oauth/component/CustomeOAuth2TokenCustomizer.java
new file mode 100644
index 00000000..7b5b29b7
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/component/CustomeOAuth2TokenCustomizer.java
@@ -0,0 +1,35 @@
+package com.central.oauth.component;
+
+import com.central.common.constant.SecurityConstants;
+import com.central.common.model.LoginAppUser;
+import com.central.oauth2.common.token.BaseAuthenticationToken;
+import org.springframework.security.authentication.AbstractAuthenticationToken;
+import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenClaimsContext;
+import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenClaimsSet;
+import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenCustomizer;
+
+/**
+ * token 输出增强
+ *
+ * @author: zlt
+ * @date: 2023/12/2
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+public class CustomeOAuth2TokenCustomizer implements OAuth2TokenCustomizer {
+ @Override
+ public void customize(OAuth2TokenClaimsContext context) {
+ OAuth2TokenClaimsSet.Builder claims = context.getClaims();
+ AbstractAuthenticationToken authenticationToken = context.getAuthorizationGrant();
+
+ if (authenticationToken instanceof BaseAuthenticationToken baseAuthenticationToken) {
+ LoginAppUser user = (LoginAppUser) context.getPrincipal().getPrincipal();
+ claims.claim(SecurityConstants.DETAILS_USER_ID, user.getId());
+ claims.claim(SecurityConstants.USERNAME, user.getUsername());
+
+ String account_type = (String)baseAuthenticationToken.getAdditionalParameters().get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
+ claims.claim(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, account_type);
+ }
+ }
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/filter/LoginProcessSetTenantFilter.java b/zlt-uaa/src/main/java/com/central/oauth/component/LoginProcessSetTenantFilter.java
similarity index 89%
rename from zlt-uaa/src/main/java/com/central/oauth/filter/LoginProcessSetTenantFilter.java
rename to zlt-uaa/src/main/java/com/central/oauth/component/LoginProcessSetTenantFilter.java
index da6dad12..57d94efd 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/filter/LoginProcessSetTenantFilter.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/component/LoginProcessSetTenantFilter.java
@@ -1,22 +1,22 @@
-package com.central.oauth.filter;
+package com.central.oauth.component;
import cn.hutool.core.util.ArrayUtil;
import com.central.common.constant.SecurityConstants;
import com.central.common.context.TenantContextHolder;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.savedrequest.DefaultSavedRequest;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
- * 设置租户id过滤器
+ * 授权码模式登录时设置租户id过滤器
*
* @author zlt
* @date 2020/3/29
diff --git a/zlt-uaa/src/main/java/com/central/oauth/config/AuthorizationServerConfig.java b/zlt-uaa/src/main/java/com/central/oauth/config/AuthorizationServerConfig.java
index e7d68db9..51c98439 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/config/AuthorizationServerConfig.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/config/AuthorizationServerConfig.java
@@ -1,178 +1,151 @@
-package com.central.oauth.config;
-
-import cn.hutool.core.util.StrUtil;
-import com.central.common.constant.SecurityConstants;
-import com.central.common.model.SysUser;
-import com.central.oauth.model.Client;
-import com.central.oauth.service.IClientService;
-import com.central.oauth.service.impl.RedisClientDetailsService;
-import com.central.oauth.service.impl.UserDetailServiceFactory;
-import com.central.oauth.utils.OidcIdTokenBuilder;
-import com.central.oauth2.common.constants.IdTokenClaimNames;
-import com.central.oauth2.common.properties.TokenStoreProperties;
-import com.central.oauth2.common.util.AuthUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.autoconfigure.AutoConfigureAfter;
-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.authentication.AuthenticationManager;
-import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
-import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
-import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
-import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
-import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
-import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
-import org.springframework.security.oauth2.provider.OAuth2Authentication;
-import org.springframework.security.oauth2.provider.TokenGranter;
-import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
-import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
-import org.springframework.security.oauth2.provider.token.TokenEnhancer;
-import org.springframework.security.oauth2.provider.token.TokenStore;
-
-import javax.annotation.Resource;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * OAuth2 授权服务器配置
- *
- * @author zlt
- * @date 2018/10/24
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Configuration
-@EnableAuthorizationServer
-@AutoConfigureAfter(AuthorizationServerEndpointsConfigurer.class)
-public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
- /**
- * 注入authenticationManager 来支持 password grant type
- */
- @Autowired
- private AuthenticationManager authenticationManager;
-
- @Resource
- private UserDetailServiceFactory userDetailsServiceFactory;
-
- @Autowired
- private TokenStore tokenStore;
-
- @Autowired
- private WebResponseExceptionTranslator webResponseExceptionTranslator;
-
- @Autowired
- private RedisClientDetailsService clientDetailsService;
-
- @Autowired
- private RandomValueAuthorizationCodeServices authorizationCodeServices;
-
- @Autowired
- private TokenGranter tokenGranter;
-
- /**
- * 配置身份认证器,配置认证方式,TokenStore,TokenGranter,OAuth2RequestFactory
- * @param endpoints
- */
- @Override
- public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
- endpoints.tokenStore(tokenStore)
- .authenticationManager(authenticationManager)
- //.userDetailsService(userDetailsServiceFactory.getService(SecurityConstants.DEF_ACCOUNT_TYPE))
- .authorizationCodeServices(authorizationCodeServices)
- .exceptionTranslator(webResponseExceptionTranslator)
- .tokenGranter(tokenGranter);
- }
-
- /**
- * 配置应用名称 应用id
- * 配置OAuth2的客户端相关信息
- * @param clients
- * @throws Exception
- */
- @Override
- public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
- clients.withClientDetails(clientDetailsService);
- clientDetailsService.loadAllClientToCache();
- }
-
- /**
- * 对应于配置AuthorizationServer安全认证的相关信息,创建ClientCredentialsTokenEndpointFilter核心过滤器
- * @param security
- */
- @Override
- public void configure(AuthorizationServerSecurityConfigurer security) {
- security
- .tokenKeyAccess("isAuthenticated()")
- .checkTokenAccess("permitAll()")
- //让/oauth/token支持client_id以及client_secret作登录认证
- .allowFormAuthenticationForClients();
- }
-
- @Bean
- @Order(1)
- public TokenEnhancer tokenEnhancer(@Autowired(required = false) KeyProperties keyProperties
- , IClientService clientService
- , TokenStoreProperties tokenStoreProperties) {
- return (accessToken, authentication) -> {
- Set responseTypes = authentication.getOAuth2Request().getResponseTypes();
- Map additionalInfo = new HashMap<>(3);
- String accountType = AuthUtils.getAccountType(authentication.getUserAuthentication());
- if (StrUtil.isNotEmpty(accountType)) {
- additionalInfo.put(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, accountType);
- }
-
- if (responseTypes.contains(SecurityConstants.ID_TOKEN)
- || "authJwt".equals(tokenStoreProperties.getType())) {
- Object principal = authentication.getPrincipal();
- //增加id参数
- if (principal instanceof SysUser) {
- SysUser user = (SysUser)principal;
- if (responseTypes.contains(SecurityConstants.ID_TOKEN)) {
- //生成id_token
- setIdToken(additionalInfo, authentication, keyProperties, clientService, user);
- }
- if ("authJwt".equals(tokenStoreProperties.getType())) {
- additionalInfo.put("id", user.getId());
- }
- }
- }
- ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
- return accessToken;
- };
- }
-
- /**
- * 生成id_token
- * @param additionalInfo 存储token附加信息对象
- * @param authentication 授权对象
- * @param keyProperties 密钥
- * @param clientService 应用service
- */
- private void setIdToken(Map additionalInfo, OAuth2Authentication authentication
- , KeyProperties keyProperties, IClientService clientService, SysUser user) {
- String clientId = authentication.getOAuth2Request().getClientId();
- Client client = clientService.loadClientByClientId(clientId);
- if (client.getSupportIdToken()) {
- String nonce = authentication.getOAuth2Request().getRequestParameters().get(IdTokenClaimNames.NONCE);
- long now = System.currentTimeMillis();
- long expiresAt = System.currentTimeMillis() + client.getIdTokenValiditySeconds() * 1000;
- String idToken = OidcIdTokenBuilder.builder(keyProperties)
- .issuer(SecurityConstants.ISS)
- .issuedAt(now)
- .expiresAt(expiresAt)
- .subject(String.valueOf(user.getId()))
- .name(user.getNickname())
- .loginName(user.getUsername())
- .picture(user.getHeadImgUrl())
- .audience(clientId)
- .nonce(nonce)
- .build();
-
- additionalInfo.put(SecurityConstants.ID_TOKEN, idToken);
- }
- }
-}
+package com.central.oauth.config;
+
+import com.central.common.config.DefaultPasswordConfig;
+import com.central.oauth.component.LoginProcessSetTenantFilter;
+import com.central.oauth.service.IValidateCodeService;
+import com.central.oauth.service.impl.RedisSecurityContextRepository;
+import com.central.oauth.service.impl.RegisteredClientService;
+import com.central.oauth.service.impl.UserDetailServiceFactory;
+import com.central.oauth.support.mobile.MobileAuthenticationConverter;
+import com.central.oauth.support.mobile.MobileAuthenticationProvider;
+import com.central.oauth.support.openid.OpenIdAuthenticationConverter;
+import com.central.oauth.support.openid.OpenIdAuthenticationProvider;
+import com.central.oauth.support.password.PasswordAuthenticationConverter;
+import com.central.oauth.support.password.PasswordAuthenticationProvider;
+import com.central.oauth.support.passwordCode.PasswordCodeAuthenticationConverter;
+import com.central.oauth.support.passwordCode.PasswordCodeAuthenticationProvider;
+import com.central.oauth2.common.component.CustomAuthorizationServiceIntrospector;
+import com.central.oauth2.common.component.CustomBearerTokenResolver;
+import com.central.oauth2.common.config.BaseSecurityConfig;
+import com.central.oauth2.common.enums.TokenType;
+import com.central.oauth2.common.properties.SecurityProperties;
+import com.central.oauth2.common.util.OAuth2ConfigurerUtils;
+import lombok.RequiredArgsConstructor;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
+import org.springframework.core.Ordered;
+import org.springframework.core.annotation.Order;
+import org.springframework.security.config.Customizer;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.security.oauth2.core.OAuth2Token;
+import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
+import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer;
+import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
+import org.springframework.security.oauth2.server.authorization.web.authentication.DelegatingAuthenticationConverter;
+import org.springframework.security.web.AuthenticationEntryPoint;
+import org.springframework.security.web.SecurityFilterChain;
+import org.springframework.security.web.access.AccessDeniedHandler;
+import org.springframework.security.web.authentication.AuthenticationConverter;
+import org.springframework.security.web.authentication.AuthenticationFailureHandler;
+import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
+import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
+import org.springframework.security.web.authentication.logout.LogoutHandler;
+import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
+
+import java.util.Arrays;
+
+/**
+ * @author: zlt
+ * @date: 2023/11/16
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+@Configuration
+@RequiredArgsConstructor
+@EnableWebSecurity
+@Import({BaseSecurityConfig.class, DefaultPasswordConfig.class})
+public class AuthorizationServerConfig {
+ private final UserDetailServiceFactory userDetailsServiceFactory;
+ private final PasswordEncoder passwordEncoder;
+ private final AuthenticationFailureHandler authenticationFailureHandler;
+ private final CustomBearerTokenResolver customBearerTokenResolver;
+ private final AuthenticationEntryPoint authenticationEntryPoint;
+ private final LogoutHandler logoutHandler;
+ private final LogoutSuccessHandler logoutSuccessHandler;
+ private final AccessDeniedHandler oAuth2AccessDeniedHandler;
+ private final SecurityProperties securityProperties;
+ private final IValidateCodeService validateCodeService;
+ private final RegisteredClientService registeredClientService;
+ private final RedisSecurityContextRepository securityContextRepository;
+ private final AuthenticationSuccessHandler authenticationSuccessHandler;
+
+ /**
+ * spring security 默认的安全策略
+ */
+ @Bean
+ @Order(Ordered.HIGHEST_PRECEDENCE)
+ public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
+ http.authorizeHttpRequests(authorizeRequests -> {
+ // 授权服务器关闭basic认证
+ authorizeRequests
+ .requestMatchers(securityProperties.getIgnore().getUrls()).permitAll()
+ .anyRequest().authenticated();
+ });
+ // 登录登出配置
+ http.apply(new FormIdentityLoginConfigurer(logoutSuccessHandler, logoutHandler));
+
+ // 登录的认证信息储存策略(redis)
+ http.securityContext(context -> context.securityContextRepository(securityContextRepository));
+
+ // 授权配置
+ OAuth2AuthorizationService authorizationService = OAuth2ConfigurerUtils.getAuthorizationService(http);
+ OAuth2TokenGenerator extends OAuth2Token> tokenGenerator = OAuth2ConfigurerUtils.getTokenGenerator(http);
+
+ OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer();
+ http.apply(authorizationServerConfigurer.tokenEndpoint((tokenEndpoint) -> tokenEndpoint
+ // 注入自定义的授权认证Converter
+ .accessTokenRequestConverter(accessTokenRequestConverter())
+ // 登录失败处理器
+ .errorResponseHandler(authenticationFailureHandler)
+ // 登录成功处理器
+ .accessTokenResponseHandler(authenticationSuccessHandler)
+ // 自定义授权类型
+ .authenticationProvider(new PasswordAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory, passwordEncoder))
+ .authenticationProvider(new PasswordCodeAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory, passwordEncoder, validateCodeService))
+ .authenticationProvider(new OpenIdAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory))
+ .authenticationProvider(new MobileAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory, passwordEncoder))
+ )
+ // 开启OpenID Connect 1.0协议相关端点
+ .oidc(Customizer.withDefaults())
+ )
+ // 应用鉴权
+ .clientAuthentication(clientConfig -> clientConfig.errorResponseHandler(authenticationFailureHandler));
+ // 指定授权服务
+ http.apply(authorizationServerConfigurer
+ .authorizationService(authorizationService)
+ .authorizationEndpoint(endpoint -> endpoint
+ .errorResponseHandler(authenticationFailureHandler)
+ ));
+
+ // 资源服务配置
+ http.oauth2ResourceServer(oauth2 -> {
+ oauth2.authenticationEntryPoint(authenticationEntryPoint)
+ .bearerTokenResolver(customBearerTokenResolver)
+ .accessDeniedHandler(oAuth2AccessDeniedHandler);
+ if (TokenType.JWT.getName().equals(securityProperties.getResourceServer().getTokenType())) {
+ oauth2.jwt(Customizer.withDefaults());
+ } else {
+ oauth2.opaqueToken(token -> token.introspector(new CustomAuthorizationServiceIntrospector(authorizationService)));
+ }
+ });
+
+ http.addFilterBefore(new LoginProcessSetTenantFilter(), UsernamePasswordAuthenticationFilter.class);
+
+ // 缓存应用
+ registeredClientService.loadAllClientToCache();
+
+ return http.build();
+ }
+
+ private AuthenticationConverter accessTokenRequestConverter() {
+ return new DelegatingAuthenticationConverter(Arrays.asList(
+ new PasswordAuthenticationConverter(),
+ new PasswordCodeAuthenticationConverter(),
+ new OpenIdAuthenticationConverter(),
+ new MobileAuthenticationConverter()));
+ }
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/config/FormIdentityLoginConfigurer.java b/zlt-uaa/src/main/java/com/central/oauth/config/FormIdentityLoginConfigurer.java
new file mode 100644
index 00000000..54d59be2
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/config/FormIdentityLoginConfigurer.java
@@ -0,0 +1,45 @@
+package com.central.oauth.config;
+
+import com.central.common.constant.SecurityConstants;
+import lombok.RequiredArgsConstructor;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
+import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
+import org.springframework.security.config.http.SessionCreationPolicy;
+import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
+import org.springframework.security.web.authentication.logout.LogoutHandler;
+import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
+
+/**
+ * @author: zlt
+ * @date: 2023/11/23
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+@RequiredArgsConstructor
+public class FormIdentityLoginConfigurer extends AbstractHttpConfigurer {
+ private final LogoutSuccessHandler logoutSuccessHandler;
+ private final LogoutHandler logoutHandler;
+
+ @Override
+ public void init(HttpSecurity http) throws Exception {
+ http.formLogin(formLogin -> formLogin
+ .loginPage(SecurityConstants.LOGIN_PAGE)
+ .loginProcessingUrl(SecurityConstants.OAUTH_LOGIN_PRO_URL)
+ .successHandler(new SavedRequestAwareAuthenticationSuccessHandler()))
+ .logout(logout -> logout
+ .logoutUrl(SecurityConstants.LOGOUT_URL)
+ .logoutSuccessHandler(logoutSuccessHandler)
+ .addLogoutHandler(logoutHandler)
+ .deleteCookies("JSESSIONID")
+ .clearAuthentication(true)
+ .invalidateHttpSession(true))
+ .headers(header -> header
+ // 避免iframe同源无法登录许iframe
+ .frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin))
+ .csrf(AbstractHttpConfigurer::disable)
+ .sessionManagement(session -> session
+ .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED));
+ }
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/config/RedisListenerConfig.java b/zlt-uaa/src/main/java/com/central/oauth/config/RedisListenerConfig.java
deleted file mode 100644
index 9daa34aa..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/config/RedisListenerConfig.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package com.central.oauth.config;
-
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Primary;
-import org.springframework.data.redis.connection.RedisConnectionFactory;
-import org.springframework.data.redis.listener.RedisMessageListenerContainer;
-/**
- *
- * redis过期key监听器配置类
- * @author zlt
- *
- */
-@Configuration
-public class RedisListenerConfig {
- @Bean
- @Primary
- public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory factory) {
- RedisMessageListenerContainer container = new RedisMessageListenerContainer();
- container.setConnectionFactory(factory);
- return container;
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/config/SecurityConfig.java b/zlt-uaa/src/main/java/com/central/oauth/config/SecurityConfig.java
index 359c8475..135d9d72 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/config/SecurityConfig.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/config/SecurityConfig.java
@@ -1,167 +1,146 @@
-package com.central.oauth.config;
-
-import com.central.common.constant.SecurityConstants;
-import com.central.common.properties.TenantProperties;
-import com.central.oauth.filter.LoginProcessSetTenantFilter;
-import com.central.oauth.handler.OauthLogoutSuccessHandler;
-import com.central.oauth.password.PasswordAuthenticationProvider;
-import com.central.oauth.service.impl.UserDetailServiceFactory;
-import com.central.oauth.tenant.TenantAuthenticationSecurityConfig;
-import com.central.oauth.tenant.TenantUsernamePasswordAuthenticationFilter;
-import com.central.oauth.mobile.MobileAuthenticationSecurityConfig;
-import com.central.oauth.openid.OpenIdAuthenticationSecurityConfig;
-import com.central.common.config.DefaultPasswordConfig;
-import com.central.oauth2.common.token.CustomWebAuthenticationDetails;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Import;
-import org.springframework.security.authentication.AuthenticationDetailsSource;
-import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
-import org.springframework.security.config.annotation.web.builders.HttpSecurity;
-import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
-import org.springframework.security.config.http.SessionCreationPolicy;
-import org.springframework.security.crypto.password.PasswordEncoder;
-import org.springframework.security.web.AuthenticationEntryPoint;
-import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
-import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
-import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
-import org.springframework.security.web.authentication.logout.LogoutHandler;
-import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
-
-import javax.annotation.Resource;
-import javax.servlet.http.HttpServletRequest;
-
-/**
- * spring security配置
- * 在WebSecurityConfigurerAdapter不拦截oauth要开放的资源
- *
- * @author zlt
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Configuration
-@Import(DefaultPasswordConfig.class)
-public class SecurityConfig extends WebSecurityConfigurerAdapter {
-
- @Autowired
- private AuthenticationSuccessHandler authenticationSuccessHandler;
-
- @Autowired(required = false)
- private AuthenticationEntryPoint authenticationEntryPoint;
-
- @Resource
- private UserDetailServiceFactory userDetailsServiceFactory;
-
- @Autowired
- private PasswordEncoder passwordEncoder;
-
- @Resource
- private LogoutHandler logoutHandler;
-
- @Resource
- private LogoutSuccessHandler logoutSuccessHandler;
-
- @Autowired
- private OpenIdAuthenticationSecurityConfig openIdAuthenticationSecurityConfig;
-
- @Autowired
- private MobileAuthenticationSecurityConfig mobileAuthenticationSecurityConfig;
-
- @Autowired
- private AuthenticationManager authenticationManager;
-
- @Autowired
- private TenantAuthenticationSecurityConfig tenantAuthenticationSecurityConfig;
-
- @Autowired
- private TenantProperties tenantProperties;
-
- @Autowired
- private AuthenticationDetailsSource authenticationDetailsSource;
-
- /**
- * 这一步的配置是必不可少的,否则SpringBoot会自动配置一个AuthenticationManager,覆盖掉内存中的用户
- * @return 认证管理对象
- */
- @Bean
- @Override
- public AuthenticationManager authenticationManagerBean() throws Exception {
- return super.authenticationManagerBean();
- }
-
- @Bean
- public TenantUsernamePasswordAuthenticationFilter tenantAuthenticationFilter(AuthenticationManager authenticationManager) {
- TenantUsernamePasswordAuthenticationFilter filter = new TenantUsernamePasswordAuthenticationFilter();
- filter.setAuthenticationManager(authenticationManager);
- filter.setFilterProcessesUrl(SecurityConstants.OAUTH_LOGIN_PRO_URL);
- filter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
- filter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(SecurityConstants.LOGIN_FAILURE_PAGE));
- filter.setAuthenticationDetailsSource(authenticationDetailsSource);
- return filter;
- }
-
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests()
- .anyRequest()
- //授权服务器关闭basic认证
- .permitAll()
- .and()
- .logout()
- .logoutUrl(SecurityConstants.LOGOUT_URL)
- .logoutSuccessHandler(logoutSuccessHandler)
- .addLogoutHandler(logoutHandler)
- .clearAuthentication(true)
- .and()
- .apply(openIdAuthenticationSecurityConfig)
- .and()
- .apply(mobileAuthenticationSecurityConfig)
- .and()
- .addFilterBefore(new LoginProcessSetTenantFilter(), UsernamePasswordAuthenticationFilter.class)
- .csrf().disable()
- // 解决不允许显示在iframe的问题
- .headers().frameOptions().disable().cacheControl();
-
- if (tenantProperties.getEnable()) {
- //解决不同租户单点登录时角色没变化
- http.formLogin()
- .loginPage(SecurityConstants.LOGIN_PAGE)
- .and()
- .addFilterAt(tenantAuthenticationFilter(authenticationManager), UsernamePasswordAuthenticationFilter.class)
- .apply(tenantAuthenticationSecurityConfig);
- } else {
- http.formLogin()
- .loginPage(SecurityConstants.LOGIN_PAGE)
- .loginProcessingUrl(SecurityConstants.OAUTH_LOGIN_PRO_URL)
- .successHandler(authenticationSuccessHandler)
- .authenticationDetailsSource(authenticationDetailsSource);
- }
-
-
- // 基于密码 等模式可以无session,不支持授权码模式
- if (authenticationEntryPoint != null) {
- http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
- http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
- } else {
- // 授权码模式单独处理,需要session的支持,此模式可以支持所有oauth2的认证
- http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
- }
- }
-
- /**
- * 全局用户信息
- */
- @Override
- public void configure(AuthenticationManagerBuilder auth) {
- PasswordAuthenticationProvider provider = new PasswordAuthenticationProvider();
- provider.setPasswordEncoder(passwordEncoder);
- provider.setUserDetailsServiceFactory(userDetailsServiceFactory);
- auth.authenticationProvider(provider);
- }
- /*public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
- auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
- }*/
-}
+package com.central.oauth.config;
+
+import cn.hutool.core.util.StrUtil;
+import com.central.common.constant.SecurityConstants;
+import com.central.common.utils.ResponseUtil;
+import com.central.oauth.component.CustomAccessTokenResponseHttpMessageConverter;
+import com.central.oauth.component.CustomeOAuth2TokenCustomizer;
+import com.central.oauth2.common.properties.SecurityProperties;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.catalina.util.StandardSessionIdGenerator;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.server.ServletServerHttpResponse;
+import org.springframework.security.oauth2.core.AuthorizationGrantType;
+import org.springframework.security.oauth2.core.OAuth2AccessToken;
+import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
+import org.springframework.security.oauth2.core.OAuth2RefreshToken;
+import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
+import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
+import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
+import org.springframework.security.oauth2.jwt.JwtClaimsSet;
+import org.springframework.security.oauth2.jwt.JwtEncoder;
+import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
+import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken;
+import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings;
+import org.springframework.security.oauth2.server.authorization.token.*;
+import org.springframework.security.web.authentication.AuthenticationFailureHandler;
+import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
+import org.springframework.util.CollectionUtils;
+
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.Date;
+import java.util.Map;
+
+/**
+ * 服务安全相关配置
+ *
+ * @author: zlt
+ * @date: 2023/11/9
+ *
+ * Blog: http://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+@Configuration
+public class SecurityConfig {
+ /**
+ * token内容增强
+ */
+ @Bean
+ public OAuth2TokenCustomizer jwtTokenCustomizer(){
+ return context -> {
+ JwtClaimsSet.Builder claims = context.getClaims();
+ claims.claim(SecurityConstants.LICENSE_NAME, SecurityConstants.PROJECT_LICENSE);
+ // 客户端模式不返回具体用户信息
+ if (AuthorizationGrantType.CLIENT_CREDENTIALS.equals(context.getAuthorizationGrantType().getValue())) {
+ return;
+ }
+ if (context.getTokenType().equals(OAuth2TokenType.ACCESS_TOKEN)) {
+ claims.claim(SecurityConstants.DETAILS_USER, context.getPrincipal().getPrincipal());
+ } else if (context.getTokenType().getValue().equals(OidcParameterNames.ID_TOKEN)) {
+ claims.claim(IdTokenClaimNames.AUTH_TIME, Date.from(Instant.now()));
+ StandardSessionIdGenerator standardSessionIdGenerator = new StandardSessionIdGenerator();
+ claims.claim("sid", standardSessionIdGenerator.generateSessionId());
+ }
+ };
+ }
+
+ /**
+ * 令牌生成规则实现
+ */
+ @Bean
+ public OAuth2TokenGenerator oAuth2TokenGenerator(JwtEncoder jwtEncoder, OAuth2TokenCustomizer jwtTokenCustomizer) {
+ JwtGenerator jwtGenerator = new JwtGenerator(jwtEncoder);
+ jwtGenerator.setJwtCustomizer(jwtTokenCustomizer);
+
+ OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
+ accessTokenGenerator.setAccessTokenCustomizer(new CustomeOAuth2TokenCustomizer());
+
+ return new DelegatingOAuth2TokenGenerator(
+ jwtGenerator,
+ accessTokenGenerator,
+ new OAuth2RefreshTokenGenerator()
+ );
+ }
+
+ /**
+ * 授权服务信息配置
+ */
+ @Bean
+ public AuthorizationServerSettings authorizationServerSettings(SecurityProperties securityProperties) {
+ return AuthorizationServerSettings.builder()
+ .issuer(securityProperties.getAuth().getIssuer())
+ .authorizationEndpoint(SecurityConstants.AUTH_CODE_URL)
+ .tokenEndpoint(SecurityConstants.OAUTH_TOKEN_URL)
+ .tokenIntrospectionEndpoint(SecurityConstants.OAUTH_CHECK_TOKEN_URL)
+ .jwkSetEndpoint(SecurityConstants.OAUTH_JWKS_URL)
+ .build();
+ }
+
+ /**
+ * 授权错误处理
+ */
+ @Bean
+ public AuthenticationFailureHandler authenticationFailureHandler(ObjectMapper objectMapper) {
+ return (request, response, authException) -> {
+ String msg = null;
+ if (StrUtil.isNotEmpty(authException.getMessage())) {
+ msg = authException.getMessage();
+ } else if (authException instanceof OAuth2AuthenticationException exception) {
+ msg = exception.getError().getErrorCode();
+ }
+ ResponseUtil.responseFailed(objectMapper, response, msg);
+ };
+ }
+
+ @Bean
+ public AuthenticationSuccessHandler authenticationSuccessHandler(ObjectMapper objectMapper) {
+ return (request, response, authentication) -> {
+ OAuth2AccessTokenAuthenticationToken accessTokenAuthentication =
+ (OAuth2AccessTokenAuthenticationToken) authentication;
+
+ OAuth2AccessToken accessToken = accessTokenAuthentication.getAccessToken();
+ OAuth2RefreshToken refreshToken = accessTokenAuthentication.getRefreshToken();
+ Map additionalParameters = accessTokenAuthentication.getAdditionalParameters();
+
+ OAuth2AccessTokenResponse.Builder builder =
+ OAuth2AccessTokenResponse.withToken(accessToken.getTokenValue())
+ .tokenType(accessToken.getTokenType())
+ .scopes(accessToken.getScopes());
+ if (accessToken.getIssuedAt() != null && accessToken.getExpiresAt() != null) {
+ builder.expiresIn(ChronoUnit.SECONDS.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()));
+ }
+ if (refreshToken != null) {
+ builder.refreshToken(refreshToken.getTokenValue());
+ }
+ if (!CollectionUtils.isEmpty(additionalParameters)) {
+ builder.additionalParameters(additionalParameters);
+ }
+ OAuth2AccessTokenResponse accessTokenResponse = builder.build();
+ ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
+ CustomAccessTokenResponseHttpMessageConverter converter = new CustomAccessTokenResponseHttpMessageConverter(objectMapper);
+ converter.write(accessTokenResponse, null, httpResponse);
+ };
+ }
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/config/SecurityHandlerConfig.java b/zlt-uaa/src/main/java/com/central/oauth/config/SecurityHandlerConfig.java
deleted file mode 100644
index 21466313..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/config/SecurityHandlerConfig.java
+++ /dev/null
@@ -1,86 +0,0 @@
-package com.central.oauth.config;
-
-import com.central.oauth.exception.ValidateCodeException;
-import com.central.oauth.handler.OauthLogoutHandler;
-import com.central.oauth.handler.OauthLogoutSuccessHandler;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.http.ResponseEntity;
-import org.springframework.security.authentication.InternalAuthenticationServiceException;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.oauth2.common.exceptions.*;
-import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
-import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
-import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
-import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
-import org.springframework.security.web.authentication.logout.LogoutHandler;
-import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-
-/**
- * 认证错误处理
- *
- * @author zlt
- */
-@Slf4j
-@Configuration
-public class SecurityHandlerConfig {
- @Bean
- public LogoutHandler logoutHandler() {
- return new OauthLogoutHandler();
- }
-
- @Bean
- public LogoutSuccessHandler logoutSuccessHandler() {
- return new OauthLogoutSuccessHandler();
- }
-
- @Bean
- public WebResponseExceptionTranslator webResponseExceptionTranslator() {
- return new DefaultWebResponseExceptionTranslator() {
- private static final String BAD_MSG = "坏的凭证";
- private static final String BAD_MSG_EN = "Bad credentials";
-
- @Override
- public ResponseEntity translate(Exception e) throws Exception {
- OAuth2Exception oAuth2Exception;
- if (e.getMessage() != null
- && (BAD_MSG.equals(e.getMessage()) || BAD_MSG_EN.equals(e.getMessage()))) {
- oAuth2Exception = new InvalidGrantException("用户名或密码错误", e);
- } else if (e instanceof InternalAuthenticationServiceException
- || e instanceof ValidateCodeException) {
- oAuth2Exception = new InvalidGrantException(e.getMessage(), e);
- } else if (e instanceof OAuth2Exception) {
- oAuth2Exception = (OAuth2Exception)e;
- } else {
- oAuth2Exception = new UnsupportedResponseTypeException("服务内部错误", e);
- }
- ResponseEntity response = super.translate(oAuth2Exception);
- ResponseEntity.status(oAuth2Exception.getHttpErrorCode());
- response.getBody().addAdditionalInformation("resp_code", oAuth2Exception.getHttpErrorCode() + "");
- response.getBody().addAdditionalInformation("resp_msg", oAuth2Exception.getMessage());
-
- return response;
- }
- };
- }
-
- /**
- * 登陆成功
- */
- @Bean
- public AuthenticationSuccessHandler loginSuccessHandler() {
- return new SavedRequestAwareAuthenticationSuccessHandler() {
- @Override
- public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
- Authentication authentication) throws IOException, ServletException {
- super.onAuthenticationSuccess(request, response, authentication);
- }
- };
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/config/TokenGranterConfig.java b/zlt-uaa/src/main/java/com/central/oauth/config/TokenGranterConfig.java
deleted file mode 100644
index 067ca3c7..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/config/TokenGranterConfig.java
+++ /dev/null
@@ -1,179 +0,0 @@
-package com.central.oauth.config;
-
-import com.central.oauth.granter.MobilePwdGranter;
-import com.central.oauth.granter.OpenIdGranter;
-import com.central.oauth.granter.PwdImgCodeGranter;
-import com.central.oauth.service.IValidateCodeService;
-import com.central.oauth.service.impl.CustomTokenServices;
-import com.central.oauth.service.impl.UserDetailServiceFactory;
-import com.central.oauth.service.impl.UserDetailsByNameServiceFactoryWrapper;
-import com.central.oauth2.common.properties.SecurityProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.authentication.ProviderManager;
-import org.springframework.security.oauth2.common.OAuth2AccessToken;
-import org.springframework.security.oauth2.provider.*;
-import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenGranter;
-import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
-import org.springframework.security.oauth2.provider.code.AuthorizationCodeTokenGranter;
-import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
-import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
-import org.springframework.security.oauth2.provider.implicit.ImplicitTokenGranter;
-import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;
-import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter;
-import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
-import org.springframework.security.oauth2.provider.token.*;
-import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;
-
-import javax.annotation.Resource;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * token授权模式配置类
- *
- * @author zlt
- * @date 2020/7/11
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Configuration
-public class TokenGranterConfig {
- @Autowired
- private ClientDetailsService clientDetailsService;
-
- @Resource
- private UserDetailServiceFactory userDetailsServiceFactory;
-
- @Autowired
- private AuthenticationManager authenticationManager;
-
- @Autowired
- private TokenStore tokenStore;
-
- @Autowired(required = false)
- private List tokenEnhancer;
-
- @Autowired
- private IValidateCodeService validateCodeService;
-
- @Autowired
- private RandomValueAuthorizationCodeServices authorizationCodeServices;
-
- private boolean reuseRefreshToken = true;
-
- private AuthorizationServerTokenServices tokenServices;
-
- private TokenGranter tokenGranter;
-
- @Resource
- private SecurityProperties securityProperties;
-
- /**
- * 授权模式
- */
- @Bean
- @ConditionalOnMissingBean
- public TokenGranter tokenGranter(DefaultTokenServices tokenServices) {
- if (tokenGranter == null) {
- tokenGranter = new TokenGranter() {
- private CompositeTokenGranter delegate;
-
- @Override
- public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) {
- if (delegate == null) {
- delegate = new CompositeTokenGranter(getAllTokenGranters(tokenServices));
- }
- return delegate.grant(grantType, tokenRequest);
- }
- };
- }
- return tokenGranter;
- }
-
- /**
- * 所有授权模式:默认的5种模式 + 自定义的模式
- */
- protected List getAllTokenGranters(DefaultTokenServices tokenServices) {
- AuthorizationCodeServices authorizationCodeServices = authorizationCodeServices();
- OAuth2RequestFactory requestFactory = requestFactory();
- //获取默认的授权模式
- List tokenGranters = getDefaultTokenGranters(tokenServices, authorizationCodeServices, requestFactory);
- if (authenticationManager != null) {
- // 添加密码加图形验证码模式
- tokenGranters.add(new PwdImgCodeGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory, validateCodeService));
- // 添加openId模式
- tokenGranters.add(new OpenIdGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));
- // 添加手机号加密码授权模式
- tokenGranters.add(new MobilePwdGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));
- }
- return tokenGranters;
- }
-
- /**
- * 默认的授权模式
- */
- private List getDefaultTokenGranters(AuthorizationServerTokenServices tokenServices
- , AuthorizationCodeServices authorizationCodeServices, OAuth2RequestFactory requestFactory) {
- List tokenGranters = new ArrayList<>();
- // 添加授权码模式
- tokenGranters.add(new AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, clientDetailsService, requestFactory));
- // 添加刷新令牌的模式
- tokenGranters.add(new RefreshTokenGranter(tokenServices, clientDetailsService, requestFactory));
- // 添加隐士授权模式
- tokenGranters.add(new ImplicitTokenGranter(tokenServices, clientDetailsService, requestFactory));
- // 添加客户端模式
- tokenGranters.add(new ClientCredentialsTokenGranter(tokenServices, clientDetailsService, requestFactory));
- if (authenticationManager != null) {
- // 添加密码模式
- tokenGranters.add(new ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));
- }
- return tokenGranters;
- }
-
- private AuthorizationCodeServices authorizationCodeServices() {
- if (authorizationCodeServices == null) {
- authorizationCodeServices = new InMemoryAuthorizationCodeServices();
- }
- return authorizationCodeServices;
- }
-
- private OAuth2RequestFactory requestFactory() {
- return new DefaultOAuth2RequestFactory(clientDetailsService);
- }
-
- @Bean
- @ConditionalOnMissingBean
- protected DefaultTokenServices createDefaultTokenServices() {
- DefaultTokenServices tokenServices = new CustomTokenServices(securityProperties.getAuth());
- tokenServices.setTokenStore(tokenStore);
- tokenServices.setSupportRefreshToken(true);
- tokenServices.setReuseRefreshToken(reuseRefreshToken);
- tokenServices.setClientDetailsService(clientDetailsService);
- tokenServices.setTokenEnhancer(tokenEnhancer());
- addUserDetailsService(tokenServices);
- return tokenServices;
- }
-
- private TokenEnhancer tokenEnhancer() {
- if (tokenEnhancer != null) {
- TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
- tokenEnhancerChain.setTokenEnhancers(tokenEnhancer);
- return tokenEnhancerChain;
- }
- return null;
- }
-
- private void addUserDetailsService(DefaultTokenServices tokenServices) {
- if (this.userDetailsServiceFactory != null) {
- PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
- provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceFactoryWrapper<>(this.userDetailsServiceFactory));
- tokenServices.setAuthenticationManager(new ProviderManager(Collections.singletonList(provider)));
- }
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/config/WebMvcConfig.java b/zlt-uaa/src/main/java/com/central/oauth/config/WebMvcConfig.java
deleted file mode 100644
index b98efd9a..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/config/WebMvcConfig.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package com.central.oauth.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 {
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/controller/ClientController.java b/zlt-uaa/src/main/java/com/central/oauth/controller/ClientController.java
index 4dd8097a..94055605 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/controller/ClientController.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/controller/ClientController.java
@@ -2,13 +2,13 @@ package com.central.oauth.controller;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
-import com.central.oauth.dto.ClientDto;
import com.central.oauth.model.Client;
-import com.central.oauth.service.IClientService;
+import com.central.oauth.service.impl.RegisteredClientService;
+import com.central.oauth2.common.pojo.ClientDto;
import com.google.common.collect.Maps;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import org.springframework.beans.factory.annotation.Autowired;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@@ -19,44 +19,45 @@ import java.util.Map;
*
* @author zlt
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
-@Api(tags = "应用")
+@Tag(name = "应用")
@RestController
@RequestMapping("/clients")
+@RequiredArgsConstructor
public class ClientController {
- @Autowired
- private IClientService clientService;
+ private final RegisteredClientService clientService;
@GetMapping("/list")
- @ApiOperation(value = "应用列表")
- public PageResult list(@RequestParam Map params) {
+ @Operation(summary = "应用列表")
+ public PageResult list(@RequestParam Map params) {
return clientService.listClient(params, true);
}
@GetMapping("/{id}")
- @ApiOperation(value = "根据id获取应用")
- public Client get(@PathVariable Long id) {
+ @Operation(summary = "根据id获取应用")
+ public ClientDto get(@PathVariable Long id) {
return clientService.getById(id);
}
@GetMapping("/all")
- @ApiOperation(value = "所有应用")
- public Result> allClient() {
- PageResult page = clientService.listClient(Maps.newHashMap(), false);
+ @Operation(summary = "所有应用")
+ public Result> allClient() {
+ PageResult page = clientService.listClient(Maps.newHashMap(), false);
return Result.succeed(page.getData());
}
@DeleteMapping("/{id}")
- @ApiOperation(value = "删除应用")
+ @Operation(summary = "删除应用")
public void delete(@PathVariable Long id) {
clientService.delClient(id);
}
@PostMapping("/saveOrUpdate")
- @ApiOperation(value = "保存或者修改应用")
- public Result saveOrUpdate(@RequestBody ClientDto clientDto) throws Exception {
- return clientService.saveClient(clientDto);
+ @Operation(summary = "保存或者修改应用")
+ public Result saveOrUpdate(@RequestBody Client client) throws Exception {
+ clientService.saveClient(client);
+ return Result.succeed("操作成功");
}
}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/controller/TokensController.java b/zlt-uaa/src/main/java/com/central/oauth/controller/TokensController.java
index 088d44f3..97aad393 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/controller/TokensController.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/controller/TokensController.java
@@ -1,36 +1,25 @@
package com.central.oauth.controller;
-import com.central.common.constant.SecurityConstants;
import com.central.common.model.PageResult;
-import com.central.common.model.Result;
import com.central.oauth.model.TokenVo;
import com.central.oauth.service.ITokensService;
-import com.central.oauth2.common.util.AuthUtils;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.security.authentication.BadCredentialsException;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.crypto.password.PasswordEncoder;
-import org.springframework.security.oauth2.provider.ClientDetails;
-import org.springframework.security.oauth2.provider.ClientDetailsService;
-import org.springframework.web.bind.annotation.*;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
-import javax.servlet.http.HttpServletRequest;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
import java.util.Map;
-import java.util.stream.Collectors;
/**
* token管理接口
*
* @author zlt
*/
-@Api(tags = "Token管理")
+@Tag(name = "Token管理")
@Slf4j
@RestController
@RequestMapping("/tokens")
@@ -38,36 +27,9 @@ public class TokensController {
@Resource
private ITokensService tokensService;
- @Resource
- private ClientDetailsService clientDetailsService;
-
- @Resource
- private PasswordEncoder passwordEncoder;
-
@GetMapping("")
- @ApiOperation(value = "token列表")
+ @Operation(summary = "token列表")
public PageResult list(@RequestParam Map params, String tenantId) {
return tokensService.listTokens(params, tenantId);
}
-
- @GetMapping("/key")
- @ApiOperation(value = "获取jwt密钥")
- public Result key(HttpServletRequest request) {
- try {
- String[] clientArr = AuthUtils.extractClient(request);
- ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientArr[0]);
- if (clientDetails == null || !passwordEncoder.matches(clientArr[1], clientDetails.getClientSecret())) {
- throw new BadCredentialsException("应用ID或密码错误");
- }
- } catch (AuthenticationException ae) {
- return Result.failed(ae.getMessage());
- }
- org.springframework.core.io.Resource res = new ClassPathResource(SecurityConstants.RSA_PUBLIC_KEY);
- try (BufferedReader br = new BufferedReader(new InputStreamReader(res.getInputStream()))) {
- return Result.succeed(br.lines().collect(Collectors.joining("\n")));
- } catch (IOException ioe) {
- log.error("key error", ioe);
- return Result.failed(ioe.getMessage());
- }
- }
}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/controller/ValidateCodeController.java b/zlt-uaa/src/main/java/com/central/oauth/controller/ValidateCodeController.java
index a85d4726..a387b76d 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/controller/ValidateCodeController.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/controller/ValidateCodeController.java
@@ -1,11 +1,11 @@
package com.central.oauth.controller;
+import cn.hutool.captcha.CaptchaUtil;
+import cn.hutool.captcha.LineCaptcha;
import com.central.common.constant.SecurityConstants;
import com.central.common.model.Result;
import com.central.oauth.service.IValidateCodeService;
-import com.wf.captcha.base.Captcha;
-import com.wf.captcha.GifCaptcha;
-import com.wf.captcha.utils.CaptchaUtil;
+import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
@@ -13,7 +13,7 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
-import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
/**
* 验证码提供
@@ -31,18 +31,20 @@ public class ValidateCodeController {
* @throws Exception
*/
@GetMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{deviceId}")
- public void createCode(@PathVariable String deviceId, HttpServletResponse response) throws Exception {
+ public void createCode(@PathVariable String deviceId, HttpServletResponse response) throws IOException {
+ Assert.notNull(deviceId, "机器码不能为空");
Assert.notNull(deviceId, "机器码不能为空");
// 设置请求头为输出图片类型
- CaptchaUtil.setHeader(response);
- // 三个参数分别为宽、高、位数
- GifCaptcha gifCaptcha = new GifCaptcha(100, 35, 4);
- // 设置类型:字母数字混合
- gifCaptcha.setCharType(Captcha.TYPE_DEFAULT);
+ response.setContentType("image/jpeg");
+ response.setHeader("Pragma", "no-cache");
+ response.setHeader("Cache-Control", "no-cache");
+ response.setDateHeader("Expires", 0);
+ // 三个参数分别为宽、高、验证码字符数、干扰线宽度
+ LineCaptcha captcha = CaptchaUtil.createLineCaptcha(100, 35, 4, 10);
// 保存验证码
- validateCodeService.saveImageCode(deviceId, gifCaptcha.text().toLowerCase());
+ validateCodeService.saveImageCode(deviceId, captcha.getCode().toLowerCase());
// 输出图片流
- gifCaptcha.out(response.getOutputStream());
+ captcha.write(response.getOutputStream());
}
/**
@@ -54,7 +56,7 @@ public class ValidateCodeController {
*/
@ResponseBody
@GetMapping(SecurityConstants.MOBILE_VALIDATE_CODE_URL_PREFIX + "/{mobile}")
- public Result createCode(@PathVariable String mobile) {
+ public Result createCode(@PathVariable String mobile) {
Assert.notNull(mobile, "手机号不能为空");
return validateCodeService.sendSmsCode(mobile);
}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/dto/ClientDto.java b/zlt-uaa/src/main/java/com/central/oauth/dto/ClientDto.java
deleted file mode 100644
index 2b00c02a..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/dto/ClientDto.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package com.central.oauth.dto;
-
-import com.central.oauth.model.Client;
-import lombok.Getter;
-import lombok.Setter;
-
-import java.util.List;
-import java.util.Set;
-
-@Setter
-@Getter
-public class ClientDto extends Client {
- private static final long serialVersionUID = 1475637288060027265L;
-
- private List permissionIds;
-
- private Set serviceIds;
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/exception/CustomOAuth2AuthenticationException.java b/zlt-uaa/src/main/java/com/central/oauth/exception/CustomOAuth2AuthenticationException.java
new file mode 100644
index 00000000..ee8d5097
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/exception/CustomOAuth2AuthenticationException.java
@@ -0,0 +1,17 @@
+package com.central.oauth.exception;
+
+import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
+import org.springframework.security.oauth2.core.OAuth2Error;
+
+/**
+ * @author: zlt
+ * @date: 2023/11/16
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+public class CustomOAuth2AuthenticationException extends OAuth2AuthenticationException {
+ public CustomOAuth2AuthenticationException(String msg) {
+ super(new OAuth2Error(msg), msg);
+ }
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/exception/ValidateCodeException.java b/zlt-uaa/src/main/java/com/central/oauth/exception/ValidateCodeException.java
deleted file mode 100644
index 3123b04c..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/exception/ValidateCodeException.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.central.oauth.exception;
-
-import org.springframework.security.core.AuthenticationException;
-
-/**
- * 验证码异常
- * @author zlt
- */
-public class ValidateCodeException extends AuthenticationException {
- private static final long serialVersionUID = -7285211528095468156L;
-
- public ValidateCodeException(String msg) {
- super(msg);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/filter/OauthTokenAspect.java b/zlt-uaa/src/main/java/com/central/oauth/filter/OauthTokenAspect.java
deleted file mode 100644
index 822b9c7c..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/filter/OauthTokenAspect.java
+++ /dev/null
@@ -1,93 +0,0 @@
-package com.central.oauth.filter;
-
-import com.central.common.constant.SecurityConstants;
-import com.central.common.context.TenantContextHolder;
-import com.central.common.model.Result;
-import com.central.oauth.handler.decryptParamHandler.IDecryptParamHandler;
-import lombok.extern.slf4j.Slf4j;
-import org.aspectj.lang.ProceedingJoinPoint;
-import org.aspectj.lang.annotation.Around;
-import org.aspectj.lang.annotation.Aspect;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.oauth2.common.OAuth2AccessToken;
-import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
-import org.springframework.security.oauth2.common.util.OAuth2Utils;
-import org.springframework.security.oauth2.provider.OAuth2Authentication;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.Resource;
-import java.security.Principal;
-import java.util.Map;
-
-/**
- * oauth-token拦截器
- * 1. 赋值租户
- * 2. 统一返回token格式
- *
- * @author zlt
- * @date 2020/3/29
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Slf4j
-@Component
-@Aspect
-public class OauthTokenAspect {
- @Resource
- private IDecryptParamHandler decryptParamHandler;
-
- @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
- public Object handleControllerMethod(ProceedingJoinPoint joinPoint) throws Throwable {
- try {
- Object[] args = joinPoint.getArgs();
- Principal principal = (Principal) args[0];
- if (!(principal instanceof Authentication)) {
- throw new OAuth2Exception(
- "There is no client authentication. Try adding an appropriate authentication filter.");
- }
- String clientId = getClientId(principal);
- Map parameters = (Map) args[1];
- //解密参数
- decryptParamHandler.decryptParams(parameters);
-
- String grantType = parameters.get(OAuth2Utils.GRANT_TYPE);
- if (!parameters.containsKey(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME)) {
- parameters.put(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, SecurityConstants.DEF_ACCOUNT_TYPE);
- }
-
- //保存租户id
- TenantContextHolder.setTenant(clientId);
- Object proceed = joinPoint.proceed(args);
- if (SecurityConstants.AUTHORIZATION_CODE.equals(grantType)) {
- /*
- 如果使用 @EnableOAuth2Sso 注解不能修改返回格式,否则授权码模式可以统一改
- 因为本项目的 sso-demo/ss-sso 里面使用了 @EnableOAuth2Sso 注解,所以这里就不修改授权码模式的token返回值了
- */
- return proceed;
- } else {
- ResponseEntity responseEntity = (ResponseEntity) proceed;
- OAuth2AccessToken body = responseEntity.getBody();
- return ResponseEntity
- .status(HttpStatus.OK)
- .body(Result.succeed(body));
- }
- } finally {
- TenantContextHolder.clear();
- }
- }
-
- private String getClientId(Principal principal) {
- Authentication client = (Authentication) principal;
- if (!client.isAuthenticated()) {
- throw new OAuth2Exception("The client is not authenticated.");
- }
- String clientId = client.getName();
- if (client instanceof OAuth2Authentication) {
- clientId = ((OAuth2Authentication) client).getOAuth2Request().getClientId();
- }
- return clientId;
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/granter/MobilePwdGranter.java b/zlt-uaa/src/main/java/com/central/oauth/granter/MobilePwdGranter.java
deleted file mode 100644
index 1f774e0d..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/granter/MobilePwdGranter.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package com.central.oauth.granter;
-
-import com.central.oauth2.common.token.MobileAuthenticationToken;
-import org.springframework.security.authentication.AbstractAuthenticationToken;
-import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
-import org.springframework.security.oauth2.provider.*;
-import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
-import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-/**
- * openId授权模式
- *
- * @author zlt
- * @date 2020/7/11
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-public class MobilePwdGranter extends AbstractTokenGranter {
- private static final String GRANT_TYPE = "mobile_password";
-
- private final AuthenticationManager authenticationManager;
-
- public MobilePwdGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices
- , ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
- super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
- this.authenticationManager = authenticationManager;
- }
-
- @Override
- protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
- Map parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
- String mobile = parameters.get("mobile");
- String password = parameters.get("password");
- // Protect from downstream leaks of password
- parameters.remove("password");
-
- Authentication userAuth = new MobileAuthenticationToken(mobile, password);
- ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
- userAuth = authenticationManager.authenticate(userAuth);
- if (userAuth == null || !userAuth.isAuthenticated()) {
- throw new InvalidGrantException("Could not authenticate mobile: " + mobile);
- }
-
- OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
- return new OAuth2Authentication(storedOAuth2Request, userAuth);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/granter/OpenIdGranter.java b/zlt-uaa/src/main/java/com/central/oauth/granter/OpenIdGranter.java
deleted file mode 100644
index fc95bce4..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/granter/OpenIdGranter.java
+++ /dev/null
@@ -1,49 +0,0 @@
-package com.central.oauth.granter;
-
-import com.central.oauth2.common.token.OpenIdAuthenticationToken;
-import org.springframework.security.authentication.*;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
-import org.springframework.security.oauth2.provider.*;
-import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
-import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-/**
- * openId授权模式
- *
- * @author zlt
- * @date 2020/7/11
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-public class OpenIdGranter extends AbstractTokenGranter {
- private static final String GRANT_TYPE = "openId";
-
- private final AuthenticationManager authenticationManager;
-
- public OpenIdGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices
- , ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
- super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
- this.authenticationManager = authenticationManager;
- }
-
- @Override
- protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
- Map parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
- String openId = parameters.get("openId");
-
- Authentication userAuth = new OpenIdAuthenticationToken(openId);
- ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
- userAuth = authenticationManager.authenticate(userAuth);
- if (userAuth == null || !userAuth.isAuthenticated()) {
- throw new InvalidGrantException("Could not authenticate openId: " + openId);
- }
-
- OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
- return new OAuth2Authentication(storedOAuth2Request, userAuth);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/granter/PwdImgCodeGranter.java b/zlt-uaa/src/main/java/com/central/oauth/granter/PwdImgCodeGranter.java
deleted file mode 100644
index 53d2b0d6..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/granter/PwdImgCodeGranter.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.central.oauth.granter;
-
-import com.central.oauth.service.IValidateCodeService;
-import org.springframework.security.authentication.*;
-import org.springframework.security.oauth2.provider.*;
-import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;
-import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-/**
- * password添加图像验证码授权模式
- *
- * @author zlt
- * @date 2020/7/11
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-public class PwdImgCodeGranter extends ResourceOwnerPasswordTokenGranter {
- private static final String GRANT_TYPE = "password_code";
-
- private final IValidateCodeService validateCodeService;
-
- public PwdImgCodeGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices
- , ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, IValidateCodeService validateCodeService) {
- super(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
- this.validateCodeService = validateCodeService;
- }
-
- @Override
- protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
- Map parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
- String deviceId = parameters.get("deviceId");
- String validCode = parameters.get("validCode");
- //校验图形验证码
- validateCodeService.validate(deviceId, validCode);
-
- return super.getOAuth2Authentication(client, tokenRequest);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutHandler.java b/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutHandler.java
index b3a3d49f..c26f2928 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutHandler.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutHandler.java
@@ -1,62 +1,50 @@
-package com.central.oauth.handler;
-
-import cn.hutool.core.util.StrUtil;
-import com.central.oauth.utils.UsernameHolder;
-import com.central.oauth2.common.properties.SecurityProperties;
-import com.central.oauth2.common.util.AuthUtils;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.oauth2.common.OAuth2AccessToken;
-import org.springframework.security.oauth2.common.OAuth2RefreshToken;
-import org.springframework.security.oauth2.provider.OAuth2Authentication;
-import org.springframework.security.oauth2.provider.token.TokenStore;
-import org.springframework.security.web.authentication.logout.LogoutHandler;
-import org.springframework.util.Assert;
-
-import javax.annotation.Resource;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-/**
- * @author zlt
- * @date 2018/10/17
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Slf4j
-public class OauthLogoutHandler implements LogoutHandler {
- @Resource
- private TokenStore tokenStore;
-
- @Resource
- private SecurityProperties securityProperties;
-
- @Override
- public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
- Assert.notNull(tokenStore, "tokenStore must be set");
- String token = request.getParameter("token");
- if (StrUtil.isEmpty(token)) {
- token = AuthUtils.extractToken(request);
- }
- if(StrUtil.isNotEmpty(token)){
- if (securityProperties.getAuth().getUnifiedLogout()) {
- OAuth2Authentication oAuth2Authentication = tokenStore.readAuthentication(token);
- UsernameHolder.setContext(oAuth2Authentication.getName());
- }
-
- OAuth2AccessToken existingAccessToken = tokenStore.readAccessToken(token);
- OAuth2RefreshToken refreshToken;
- if (existingAccessToken != null) {
- if (existingAccessToken.getRefreshToken() != null) {
- log.info("remove refreshToken!", existingAccessToken.getRefreshToken());
- refreshToken = existingAccessToken.getRefreshToken();
- tokenStore.removeRefreshToken(refreshToken);
- }
- log.info("remove existingAccessToken!", existingAccessToken);
- tokenStore.removeAccessToken(existingAccessToken);
- }
- }
- }
-}
+package com.central.oauth.handler;
+
+import cn.hutool.core.util.StrUtil;
+import com.central.oauth.utils.UsernameHolder;
+import com.central.oauth2.common.properties.SecurityProperties;
+import com.central.oauth2.common.util.AuthUtils;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.security.core.Authentication;
+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.web.authentication.logout.LogoutHandler;
+import org.springframework.stereotype.Component;
+import org.springframework.util.Assert;
+
+/**
+ * @author zlt
+ * @date 2018/10/17
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+@Slf4j
+@RequiredArgsConstructor
+@Component
+public class OauthLogoutHandler implements LogoutHandler {
+ private final OAuth2AuthorizationService oAuth2AuthorizationService;
+ private final SecurityProperties securityProperties;
+ @Override
+ public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
+ Assert.notNull(oAuth2AuthorizationService, "oAuth2AuthorizationService must be set");
+ String token = request.getParameter("token");
+ if (StrUtil.isEmpty(token)) {
+ token = AuthUtils.extractToken(request);
+ }
+ if(StrUtil.isNotEmpty(token)){
+ OAuth2Authorization existingAccessToken = oAuth2AuthorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
+ if (existingAccessToken != null) {
+ if (securityProperties.getAuth().getUnifiedLogout()) {
+ UsernameHolder.setContext(existingAccessToken.getPrincipalName());
+ }
+ oAuth2AuthorizationService.remove(existingAccessToken);
+ log.info("remove existingAccessToken!", existingAccessToken.getAccessToken().getToken().getTokenType());
+ }
+ }
+ }
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutSuccessHandler.java b/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutSuccessHandler.java
index 78dae8e0..d2d7d17c 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutSuccessHandler.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutSuccessHandler.java
@@ -1,23 +1,21 @@
package com.central.oauth.handler;
import cn.hutool.core.util.StrUtil;
-import com.central.common.model.Result;
-import com.central.common.utils.JsonUtil;
+import com.central.common.utils.ResponseUtil;
import com.central.oauth.service.impl.UnifiedLogoutService;
import com.central.oauth2.common.properties.SecurityProperties;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
+import org.springframework.stereotype.Component;
-import javax.annotation.Resource;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
-import java.io.PrintWriter;
/**
* @author zlt
@@ -27,14 +25,14 @@ import java.io.PrintWriter;
* Github: https://github.com/zlt2000
*/
@Slf4j
+@RequiredArgsConstructor
+@Component
public class OauthLogoutSuccessHandler implements LogoutSuccessHandler {
+ private static final String REDIRECT_URL = "redirect_url";
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
-
- @Resource
- private UnifiedLogoutService unifiedLogoutService;
-
- @Resource
- private SecurityProperties securityProperties;
+ private final UnifiedLogoutService unifiedLogoutService;
+ private final SecurityProperties securityProperties;
+ private final ObjectMapper objectMapper;
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
@@ -42,18 +40,12 @@ public class OauthLogoutSuccessHandler implements LogoutSuccessHandler {
unifiedLogoutService.allLogout();
}
- String redirectUri = request.getParameter("redirect_uri");
+ String redirectUri = request.getParameter(REDIRECT_URL);
if (StrUtil.isNotEmpty(redirectUri)) {
//重定向指定的地址
redirectStrategy.sendRedirect(request, response, redirectUri);
} else {
- response.setStatus(HttpStatus.OK.value());
- response.setCharacterEncoding("UTF-8");
- response.setContentType(MediaType.APPLICATION_JSON_VALUE);
- PrintWriter writer = response.getWriter();
- String jsonStr = JsonUtil.toJSONString(Result.succeed("登出成功"));
- writer.write(jsonStr);
- writer.flush();
+ ResponseUtil.responseWriter(objectMapper, response, "登出成功", 0);
}
}
}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/handler/decryptParamHandler/IDecryptParamHandler.java b/zlt-uaa/src/main/java/com/central/oauth/handler/decryptParamHandler/IDecryptParamHandler.java
deleted file mode 100644
index 942f3e1c..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/handler/decryptParamHandler/IDecryptParamHandler.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package com.central.oauth.handler.decryptParamHandler;
-
-import cn.hutool.core.collection.CollUtil;
-import cn.hutool.core.util.StrUtil;
-
-import java.util.Map;
-
-/**
- * 解密参数的处理接口
- *
- * @author zlt
- * @version 1.0
- * @date 2022/12/29
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-public interface IDecryptParamHandler {
- String SEPARATOR = ";";
- /**
- * 需要解密的参数名,多个以 ; 隔离
- * 例如:decrypt_param=username;password
- */
- String PARAM_KEY_DECRYPT_PARAM = "decrypt_param";
-
- /**
- * 根据 parameters里面decrypt_param 的值进行参数解密,并把解密后的值替换原值
- * @param parameters 参数集合
- */
- default void decryptParams(Map parameters) {
- if (CollUtil.isNotEmpty(parameters)) {
- //从 parameters 中获取 decrypt_param 参数值
- String decryptParam = parameters.get(PARAM_KEY_DECRYPT_PARAM);
- //如果参数decrypt_param有值,则进行参数解密
- if (StrUtil.isNotEmpty(decryptParam)) {
- String[] paramNames = decryptParam.split(SEPARATOR);
- this.decrypt(paramNames, parameters);
- }
- }
- }
-
- /**
- * 解密并更新参数值
- * @param paramNames 需要解密的参数名
- * @param parameters 参数集合(参数名:参数值)
- */
- void decrypt(String[] paramNames, Map parameters);
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/handler/decryptParamHandler/RsaDecryptParamHandler.java b/zlt-uaa/src/main/java/com/central/oauth/handler/decryptParamHandler/RsaDecryptParamHandler.java
deleted file mode 100644
index ea324f5e..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/handler/decryptParamHandler/RsaDecryptParamHandler.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package com.central.oauth.handler.decryptParamHandler;
-
-import cn.hutool.core.util.StrUtil;
-import cn.hutool.crypto.SecureUtil;
-import cn.hutool.crypto.asymmetric.KeyType;
-import cn.hutool.crypto.asymmetric.RSA;
-import com.central.oauth2.common.properties.AuthProperties;
-import com.central.oauth2.common.properties.SecurityProperties;
-import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
-import org.springframework.stereotype.Service;
-
-import java.util.Map;
-
-/**
- * 使用rsa算法对参数进行解密
- *
- * @author zlt
- * @version 1.0
- * @date 2022/12/29
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Service
-public class RsaDecryptParamHandler implements IDecryptParamHandler {
- private final AuthProperties authProperties;
-
- public RsaDecryptParamHandler(SecurityProperties securityProperties) {
- this.authProperties = securityProperties.getAuth();
- }
-
- @Override
- public void decrypt(String[] paramNames, Map parameters) {
- RSA rsaTools = SecureUtil.rsa(authProperties.getDecryptParamPrivateKey(), null);
- String value;
- for (String param : paramNames) {
- value = parameters.get(param);
- if (StrUtil.isNotEmpty(value)) {
- //解密
- value = this.decrypt(rsaTools, value, param);
- //更新参数为解密后的值
- parameters.put(param, value);
- }
- }
- }
-
- private String decrypt(RSA rsaTools, String value, String param) {
- try {
- return rsaTools.decryptStr(value, KeyType.PrivateKey);
- } catch (Exception e) {
- throw new OAuth2Exception("参数 " + param + " 解密失败!");
- }
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/listener/RedisKeyExpirationListener.java b/zlt-uaa/src/main/java/com/central/oauth/listener/RedisKeyExpirationListener.java
deleted file mode 100644
index eb4e1db7..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/listener/RedisKeyExpirationListener.java
+++ /dev/null
@@ -1,112 +0,0 @@
-package com.central.oauth.listener;
-
-import com.central.common.constant.SecurityConstants;
-import com.central.common.redis.template.RedisRepository;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.lang3.StringUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.data.redis.connection.Message;
-import org.springframework.data.redis.connection.RedisConnection;
-import org.springframework.data.redis.connection.RedisConnectionFactory;
-import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
-import org.springframework.data.redis.listener.RedisMessageListenerContainer;
-import org.springframework.security.oauth2.provider.OAuth2Authentication;
-import org.springframework.security.oauth2.provider.token.store.redis.JdkSerializationStrategy;
-import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStoreSerializationStrategy;
-import org.springframework.stereotype.Component;
-
-/**
- *
- * redis过期key监听器
- * @author zlt
- *
- */
-@Component
-@Slf4j
-public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
- @Autowired
- private RedisRepository redisRepository;
- private RedisTokenStoreSerializationStrategy serializationStrategy = new JdkSerializationStrategy();
- private final RedisConnectionFactory connectionFactory;
-
- public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer, RedisConnectionFactory connectionFactory) {
- super(listenerContainer);
- this.connectionFactory = connectionFactory;
- }
-
- @Override
- public void onMessage(Message message, byte[] pattern) {
- if (message == null) {
- log.debug("message不能为空");
- return;
- }
- //获取失效的的key
- String expiredKey = message.toString();
- if (StringUtils.isEmpty(expiredKey)) {
- log.debug("expiredKey不能为空");
- return;
- }
- String accesskey = expiredKey.substring(0, expiredKey.indexOf(":") + 1);
- if (!"access:".equals(accesskey)) {
- log.debug("非需要监听key,跳过");
- return;
- }
- String accessValue = expiredKey.substring(expiredKey.indexOf(":") + 1);
- // 分布式集群部署下防止一个过期被多个服务重复消费
- String qc = "qc:" + accessValue;
- String oldLock = redisRepository.getAndSet(qc, "1");
- if (StringUtils.isNotEmpty(oldLock) && "1".equals(oldLock)) {
- log.debug("其他节点已经处理了该数据,跳过");
- return;
- }
- byte[] accessBakKey = serializeKey(SecurityConstants.ACCESS_BAK + accessValue);
- byte[] authKey = serializeKey(SecurityConstants.REDIS_TOKEN_AUTH + accessValue);
- RedisConnection conn = getConnection();
- try {
- byte[] access = conn.get(accessBakKey);
- byte[] auth = conn.get(authKey);
- OAuth2Authentication authentication = deserializeAuthentication(auth);
- if (authentication != null) {
- 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.lRem(unameKey, 1, access);
- conn.lRem(clientId, 1, access);
- conn.closePipeline();
- }
- } catch (Exception e) {
- log.error(e.getMessage());
- } finally {
- conn.del(serializeKey(qc));
- conn.close();
- }
-
- }
-
- private byte[] serializeKey(String object) {
- return serialize("" + object);
- }
-
- private byte[] serialize(String string) {
- return serializationStrategy.serialize(string);
- }
-
- private RedisConnection getConnection() {
- return connectionFactory.getConnection();
- }
-
- private OAuth2Authentication deserializeAuthentication(byte[] bytes) {
- return serializationStrategy.deserialize(bytes, OAuth2Authentication.class);
- }
-
- 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);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/mobile/MobileAuthenticationProvider.java b/zlt-uaa/src/main/java/com/central/oauth/mobile/MobileAuthenticationProvider.java
deleted file mode 100644
index 99e5fcde..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/mobile/MobileAuthenticationProvider.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package com.central.oauth.mobile;
-
-import com.central.oauth.service.impl.UserDetailServiceFactory;
-import com.central.oauth2.common.token.MobileAuthenticationToken;
-import lombok.Getter;
-import lombok.Setter;
-import org.springframework.security.authentication.AuthenticationProvider;
-import org.springframework.security.authentication.InternalAuthenticationServiceException;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.security.crypto.password.PasswordEncoder;
-
-/**
- * @author zlt
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Setter
-@Getter
-public class MobileAuthenticationProvider implements AuthenticationProvider {
- private UserDetailServiceFactory userDetailsServiceFactory;
- private PasswordEncoder passwordEncoder;
-
- @Override
- public Authentication authenticate(Authentication authentication) {
- MobileAuthenticationToken authenticationToken = (MobileAuthenticationToken) authentication;
- String mobile = (String) authenticationToken.getPrincipal();
- String password = (String) authenticationToken.getCredentials();
- UserDetails user = userDetailsServiceFactory.getService(authenticationToken).loadUserByMobile(mobile);
- if (user == null) {
- throw new InternalAuthenticationServiceException("手机号或密码错误");
- }
- if (!passwordEncoder.matches(password, user.getPassword())) {
- throw new InternalAuthenticationServiceException("手机号或密码错误");
- }
- MobileAuthenticationToken authenticationResult = new MobileAuthenticationToken(user, password, user.getAuthorities());
- authenticationResult.setDetails(authenticationToken.getDetails());
- return authenticationResult;
- }
-
- @Override
- public boolean supports(Class> authentication) {
- return MobileAuthenticationToken.class.isAssignableFrom(authentication);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/mobile/MobileAuthenticationSecurityConfig.java b/zlt-uaa/src/main/java/com/central/oauth/mobile/MobileAuthenticationSecurityConfig.java
deleted file mode 100644
index 4aaa7a9a..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/mobile/MobileAuthenticationSecurityConfig.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package com.central.oauth.mobile;
-
-import com.central.oauth.service.impl.UserDetailServiceFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
-import org.springframework.security.config.annotation.web.builders.HttpSecurity;
-import org.springframework.security.crypto.password.PasswordEncoder;
-import org.springframework.security.web.DefaultSecurityFilterChain;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.Resource;
-
-/**
- * mobile的相关处理配置
- *
- * @author zlt
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Component
-public class MobileAuthenticationSecurityConfig extends SecurityConfigurerAdapter {
- @Resource
- private UserDetailServiceFactory userDetailsServiceFactory;
-
- @Autowired
- private PasswordEncoder passwordEncoder;
-
- @Override
- public void configure(HttpSecurity http) {
- //mobile provider
- MobileAuthenticationProvider provider = new MobileAuthenticationProvider();
- provider.setUserDetailsServiceFactory(userDetailsServiceFactory);
- provider.setPasswordEncoder(passwordEncoder);
- http.authenticationProvider(provider);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/model/Client.java b/zlt-uaa/src/main/java/com/central/oauth/model/Client.java
index a8915966..0d268b4b 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/model/Client.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/model/Client.java
@@ -33,14 +33,9 @@ public class Client extends SuperEntity {
private String additionalInformation = "{}";
private String autoapprove = "true";
/**
- * 是否支持id_token
+ * 令牌类型: reference 引用令牌(不透明), self-contained 自包含令牌(jwt))
*/
- private Boolean supportIdToken = true;
- /**
- * id_token有效时间(s)
- */
- @TableField(value = "id_token_validity")
- private Integer idTokenValiditySeconds = 60;
+ private String tokenFormat = "reference";
private Long creatorId;
}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/model/CustomAuthenticationDetailsSource.java b/zlt-uaa/src/main/java/com/central/oauth/model/CustomAuthenticationDetailsSource.java
deleted file mode 100644
index 77e36ea4..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/model/CustomAuthenticationDetailsSource.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package com.central.oauth.model;
-
-import com.central.common.constant.SecurityConstants;
-import com.central.oauth2.common.token.CustomWebAuthenticationDetails;
-import org.springframework.security.authentication.AuthenticationDetailsSource;
-import org.springframework.stereotype.Component;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-
-/**
- * 表单登录的认证信息对象
- *
- * @author zlt
- * @version 1.0
- * @date 2021/7/21
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Component
-public class CustomAuthenticationDetailsSource implements AuthenticationDetailsSource {
- @Override
- public CustomWebAuthenticationDetails buildDetails(HttpServletRequest context) {
- String remoteAddress = context.getRemoteAddr();
- HttpSession session = context.getSession(false);
- String sessionId = session != null ? session.getId() : null;
- String accountType = context.getParameter(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
- return new CustomWebAuthenticationDetails(remoteAddress, sessionId, accountType);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/model/SupplierDeferredSecurityContext.java b/zlt-uaa/src/main/java/com/central/oauth/model/SupplierDeferredSecurityContext.java
new file mode 100644
index 00000000..b2d557d4
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/model/SupplierDeferredSecurityContext.java
@@ -0,0 +1,54 @@
+package com.central.oauth.model;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.springframework.core.log.LogMessage;
+import org.springframework.security.core.context.DeferredSecurityContext;
+import org.springframework.security.core.context.SecurityContext;
+import org.springframework.security.core.context.SecurityContextHolderStrategy;
+
+import java.util.function.Supplier;
+
+/**
+ * @author: zlt
+ * @date: 2023/12/06
+ *
+ * Blog: http://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+public final class SupplierDeferredSecurityContext implements DeferredSecurityContext {
+ private static final Log logger = LogFactory.getLog(SupplierDeferredSecurityContext.class);
+ private final Supplier supplier;
+ private final SecurityContextHolderStrategy strategy;
+ private SecurityContext securityContext;
+ private boolean missingContext;
+ public SupplierDeferredSecurityContext(Supplier supplier, SecurityContextHolderStrategy strategy) {
+ this.supplier = supplier;
+ this.strategy = strategy;
+ }
+ @Override
+ public SecurityContext get() {
+ init();
+ return this.securityContext;
+ }
+ @Override
+ public boolean isGenerated() {
+ init();
+ return this.missingContext;
+ }
+ private void init() {
+ if (this.securityContext != null) {
+ return;
+ }
+
+ this.securityContext = this.supplier.get();
+ this.missingContext = (this.securityContext == null);
+ if (this.missingContext) {
+ this.securityContext = this.strategy.createEmptyContext();
+ if (logger.isTraceEnabled()) {
+ logger.trace(LogMessage.format("Created %s", this.securityContext));
+ }
+ }
+ }
+
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/model/TokenVo.java b/zlt-uaa/src/main/java/com/central/oauth/model/TokenVo.java
index 2b107138..b9c1b95f 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/model/TokenVo.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/model/TokenVo.java
@@ -9,7 +9,7 @@ import java.util.Date;
/**
* @author zlt
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
diff --git a/zlt-uaa/src/main/java/com/central/oauth/openid/OpenIdAuthenticationProvider.java b/zlt-uaa/src/main/java/com/central/oauth/openid/OpenIdAuthenticationProvider.java
deleted file mode 100644
index 4a4623d8..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/openid/OpenIdAuthenticationProvider.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package com.central.oauth.openid;
-
-import com.central.oauth.service.impl.UserDetailServiceFactory;
-import com.central.oauth2.common.token.OpenIdAuthenticationToken;
-import lombok.Getter;
-import lombok.Setter;
-import org.springframework.security.authentication.AuthenticationProvider;
-import org.springframework.security.authentication.InternalAuthenticationServiceException;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.userdetails.UserDetails;
-
-/**
- * @author zlt
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Setter
-@Getter
-public class OpenIdAuthenticationProvider implements AuthenticationProvider {
- private UserDetailServiceFactory userDetailsServiceFactory;
-
- @Override
- public Authentication authenticate(Authentication authentication) {
- OpenIdAuthenticationToken authenticationToken = (OpenIdAuthenticationToken) authentication;
- String openId = (String) authenticationToken.getPrincipal();
- UserDetails user = userDetailsServiceFactory.getService(authenticationToken).loadUserByUserId(openId);
- if (user == null) {
- throw new InternalAuthenticationServiceException("openId错误");
- }
- OpenIdAuthenticationToken authenticationResult = new OpenIdAuthenticationToken(user, user.getAuthorities());
- authenticationResult.setDetails(authenticationToken.getDetails());
- return authenticationResult;
- }
-
- @Override
- public boolean supports(Class> authentication) {
- return OpenIdAuthenticationToken.class.isAssignableFrom(authentication);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/openid/OpenIdAuthenticationSecurityConfig.java b/zlt-uaa/src/main/java/com/central/oauth/openid/OpenIdAuthenticationSecurityConfig.java
deleted file mode 100644
index f5ef56cb..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/openid/OpenIdAuthenticationSecurityConfig.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.central.oauth.openid;
-
-import com.central.oauth.service.impl.UserDetailServiceFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
-import org.springframework.security.config.annotation.web.builders.HttpSecurity;
-import org.springframework.security.web.DefaultSecurityFilterChain;
-import org.springframework.stereotype.Component;
-
-/**
- * openId的相关处理配置
- *
- * @author zlt
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Component
-public class OpenIdAuthenticationSecurityConfig extends SecurityConfigurerAdapter {
- @Autowired
- private UserDetailServiceFactory userDetailsServiceFactory;
-
- @Override
- public void configure(HttpSecurity http) {
- //openId provider
- OpenIdAuthenticationProvider provider = new OpenIdAuthenticationProvider();
- provider.setUserDetailsServiceFactory(userDetailsServiceFactory);
- http.authenticationProvider(provider);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/password/PasswordAuthenticationProvider.java b/zlt-uaa/src/main/java/com/central/oauth/password/PasswordAuthenticationProvider.java
deleted file mode 100644
index 7fbdd579..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/password/PasswordAuthenticationProvider.java
+++ /dev/null
@@ -1,148 +0,0 @@
-package com.central.oauth.password;
-
-import com.central.oauth.service.impl.UserDetailServiceFactory;
-import lombok.Getter;
-import lombok.Setter;
-import org.springframework.security.authentication.BadCredentialsException;
-import org.springframework.security.authentication.InternalAuthenticationServiceException;
-import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
-import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.security.core.userdetails.UserDetailsPasswordService;
-import org.springframework.security.core.userdetails.UsernameNotFoundException;
-import org.springframework.security.crypto.factory.PasswordEncoderFactories;
-import org.springframework.security.crypto.password.PasswordEncoder;
-import org.springframework.util.Assert;
-
-/**
- * 扩展用户名密码provider
- *
- * @author zlt
- * @version 1.0
- * @date 2021/7/24
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Setter
-@Getter
-public class PasswordAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
- private UserDetailServiceFactory userDetailsServiceFactory;
-
- private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword";
-
- private PasswordEncoder passwordEncoder;
-
- /**
- * The password used to perform
- * {@link PasswordEncoder#matches(CharSequence, String)} on when the user is
- * not found to avoid SEC-2056. This is necessary, because some
- * {@link PasswordEncoder} implementations will short circuit if the password is not
- * in a valid format.
- */
- private volatile String userNotFoundEncodedPassword;
-
- private UserDetailsPasswordService userDetailsPasswordService;
-
- public PasswordAuthenticationProvider() {
- setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());
- }
-
- // ~ Methods
- // ========================================================================================================
-
- @Override
- @SuppressWarnings("deprecation")
- protected void additionalAuthenticationChecks(UserDetails userDetails,
- UsernamePasswordAuthenticationToken authentication)
- throws AuthenticationException {
- if (authentication.getCredentials() == null) {
- logger.debug("Authentication failed: no credentials provided");
-
- throw new BadCredentialsException(messages.getMessage(
- "AbstractUserDetailsAuthenticationProvider.badCredentials",
- "Bad credentials"));
- }
-
- String presentedPassword = authentication.getCredentials().toString();
-
- if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
- logger.debug("Authentication failed: password does not match stored value");
-
- throw new BadCredentialsException(messages.getMessage(
- "AbstractUserDetailsAuthenticationProvider.badCredentials",
- "Bad credentials"));
- }
- }
-
- @Override
- protected void doAfterPropertiesSet() {
- Assert.notNull(this.userDetailsServiceFactory, "A UserDetailsService must be set");
- }
-
- @Override
- protected final UserDetails retrieveUser(String username,
- UsernamePasswordAuthenticationToken authentication)
- throws AuthenticationException {
- prepareTimingAttackProtection();
- try {
- UserDetails loadedUser = userDetailsServiceFactory.getService(authentication).loadUserByUsername(username);
- if (loadedUser == null) {
- throw new InternalAuthenticationServiceException(
- "UserDetailsService returned null, which is an interface contract violation");
- }
- return loadedUser;
- }
- catch (UsernameNotFoundException ex) {
- mitigateAgainstTimingAttack(authentication);
- throw ex;
- }
- catch (InternalAuthenticationServiceException ex) {
- throw ex;
- }
- catch (Exception ex) {
- throw new InternalAuthenticationServiceException(ex.getMessage(), ex);
- }
- }
-
- @Override
- protected Authentication createSuccessAuthentication(Object principal,
- Authentication authentication, UserDetails user) {
- boolean upgradeEncoding = this.userDetailsPasswordService != null
- && this.passwordEncoder.upgradeEncoding(user.getPassword());
- if (upgradeEncoding) {
- String presentedPassword = authentication.getCredentials().toString();
- String newPassword = this.passwordEncoder.encode(presentedPassword);
- user = this.userDetailsPasswordService.updatePassword(user, newPassword);
- }
- return super.createSuccessAuthentication(principal, authentication, user);
- }
-
- private void prepareTimingAttackProtection() {
- if (this.userNotFoundEncodedPassword == null) {
- this.userNotFoundEncodedPassword = this.passwordEncoder.encode(USER_NOT_FOUND_PASSWORD);
- }
- }
-
- private void mitigateAgainstTimingAttack(UsernamePasswordAuthenticationToken authentication) {
- if (authentication.getCredentials() != null) {
- String presentedPassword = authentication.getCredentials().toString();
- this.passwordEncoder.matches(presentedPassword, this.userNotFoundEncodedPassword);
- }
- }
-
- /**
- * Sets the PasswordEncoder instance to be used to encode and validate passwords. If
- * not set, the password will be compared using {@link PasswordEncoderFactories#createDelegatingPasswordEncoder()}
- *
- * @param passwordEncoder must be an instance of one of the {@code PasswordEncoder}
- * types.
- */
- public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
- Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
- this.passwordEncoder = passwordEncoder;
- this.userNotFoundEncodedPassword = null;
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/IClientService.java b/zlt-uaa/src/main/java/com/central/oauth/service/IClientService.java
index eed136a1..306f2c5a 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/service/IClientService.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/service/IClientService.java
@@ -1,29 +1,28 @@
-package com.central.oauth.service;
-
-import com.central.common.model.PageResult;
-import com.central.common.model.Result;
-import com.central.common.service.ISuperService;
-import com.central.oauth.model.Client;
-
-import java.util.Map;
-
-/**
- * @author zlt
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-public interface IClientService extends ISuperService {
- Result saveClient(Client clientDto) throws Exception;
-
- /**
- * 查询应用列表
- * @param params
- * @param isPage 是否分页
- */
- PageResult listClient(Map params, boolean isPage);
-
- void delClient(long id);
-
- Client loadClientByClientId(String clientId);
-}
+package com.central.oauth.service;
+
+import com.central.common.model.PageResult;
+import com.central.common.service.ISuperService;
+import com.central.oauth.model.Client;
+
+import java.util.Map;
+
+/**
+ * @author zlt
+ *
+ * Blog: http://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+public interface IClientService extends ISuperService {
+ void saveClient(Client clientDto) throws Exception;
+
+ /**
+ * 查询应用列表
+ * @param params
+ * @param isPage 是否分页
+ */
+ PageResult listClient(Map params, boolean isPage);
+
+ void delClient(long id);
+
+ Client loadClientByClientId(String clientId);
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/IValidateCodeService.java b/zlt-uaa/src/main/java/com/central/oauth/service/IValidateCodeService.java
index 75ee0c6c..3f69a98b 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/service/IValidateCodeService.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/service/IValidateCodeService.java
@@ -1,40 +1,38 @@
-package com.central.oauth.service;
-
-import com.central.common.model.Result;
-
-import javax.servlet.http.HttpServletRequest;
-
-/**
- * @author zlt
- * @date 2018/12/10
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-public interface IValidateCodeService {
- /**
- * 保存图形验证码
- * @param deviceId 前端唯一标识
- * @param imageCode 验证码
- */
- void saveImageCode(String deviceId, String imageCode);
-
- Result sendSmsCode(String mobile);
-
- /**
- * 获取验证码
- * @param deviceId 前端唯一标识/手机号
- */
- String getCode(String deviceId);
-
- /**
- * 删除验证码
- * @param deviceId 前端唯一标识/手机号
- */
- void remove(String deviceId);
-
- /**
- * 验证验证码
- */
- void validate(String deviceId, String validCode);
-}
+package com.central.oauth.service;
+
+import com.central.common.model.Result;
+
+/**
+ * @author zlt
+ * @date 2018/12/10
+ *
+ * Blog: http://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+public interface IValidateCodeService {
+ /**
+ * 保存图形验证码
+ * @param deviceId 前端唯一标识
+ * @param imageCode 验证码
+ */
+ void saveImageCode(String deviceId, String imageCode);
+
+ Result sendSmsCode(String mobile);
+
+ /**
+ * 获取验证码
+ * @param deviceId 前端唯一标识/手机号
+ */
+ String getCode(String deviceId);
+
+ /**
+ * 删除验证码
+ * @param deviceId 前端唯一标识/手机号
+ */
+ void remove(String deviceId);
+
+ /**
+ * 验证验证码
+ */
+ void validate(String deviceId, String validCode);
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/ZltUserDetailsService.java b/zlt-uaa/src/main/java/com/central/oauth/service/ZltUserDetailsService.java
index c02809d1..a3148273 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/service/ZltUserDetailsService.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/service/ZltUserDetailsService.java
@@ -3,13 +3,12 @@ package com.central.oauth.service;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
-import org.springframework.social.security.SocialUserDetails;
/**
* @author zlt
* @date 2018/12/28
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public interface ZltUserDetailsService extends UserDetailsService {
@@ -31,5 +30,5 @@ public interface ZltUserDetailsService extends UserDetailsService {
* 根据用户id/openId查询用户
* @param userId 用户id/openId
*/
- SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException;
+ UserDetails loadUserByUserId(String userId) throws UsernameNotFoundException;
}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/ClientServiceImpl.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/ClientServiceImpl.java
index a84007ee..aaf43e81 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/ClientServiceImpl.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/ClientServiceImpl.java
@@ -5,17 +5,14 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.lock.DistributedLock;
-import com.central.common.redis.template.RedisRepository;
-import com.central.common.constant.SecurityConstants;
import com.central.common.model.PageResult;
-import com.central.common.model.Result;
import com.central.common.service.impl.SuperServiceImpl;
import com.central.oauth.mapper.ClientMapper;
import com.central.oauth.model.Client;
import com.central.oauth.service.IClientService;
+import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@@ -25,25 +22,21 @@ import java.util.Map;
/**
* @author zlt
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
+@RequiredArgsConstructor
@Service
public class ClientServiceImpl extends SuperServiceImpl implements IClientService {
private final static String LOCK_KEY_CLIENTID = "clientId:";
- @Autowired
- private RedisRepository redisRepository;
+ private final PasswordEncoder passwordEncoder;
- @Autowired
- private PasswordEncoder passwordEncoder;
-
- @Autowired
- private DistributedLock lock;
+ private final DistributedLock lock;
@Override
- public Result saveClient(Client client) throws Exception {
+ public void saveClient(Client client) throws Exception {
client.setClientSecret(passwordEncoder.encode(client.getClientSecretStr()));
String clientId = client.getClientId();
if (client.getId() == null) {
@@ -53,7 +46,6 @@ public class ClientServiceImpl extends SuperServiceImpl im
, LOCK_KEY_CLIENTID+clientId
, new QueryWrapper().eq("client_id", clientId)
, clientId + "已存在");
- return Result.succeed("操作成功");
}
@Override
@@ -71,9 +63,7 @@ public class ClientServiceImpl extends SuperServiceImpl im
@Override
public void delClient(long id) {
- String clientId = baseMapper.selectById(id).getClientId();
baseMapper.deleteById(id);
- redisRepository.del(clientRedisKey(clientId));
}
@Override
@@ -82,8 +72,4 @@ public class ClientServiceImpl extends SuperServiceImpl im
wrapper.eq("client_id", clientId);
return this.getOne(wrapper);
}
-
- private String clientRedisKey(String clientId) {
- return SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId;
- }
}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/CustomRegisteredClientRepository.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/CustomRegisteredClientRepository.java
new file mode 100644
index 00000000..8fe79fe7
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/CustomRegisteredClientRepository.java
@@ -0,0 +1,90 @@
+package com.central.oauth.service.impl;
+
+import cn.hutool.core.util.BooleanUtil;
+import cn.hutool.core.util.StrUtil;
+import com.central.oauth2.common.pojo.ClientDto;
+import lombok.RequiredArgsConstructor;
+import org.springframework.security.oauth2.core.AuthorizationGrantType;
+import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
+import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
+import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
+import org.springframework.security.oauth2.server.authorization.settings.ClientSettings;
+import org.springframework.security.oauth2.server.authorization.settings.OAuth2TokenFormat;
+import org.springframework.security.oauth2.server.authorization.settings.TokenSettings;
+import org.springframework.stereotype.Component;
+
+import java.time.Duration;
+
+/**
+ * @author: zlt
+ * @date: 2023/08/04
+ *
+ * Blog: http://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+@RequiredArgsConstructor
+@Component
+public class CustomRegisteredClientRepository implements RegisteredClientRepository {
+ private final RegisteredClientService clientService;
+ @Override
+ public void save(RegisteredClient registeredClient) {
+
+ }
+
+ @Override
+ public RegisteredClient findById(String id) {
+ return this.findByClientId(id);
+ }
+
+ @Override
+ public RegisteredClient findByClientId(String clientId) {
+ ClientDto clientObj = clientService.loadClientByClientId(clientId);
+ if (clientObj == null) {
+ return null;
+ }
+ RegisteredClient.Builder builder = RegisteredClient.withId(clientObj.getClientId())
+ .clientId(clientObj.getClientId())
+ .clientSecret(clientObj.getClientSecret())
+ .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
+
+ if (StrUtil.isNotBlank(clientObj.getAuthorizedGrantTypes())) {
+ for (String authorizedGrantType : clientObj.getAuthorizedGrantTypes().split(StrUtil.COMMA)) {
+ builder.authorizationGrantType(new AuthorizationGrantType(authorizedGrantType));
+ }
+ }
+
+ if (StrUtil.isNotBlank(clientObj.getWebServerRedirectUri())) {
+ for (String redirectUri : clientObj.getWebServerRedirectUri().split(StrUtil.COMMA)) {
+ builder.redirectUri(redirectUri);
+ }
+ }
+
+ if (StrUtil.isNotBlank(clientObj.getScope())) {
+ for (String scope : clientObj.getScope().split(StrUtil.COMMA)) {
+ builder.scope(scope);
+ }
+ }
+
+ OAuth2TokenFormat tokenFormat;
+ if (OAuth2TokenFormat.SELF_CONTAINED.getValue().equals(clientObj.getTokenFormat())) {
+ tokenFormat = OAuth2TokenFormat.SELF_CONTAINED;
+ } else {
+ tokenFormat = OAuth2TokenFormat.REFERENCE;
+ }
+
+ return builder
+ .tokenSettings(
+ TokenSettings.builder()
+ .accessTokenFormat(tokenFormat)
+ .accessTokenTimeToLive(Duration.ofSeconds(clientObj.getAccessTokenValiditySeconds()))
+ .refreshTokenTimeToLive(Duration.ofSeconds(clientObj.getRefreshTokenValiditySeconds()))
+ .build()
+ )
+ .clientSettings(
+ ClientSettings.builder()
+ .requireAuthorizationConsent(!BooleanUtil.toBoolean(clientObj.getAutoapprove()))
+ .build()
+ )
+ .build();
+ }
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/CustomTokenServices.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/CustomTokenServices.java
deleted file mode 100644
index 6ce79c31..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/CustomTokenServices.java
+++ /dev/null
@@ -1,258 +0,0 @@
-package com.central.oauth.service.impl;
-
-import com.central.common.constant.SecurityConstants;
-import com.central.oauth2.common.properties.AuthProperties;
-import org.springframework.security.authentication.AbstractAuthenticationToken;
-import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.oauth2.common.*;
-import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
-import org.springframework.security.oauth2.common.exceptions.InvalidScopeException;
-import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
-import org.springframework.security.oauth2.provider.OAuth2Authentication;
-import org.springframework.security.oauth2.provider.OAuth2Request;
-import org.springframework.security.oauth2.provider.TokenRequest;
-import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
-import org.springframework.security.oauth2.provider.token.TokenEnhancer;
-import org.springframework.security.oauth2.provider.token.TokenStore;
-import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
-import org.springframework.transaction.annotation.Transactional;
-
-import java.util.Date;
-import java.util.Set;
-import java.util.UUID;
-
-/**
- * 重写 DefaultTokenServices,实现登录同应用同账号互踢
- *
- * @author zlt
- * @date 2021/1/28
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-public class CustomTokenServices extends DefaultTokenServices {
- private TokenStore tokenStore;
- private TokenEnhancer accessTokenEnhancer;
- private AuthenticationManager authenticationManager;
- private boolean supportRefreshToken = false;
- private boolean reuseRefreshToken = true;
-
- /**
- * 是否登录同应用同账号互踢
- */
- private final AuthProperties authProperties;
-
- public CustomTokenServices(AuthProperties auth) {
- this.authProperties = auth;
- }
-
- @Override
- @Transactional
- public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {
- OAuth2AccessToken existingAccessToken = tokenStore.getAccessToken(authentication);
- OAuth2RefreshToken refreshToken = null;
- if (existingAccessToken != null) {
- if (authProperties.getIsSingleLogin()) {
- if (existingAccessToken.getRefreshToken() != null) {
- tokenStore.removeRefreshToken(existingAccessToken.getRefreshToken());
- }
- tokenStore.removeAccessToken(existingAccessToken);
- } else if (existingAccessToken.isExpired()) {
- if (existingAccessToken.getRefreshToken() != null) {
- refreshToken = existingAccessToken.getRefreshToken();
- // The token store could remove the refresh token when the
- // access token is removed, but we want to
- // be sure...
- tokenStore.removeRefreshToken(refreshToken);
- }
- tokenStore.removeAccessToken(existingAccessToken);
- } else if (authProperties.getIsShareToken()) {
- // oidc每次授权都刷新id_token
- existingAccessToken = refreshIdToken(existingAccessToken, authentication);
- // Re-store the access token in case the authentication has changed
- tokenStore.storeAccessToken(existingAccessToken, authentication);
- return existingAccessToken;
- }
- }
-
- // Only create a new refresh token if there wasn't an existing one
- // associated with an expired access token.
- // Clients might be holding existing refresh tokens, so we re-use it in
- // the case that the old access token
- // expired.
- if (refreshToken == null) {
- refreshToken = createRefreshToken(authentication);
- }
- // But the refresh token itself might need to be re-issued if it has
- // expired.
- else if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
- ExpiringOAuth2RefreshToken expiring = (ExpiringOAuth2RefreshToken) refreshToken;
- if (System.currentTimeMillis() > expiring.getExpiration().getTime()) {
- refreshToken = createRefreshToken(authentication);
- }
- }
-
- OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken);
- tokenStore.storeAccessToken(accessToken, authentication);
- // In case it was modified
- refreshToken = accessToken.getRefreshToken();
- if (refreshToken != null) {
- tokenStore.storeRefreshToken(refreshToken, authentication);
- }
- return accessToken;
-
- }
-
- /**
- * oidc每次授权都刷新id_token
- * @param token 已存在的token
- * @param authentication 认证信息
- */
- private OAuth2AccessToken refreshIdToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
- Set responseTypes = authentication.getOAuth2Request().getResponseTypes();
- if (accessTokenEnhancer != null && responseTypes.contains(SecurityConstants.ID_TOKEN)) {
- return accessTokenEnhancer.enhance(token, authentication);
- }
- return token;
- }
-
- private OAuth2RefreshToken createRefreshToken(OAuth2Authentication authentication) {
- if (!isSupportRefreshToken(authentication.getOAuth2Request())) {
- return null;
- }
- int validitySeconds = getRefreshTokenValiditySeconds(authentication.getOAuth2Request());
- String value = UUID.randomUUID().toString();
- if (validitySeconds > 0) {
- return new DefaultExpiringOAuth2RefreshToken(value, new Date(System.currentTimeMillis()
- + (validitySeconds * 1000L)));
- }
- return new DefaultOAuth2RefreshToken(value);
- }
-
- private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) {
- DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(UUID.randomUUID().toString());
- int validitySeconds = getAccessTokenValiditySeconds(authentication.getOAuth2Request());
- if (validitySeconds > 0) {
- token.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
- }
- token.setRefreshToken(refreshToken);
- token.setScope(authentication.getOAuth2Request().getScope());
-
- return accessTokenEnhancer != null ? accessTokenEnhancer.enhance(token, authentication) : token;
- }
-
- @Override
- @Transactional(noRollbackFor={InvalidTokenException.class, InvalidGrantException.class})
- public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest tokenRequest)
- throws AuthenticationException {
- if (!supportRefreshToken) {
- throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
- }
-
- OAuth2RefreshToken refreshToken = tokenStore.readRefreshToken(refreshTokenValue);
- if (refreshToken == null) {
- throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
- }
-
- OAuth2Authentication authentication = tokenStore.readAuthenticationForRefreshToken(refreshToken);
- if (this.authenticationManager != null && !authentication.isClientOnly()) {
- AbstractAuthenticationToken userAuthentication = (AbstractAuthenticationToken)authentication.getUserAuthentication();
- Object usesrDetails = userAuthentication.getDetails();
- // The client has already been authenticated, but the user authentication might be old now, so give it a
- // chance to re-authenticate.
- Authentication user = new PreAuthenticatedAuthenticationToken(userAuthentication, "", authentication.getAuthorities());
- user = authenticationManager.authenticate(user);
- //保存账号类型
- ((PreAuthenticatedAuthenticationToken)user).setDetails(usesrDetails);
- Object details = authentication.getDetails();
- authentication = new OAuth2Authentication(authentication.getOAuth2Request(), user);
- authentication.setDetails(details);
- }
- String clientId = authentication.getOAuth2Request().getClientId();
- if (clientId == null || !clientId.equals(tokenRequest.getClientId())) {
- throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue);
- }
-
- // clear out any access tokens already associated with the refresh
- // token.
- tokenStore.removeAccessTokenUsingRefreshToken(refreshToken);
-
- if (isExpired(refreshToken)) {
- tokenStore.removeRefreshToken(refreshToken);
- throw new InvalidTokenException("Invalid refresh token (expired): " + refreshToken);
- }
-
- authentication = createRefreshedAuthentication(authentication, tokenRequest);
- if (!reuseRefreshToken) {
- tokenStore.removeRefreshToken(refreshToken);
- refreshToken = createRefreshToken(authentication);
- }
-
- OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken);
- tokenStore.storeAccessToken(accessToken, authentication);
- if (!reuseRefreshToken) {
- tokenStore.storeRefreshToken(accessToken.getRefreshToken(), authentication);
- }
- return accessToken;
- }
-
- private OAuth2Authentication createRefreshedAuthentication(OAuth2Authentication authentication, TokenRequest request) {
- OAuth2Authentication narrowed;
- Set scope = request.getScope();
- OAuth2Request clientAuth = authentication.getOAuth2Request().refresh(request);
- if (scope != null && !scope.isEmpty()) {
- Set originalScope = clientAuth.getScope();
- if (originalScope == null || !originalScope.containsAll(scope)) {
- throw new InvalidScopeException("Unable to narrow the scope of the client authentication to " + scope
- + ".", originalScope);
- }
- else {
- clientAuth = clientAuth.narrowScope(scope);
- }
- }
- narrowed = new OAuth2Authentication(clientAuth, authentication.getUserAuthentication());
- return narrowed;
- }
-
- @Override
- public void setTokenStore(TokenStore tokenStore) {
- this.tokenStore = tokenStore;
- super.setTokenStore(tokenStore);
- }
-
- @Override
- public void setTokenEnhancer(TokenEnhancer accessTokenEnhancer) {
- this.accessTokenEnhancer = accessTokenEnhancer;
- super.setTokenEnhancer(accessTokenEnhancer);
- }
-
- @Override
- public void setAuthenticationManager(AuthenticationManager authenticationManager) {
- this.authenticationManager = authenticationManager;
- super.setAuthenticationManager(authenticationManager);
- }
-
- /**
- * Whether to support the refresh token.
- *
- * @param supportRefreshToken Whether to support the refresh token.
- */
- @Override
- public void setSupportRefreshToken(boolean supportRefreshToken) {
- this.supportRefreshToken = supportRefreshToken;
- super.setSupportRefreshToken(supportRefreshToken);
- }
-
- /**
- * Whether to reuse refresh tokens (until expired).
- *
- * @param reuseRefreshToken Whether to reuse refresh tokens (until expired).
- */
- @Override
- public void setReuseRefreshToken(boolean reuseRefreshToken) {
- this.reuseRefreshToken = reuseRefreshToken;
- super.setReuseRefreshToken(reuseRefreshToken);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisAuthorizationCodeServices.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisAuthorizationCodeServices.java
deleted file mode 100644
index 59a2409f..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisAuthorizationCodeServices.java
+++ /dev/null
@@ -1,56 +0,0 @@
-package com.central.oauth.service.impl;
-
-import com.central.common.redis.template.RedisRepository;
-import org.springframework.data.redis.core.RedisTemplate;
-import org.springframework.data.redis.serializer.RedisSerializer;
-import org.springframework.security.oauth2.provider.OAuth2Authentication;
-import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
-import org.springframework.stereotype.Service;
-
-import java.util.concurrent.TimeUnit;
-
-/**
- * JdbcAuthorizationCodeServices替换
- *
- * @author zlt
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Service
-public class RedisAuthorizationCodeServices extends RandomValueAuthorizationCodeServices {
- private final RedisRepository redisRepository;
- private final RedisSerializer valueSerializer;
-
- public RedisAuthorizationCodeServices(RedisRepository redisRepository) {
- this.redisRepository = redisRepository;
- this.valueSerializer = RedisSerializer.java();
- }
-
- /**
- * 替换JdbcAuthorizationCodeServices的存储策略
- * 将存储code到redis,并设置过期时间,10分钟
- */
- @Override
- protected void store(String code, OAuth2Authentication authentication) {
- redisRepository.setExpire(redisKey(code), authentication, 10, TimeUnit.MINUTES, valueSerializer);
- }
-
- @Override
- protected OAuth2Authentication remove(final String code) {
- String codeKey = redisKey(code);
- OAuth2Authentication token = (OAuth2Authentication) redisRepository.get(codeKey, valueSerializer);
- redisRepository.del(codeKey);
- return token;
- }
-
- /**
- * redis中 code key的前缀
- *
- * @param code
- * @return
- */
- private String redisKey(String code) {
- return "oauth:code:" + code;
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisClientDetailsService.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisClientDetailsService.java
deleted file mode 100644
index 456b91bd..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisClientDetailsService.java
+++ /dev/null
@@ -1,110 +0,0 @@
-package com.central.oauth.service.impl;
-
-import com.central.common.constant.SecurityConstants;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.data.redis.core.RedisTemplate;
-import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
-import org.springframework.security.oauth2.provider.ClientDetails;
-import org.springframework.security.oauth2.provider.NoSuchClientException;
-import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
-import org.springframework.stereotype.Service;
-import org.springframework.util.CollectionUtils;
-
-import javax.sql.DataSource;
-import java.util.List;
-
-/**
- * @author zlt
- * @version 创建时间:2017年11月12日 上午22:57:51
- * 类说明
- * 将oauth_client_details表数据缓存到redis,这里做个缓存优化
- * layui模块中有对oauth_client_details的crud, 注意同步redis的数据
- * 注意对oauth_client_details清楚redis db部分数据的清空
- */
-@Slf4j
-@Service
-public class RedisClientDetailsService extends JdbcClientDetailsService {
- private RedisTemplate redisTemplate;
-
- public RedisClientDetailsService(DataSource dataSource, RedisTemplate redisTemplate) {
- super(dataSource);
- this.redisTemplate = redisTemplate;
- }
-
- @Override
- public ClientDetails loadClientByClientId(String clientId) {
- // 先从redis获取
- ClientDetails clientDetails = (ClientDetails) redisTemplate.opsForValue().get(clientRedisKey(clientId));
- if (clientDetails == null) {
- clientDetails = cacheAndGetClient(clientId);
- }
- return clientDetails;
- }
-
- /**
- * 缓存client并返回client
- * @param clientId
- * @return
- */
- private ClientDetails cacheAndGetClient(String clientId) {
- // 从数据库读取
- ClientDetails clientDetails = null;
- try {
- clientDetails = super.loadClientByClientId(clientId);
- if (clientDetails != null) {
- // 写入redis缓存
- redisTemplate.opsForValue().set(clientRedisKey(clientId), clientDetails);
- log.info("缓存clientId:{},{}", clientId, clientDetails);
- }
- } catch (NoSuchClientException e) {
- log.error("clientId:{},{}", clientId, clientId);
- } catch (InvalidClientException e) {
- log.error("cacheAndGetClient-invalidClient:{}", clientId, e);
- }
- return clientDetails;
- }
-
- @Override
- public void updateClientDetails(ClientDetails clientDetails) {
- super.updateClientDetails(clientDetails);
- cacheAndGetClient(clientDetails.getClientId());
- }
-
- @Override
- public void updateClientSecret(String clientId, String secret) {
- super.updateClientSecret(clientId, secret);
- cacheAndGetClient(clientId);
- }
-
- @Override
- public void removeClientDetails(String clientId) {
- super.removeClientDetails(clientId);
- removeRedisCache(clientId);
- }
-
- /**
- * 删除redis缓存
- *
- * @param clientId
- */
- private void removeRedisCache(String clientId) {
- redisTemplate.delete(clientRedisKey(clientId));
- }
-
- /**
- * 将oauth_client_details全表刷入redis
- */
- public void loadAllClientToCache() {
- List list = super.listClientDetails();
- if (CollectionUtils.isEmpty(list)) {
- log.error("oauth_client_details表数据为空,请检查");
- return;
- }
-
- list.forEach(client -> redisTemplate.opsForValue().set(clientRedisKey(client.getClientId()), client));
- }
-
- private String clientRedisKey(String clientId) {
- return SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId;
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisOAuth2AuthorizationConsentService.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisOAuth2AuthorizationConsentService.java
new file mode 100644
index 00000000..f916675d
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisOAuth2AuthorizationConsentService.java
@@ -0,0 +1,55 @@
+package com.central.oauth.service.impl;
+
+import lombok.RequiredArgsConstructor;
+import org.redisson.api.RedissonClient;
+import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsent;
+import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService;
+import org.springframework.stereotype.Component;
+import org.springframework.util.Assert;
+
+import java.time.Duration;
+
+/**
+ * @author: zlt
+ * @date: 2023/11/10
+ *
+ * Blog: http://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+@RequiredArgsConstructor
+@Component
+public class RedisOAuth2AuthorizationConsentService implements OAuth2AuthorizationConsentService {
+
+ private final RedissonClient redissonClient;;
+
+ private final static Long TIMEOUT = 10L;
+
+ @Override
+ public void save(OAuth2AuthorizationConsent authorizationConsent) {
+ Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
+
+ redissonClient.getBucket(buildKey(authorizationConsent))
+ .set(authorizationConsent, Duration.ofMinutes(TIMEOUT));
+ }
+
+ @Override
+ public void remove(OAuth2AuthorizationConsent authorizationConsent) {
+ Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
+ redissonClient.getBucket(buildKey(authorizationConsent)).delete();
+ }
+
+ @Override
+ public OAuth2AuthorizationConsent findById(String registeredClientId, String principalName) {
+ Assert.hasText(registeredClientId, "registeredClientId cannot be empty");
+ Assert.hasText(principalName, "principalName cannot be empty");
+ return (OAuth2AuthorizationConsent) redissonClient.getBucket(buildKey(registeredClientId, principalName)).get();
+ }
+
+ private static String buildKey(String registeredClientId, String principalName) {
+ return "token:consent:" + registeredClientId + ":" + principalName;
+ }
+
+ private static String buildKey(OAuth2AuthorizationConsent authorizationConsent) {
+ return buildKey(authorizationConsent.getRegisteredClientId(), authorizationConsent.getPrincipalName());
+ }
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisSecurityContextRepository.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisSecurityContextRepository.java
new file mode 100644
index 00000000..fce6a559
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisSecurityContextRepository.java
@@ -0,0 +1,138 @@
+package com.central.oauth.service.impl;
+
+import cn.hutool.core.util.StrUtil;
+import com.central.common.constant.SecurityConstants;
+import com.central.oauth.model.SupplierDeferredSecurityContext;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpSession;
+import lombok.RequiredArgsConstructor;
+import org.redisson.api.RBucket;
+import org.redisson.api.RedissonClient;
+import org.redisson.codec.SerializationCodec;
+import org.springframework.security.core.context.DeferredSecurityContext;
+import org.springframework.security.core.context.SecurityContext;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.core.context.SecurityContextHolderStrategy;
+import org.springframework.security.web.context.HttpRequestResponseHolder;
+import org.springframework.security.web.context.SecurityContextRepository;
+import org.springframework.stereotype.Component;
+
+import java.time.Duration;
+import java.util.function.Supplier;
+
+/**
+ * 基于redis存储认证信息,解决多节点uaa单点登录信息互通
+ *
+ * @author: zlt
+ * @date: 2023/12/06
+ *
+ * Blog: http://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+@Component
+@RequiredArgsConstructor
+public class RedisSecurityContextRepository implements SecurityContextRepository {
+ /**
+ * 认证信息存储前缀
+ */
+ public static final String SECURITY_CONTEXT_PREFIX_KEY = "security_context:";
+ /**
+ * 随机字符串请求头名字
+ */
+ public static final String NONCE_HEADER_NAME = "nonceId";
+
+ private final static SerializationCodec AUTH_CODEC = new SerializationCodec();
+
+ private final SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
+ .getContextHolderStrategy();
+ private final RedissonClient redissonClient;
+
+ @Override
+ public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
+ throw new UnsupportedOperationException("Method deprecated.");
+ }
+
+ @Override
+ public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) {
+ String nonce = getNonce(request);
+ if (StrUtil.isEmpty(nonce)) {
+ return;
+ }
+
+ // 如果当前的context是空的,则移除
+ SecurityContext emptyContext = this.securityContextHolderStrategy.createEmptyContext();
+ RBucket rBucket = this.getBucket(nonce);
+ if (emptyContext.equals(context)) {
+ rBucket.delete();
+ } else {
+ // 保存认证信息
+ rBucket.set(context, Duration.ofSeconds(SecurityConstants.ACCESS_TOKEN_VALIDITY_SECONDS));
+ }
+ }
+
+ @Override
+ public boolean containsContext(HttpServletRequest request) {
+ String nonce = getNonce(request);
+ if (StrUtil.isEmpty(nonce)) {
+ return false;
+ }
+ // 检验当前请求是否有认证信息
+ return this.getBucket(nonce).get() != null;
+ }
+
+ @Override
+ public DeferredSecurityContext loadDeferredContext(HttpServletRequest request) {
+ Supplier supplier = () -> readSecurityContextFromRedis(request);
+ return new SupplierDeferredSecurityContext(supplier, this.securityContextHolderStrategy);
+ }
+
+ /**
+ * 从redis中获取认证信息
+ *
+ * @param request 当前请求
+ * @return 认证信息
+ */
+ private SecurityContext readSecurityContextFromRedis(HttpServletRequest request) {
+ if (request == null) {
+ return null;
+ }
+ String nonce = getNonce(request);
+ if (StrUtil.isEmpty(nonce)) {
+ return null;
+ }
+ // 根据缓存id获取认证信息
+ RBucket rBucket = this.getBucket(nonce);
+ SecurityContext context = rBucket.get();
+ if (context != null) {
+ rBucket.expire(Duration.ofSeconds(SecurityConstants.ACCESS_TOKEN_VALIDITY_SECONDS));
+ }
+ return context;
+ }
+
+ /**
+ * 先从请求头中找,找不到去请求参数中找,找不到获取当前session的id
+ * 2023-07-11新增逻辑:获取当前session的sessionId
+ *
+ * @param request 当前请求
+ * @return 随机字符串(sessionId),这个字符串本来是前端生成,现在改为后端获取的sessionId
+ */
+ private String getNonce(HttpServletRequest request) {
+ String nonce = request.getHeader(NONCE_HEADER_NAME);
+ if (StrUtil.isEmpty(nonce)) {
+ nonce = request.getParameter(NONCE_HEADER_NAME);
+ if (StrUtil.isEmpty(nonce)) {
+ HttpSession session = request.getSession(Boolean.FALSE);
+ if (session != null) {
+ nonce = session.getId();
+ }
+ }
+ }
+ return nonce;
+ }
+
+ private RBucket getBucket(String nonce) {
+ return redissonClient.getBucket(SECURITY_CONTEXT_PREFIX_KEY + nonce, AUTH_CODEC);
+ }
+
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisTokensServiceImpl.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisTokensServiceImpl.java
index 45fe56a5..5877d0d2 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisTokensServiceImpl.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisTokensServiceImpl.java
@@ -7,16 +7,23 @@ import com.central.common.model.PageResult;
import com.central.common.redis.template.RedisRepository;
import com.central.oauth.model.TokenVo;
import com.central.oauth.service.ITokensService;
+import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
+import org.redisson.api.RBucket;
+import org.redisson.api.RList;
+import org.redisson.api.RedissonClient;
+import org.redisson.codec.SerializationCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.serializer.RedisSerializer;
-import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
-import org.springframework.security.oauth2.provider.OAuth2Authentication;
-import org.springframework.security.oauth2.provider.OAuth2Request;
+import org.springframework.security.oauth2.core.OAuth2AccessToken;
+import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
+import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.stereotype.Service;
+import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
+import java.util.Date;
import java.util.List;
import java.util.Map;
@@ -31,9 +38,11 @@ import java.util.Map;
*/
@Slf4j
@Service
+@RequiredArgsConstructor
public class RedisTokensServiceImpl implements ITokensService {
- @Autowired
- private RedisRepository redisRepository;
+ private final static SerializationCodec AUTH_CODEC = new SerializationCodec();
+ private static final String AUTHORIZATION = "token";
+ private final RedissonClient redisson;
@Override
public PageResult listTokens(Map params, String clientId) {
@@ -42,33 +51,31 @@ public class RedisTokensServiceImpl implements ITokensService {
int[] startEnds = PageUtil.transToStartEnd(page-1, limit);
//根据请求参数生成redis的key
String redisKey = getRedisKey(params, clientId);
- long size = redisRepository.length(redisKey);
+ RList tokenList = redisson.getList(redisKey);
+ long size = tokenList.size();
List result = new ArrayList<>(limit);
- RedisSerializer valueSerializer = RedisSerializer.java();
//查询token集合
- List tokenObjs = redisRepository.getList(redisKey, startEnds[0], startEnds[1]-1, valueSerializer);
- if (tokenObjs != null) {
- for (Object obj : tokenObjs) {
- DefaultOAuth2AccessToken accessToken = (DefaultOAuth2AccessToken)obj;
+ List tokens = tokenList.range(startEnds[0], startEnds[1]-1);
+ if (tokens != null) {
+ for (String token : tokens) {
//构造token对象
TokenVo tokenVo = new TokenVo();
- tokenVo.setTokenValue(accessToken.getValue());
- tokenVo.setExpiration(accessToken.getExpiration());
-
+ tokenVo.setTokenValue(token);
//获取用户信息
- Object authObj = redisRepository.get(SecurityConstants.REDIS_TOKEN_AUTH + accessToken.getValue(), valueSerializer);
- OAuth2Authentication authentication = (OAuth2Authentication)authObj;
- if (authentication != null) {
- OAuth2Request request = authentication.getOAuth2Request();
- tokenVo.setUsername(authentication.getName());
- tokenVo.setClientId(request.getClientId());
- tokenVo.setGrantType(request.getGrantType());
+ RBucket rBucket = redisson.getBucket(buildKey(OAuth2ParameterNames.ACCESS_TOKEN, token), AUTH_CODEC);
+ OAuth2Authorization authorization = rBucket.get();
+ if (authorization != null) {
+ OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
+ if (accessToken != null && accessToken.getExpiresAt() != null) {
+ tokenVo.setExpiration(Date.from(accessToken.getExpiresAt()));
+ }
+ tokenVo.setUsername(authorization.getPrincipalName());
+ tokenVo.setClientId(authorization.getRegisteredClientId());
+ tokenVo.setGrantType(authorization.getAuthorizationGrantType().getValue());
+
+ String accountType = (String)authorization.getAttributes().get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
+ tokenVo.setAccountType(accountType);
}
-
- Map additionalInformation = accessToken.getAdditionalInformation();
- String accountType = (String)additionalInformation.get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
- tokenVo.setAccountType(accountType);
-
result.add(tokenVo);
}
}
@@ -82,10 +89,14 @@ public class RedisTokensServiceImpl implements ITokensService {
String result;
String username = MapUtils.getString(params, "username");
if (StrUtil.isNotEmpty(username)) {
- result = SecurityConstants.REDIS_UNAME_TO_ACCESS + clientId + ":" + username;
+ result = this.buildKey(SecurityConstants.REDIS_UNAME_TO_ACCESS, clientId + "::" + username);
} else {
- result = SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + clientId;
+ result = this.buildKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS, clientId);
}
return result;
}
+
+ private String buildKey(String type, String id) {
+ return String.format("%s::%s::%s", AUTHORIZATION, type, id);
+ }
}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/RegisteredClientService.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/RegisteredClientService.java
new file mode 100644
index 00000000..857765b2
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/RegisteredClientService.java
@@ -0,0 +1,90 @@
+package com.central.oauth.service.impl;
+
+import cn.hutool.core.bean.BeanUtil;
+import com.central.common.constant.SecurityConstants;
+import com.central.common.model.PageResult;
+import com.central.oauth.model.Client;
+import com.central.oauth.service.IClientService;
+import com.central.oauth2.common.pojo.ClientDto;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.redisson.api.RBucket;
+import org.redisson.api.RedissonClient;
+import org.springframework.stereotype.Service;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @author zlt
+ *
+ * Blog: http://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+@Slf4j
+@RequiredArgsConstructor
+@Service
+public class RegisteredClientService {
+ private final IClientService clientService;
+ private final RedissonClient redisson;
+
+ public void saveClient(Client client) throws Exception {
+ clientService.saveClient(client);
+ ClientDto clientDto = BeanUtil.copyProperties(client, ClientDto.class);
+ redisson.getBucket(clientRedisKey(client.getClientId())).set(clientDto);
+ }
+
+ public PageResult listClient(Map params, boolean isPage) {
+ PageResult clientPage = clientService.listClient(params, isPage);
+ PageResult result = new PageResult<>();
+ result.setCode(clientPage.getCode());
+ result.setCount(clientPage.getCount());
+ result.setData(BeanUtil.copyToList(clientPage.getData(), ClientDto.class));
+ return result;
+ }
+
+ public ClientDto getById(long id) {
+ return BeanUtil.copyProperties(clientService.getById(id), ClientDto.class);
+ }
+
+ public void delClient(long id) {
+ Client client = clientService.getById(id);
+ if (client != null) {
+ clientService.delClient(id);
+ redisson.getBucket(clientRedisKey(client.getClientId())).delete();
+ }
+ }
+
+ public ClientDto loadClientByClientId(String clientId) {
+ RBucket clientBucket = redisson.getBucket(clientRedisKey(clientId));
+ ClientDto clientDto = clientBucket.get();
+ if (clientDto != null) {
+ return clientDto;
+ }
+ Client clientObj = clientService.loadClientByClientId(clientId);
+ clientDto = BeanUtil.copyProperties(clientObj, ClientDto.class);
+ clientBucket.set(clientDto);
+ return clientDto;
+ }
+
+ public void loadAllClientToCache() {
+ List clientList = clientService.list();
+ clientList.forEach(c -> {
+ ClientDto clientDto = BeanUtil.copyProperties(c, ClientDto.class);;
+ redisson.getBucket(clientRedisKey(c.getClientId())).set(clientDto);
+ });
+ }
+
+ public List list() {
+ return BeanUtil.copyToList(clientService.list(), ClientDto.class);
+ }
+
+ public ClientDto getRegisteredClientByClientId(String clientId) {
+ Client clientObj = clientService.loadClientByClientId(clientId);
+ return BeanUtil.copyProperties(clientObj, ClientDto.class);
+ }
+
+ private String clientRedisKey(String clientId) {
+ return SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId;
+ }
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/UnifiedLogoutService.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/UnifiedLogoutService.java
index 8fe2bf36..b8c66921 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/UnifiedLogoutService.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/UnifiedLogoutService.java
@@ -2,26 +2,27 @@ package com.central.oauth.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
+import cn.hutool.json.JSONUtil;
import com.central.oauth.utils.UsernameHolder;
+import com.central.oauth2.common.pojo.ClientDto;
+import com.central.oauth2.common.service.impl.RedisOAuth2AuthorizationService;
import lombok.extern.slf4j.Slf4j;
-import org.springframework.context.annotation.Lazy;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
-import org.springframework.security.oauth2.common.OAuth2AccessToken;
-import org.springframework.security.oauth2.provider.ClientDetails;
-import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
-import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
-import javax.annotation.Resource;
-import java.util.*;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
/**
* 统一登出服务
*
* @author zlt
* @version 1.0
- * @date 2021/10/21
+ * @date 2023/11/18
*
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
@@ -31,23 +32,28 @@ import java.util.*;
public class UnifiedLogoutService {
private final static String LOGOUT_NOTIFY_URL_KEY = "LOGOUT_NOTIFY_URL_LIST";
- @Resource
- private RestTemplate restTemplate;
+ private final RestTemplate restTemplate;
- @Resource
- private TaskExecutor taskExecutor;
+ private final TaskExecutor taskExecutor;
- @Resource
- private RedisClientDetailsService redisClientDetailsService;
+ private final RegisteredClientService clientService;
- @Resource
- private TokenStore tokenStore;
+ private final RedisOAuth2AuthorizationService authorizationService;
- @Lazy
- @Resource
- private DefaultTokenServices tokenServices;
+ public UnifiedLogoutService(RestTemplate restTemplate, TaskExecutor taskExecutor
+ , RegisteredClientService clientService
+ , @Autowired(required = false) RedisOAuth2AuthorizationService authorizationService) {
+ this.restTemplate = restTemplate;
+ this.taskExecutor = taskExecutor;
+ this.clientService = clientService;
+ this.authorizationService = authorizationService;
+ }
public void allLogout() {
+ if (authorizationService == null) {
+ throw new RuntimeException("the 'zlt.oauth2.token.store' parameter must be redis");
+ }
+
Set urls = this.getLogoutNotifyUrl();
for (String url : urls) {
taskExecutor.execute(() -> {
@@ -67,16 +73,16 @@ public class UnifiedLogoutService {
String username = UsernameHolder.getContext();
Set logoutNotifyUrls = new HashSet<>();
try {
- List clientDetails = redisClientDetailsService.listClientDetails();
+ List clientDetails = clientService.list();
Map informationMap;
- for (ClientDetails client : clientDetails) {
- informationMap = client.getAdditionalInformation();
+ for (ClientDto client : clientDetails) {
+ informationMap = this.getInfoMap(client.getAdditionalInformation());
String urls = (String)informationMap.get(LOGOUT_NOTIFY_URL_KEY);
if (StrUtil.isNotEmpty(urls)) {
- Collection tokens = tokenStore.findTokensByClientIdAndUserName(client.getClientId(), username);
+ List tokens = authorizationService.findTokensByClientIdAndUserName(client.getClientId(), username);
if (CollUtil.isNotEmpty(tokens)) {
//注销所有该用户名下的token
- tokens.forEach(t -> tokenServices.revokeToken(t.getValue()));
+ tokens.forEach(authorizationService::remove);
String tokenStr = getTokenValueStr(tokens);
logoutNotifyUrls.addAll(generateNotifyUrls(urls.split(","), tokenStr));
}
@@ -88,7 +94,7 @@ public class UnifiedLogoutService {
return logoutNotifyUrls;
}
- private String getTokenValueStr(Collection tokens) {
+ private String getTokenValueStr(List tokens) {
if (CollUtil.isNotEmpty(tokens)) {
return StrUtil.join( ",", tokens);
}
@@ -109,4 +115,11 @@ public class UnifiedLogoutService {
}
return urlSet;
}
+
+ private Map getInfoMap(String additionalInformation) {
+ if (StrUtil.isNotEmpty(additionalInformation)) {
+ return JSONUtil.toBean(additionalInformation, Map.class);
+ }
+ return Map.of();
+ }
}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceFactory.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceFactory.java
index c8d61c3f..bc1bb2b5 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceFactory.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceFactory.java
@@ -4,13 +4,13 @@ import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.central.common.constant.SecurityConstants;
import com.central.oauth.service.ZltUserDetailsService;
+import com.central.oauth.exception.CustomOAuth2AuthenticationException;
import com.central.oauth2.common.util.AuthUtils;
+import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
-import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
-import javax.annotation.Resource;
import java.util.List;
/**
@@ -20,13 +20,13 @@ import java.util.List;
* @version 1.0
* @date 2021/7/24
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@Service
public class UserDetailServiceFactory {
- private static final String ERROR_MSG = "找不到账号类型为 {} 的实现类";
+ private static final String ERROR_MSG = "Cannot find the implementation class for the account type {}";
@Resource
private List userDetailsServices;
@@ -48,6 +48,6 @@ public class UserDetailServiceFactory {
}
}
}
- throw new InternalAuthenticationServiceException(StrUtil.format(ERROR_MSG, accountType));
+ throw new CustomOAuth2AuthenticationException(StrUtil.format(ERROR_MSG, accountType));
}
}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceImpl.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceImpl.java
index b240fd4f..51159368 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceImpl.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceImpl.java
@@ -2,23 +2,21 @@ package com.central.oauth.service.impl;
import com.central.common.constant.SecurityConstants;
import com.central.common.feign.UserService;
+import com.central.common.model.SysUser;
+import com.central.common.utils.LoginUserUtils;
import com.central.oauth.service.ZltUserDetailsService;
+import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.social.security.SocialUserDetails;
import org.springframework.stereotype.Service;
-import com.central.common.model.LoginAppUser;
-
-import lombok.extern.slf4j.Slf4j;
-
import javax.annotation.Resource;
/**
* @author zlt
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@@ -36,29 +34,31 @@ public class UserDetailServiceImpl implements ZltUserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) {
- LoginAppUser loginAppUser = userService.findByUsername(username);
- if (loginAppUser == null) {
+ SysUser sysUser = userService.findByUsername(username);
+ if (sysUser == null) {
throw new InternalAuthenticationServiceException("用户名或密码错误");
}
- return checkUser(loginAppUser);
+ checkUser(sysUser);
+ return LoginUserUtils.getLoginAppUser(sysUser);
}
@Override
- public SocialUserDetails loadUserByUserId(String openId) {
- LoginAppUser loginAppUser = userService.findByOpenId(openId);
- return checkUser(loginAppUser);
+ public UserDetails loadUserByUserId(String openId) {
+ SysUser sysUser = userService.findByOpenId(openId);
+ checkUser(sysUser);
+ return LoginUserUtils.getLoginAppUser(sysUser);
}
@Override
public UserDetails loadUserByMobile(String mobile) {
- LoginAppUser loginAppUser = userService.findByMobile(mobile);
- return checkUser(loginAppUser);
+ SysUser sysUser = userService.findByMobile(mobile);
+ checkUser(sysUser);
+ return LoginUserUtils.getLoginAppUser(sysUser);
}
- private LoginAppUser checkUser(LoginAppUser loginAppUser) {
- if (loginAppUser != null && !loginAppUser.isEnabled()) {
+ private void checkUser(SysUser sysUser) {
+ if (sysUser != null && !sysUser.getEnabled()) {
throw new DisabledException("用户已作废");
}
- return loginAppUser;
}
}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailsByNameServiceFactoryWrapper.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailsByNameServiceFactoryWrapper.java
deleted file mode 100644
index 39f02f2b..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailsByNameServiceFactoryWrapper.java
+++ /dev/null
@@ -1,59 +0,0 @@
-package com.central.oauth.service.impl;
-
-import com.central.oauth.service.ZltUserDetailsService;
-import lombok.Setter;
-import org.springframework.beans.factory.InitializingBean;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.userdetails.*;
-import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
-import org.springframework.util.Assert;
-
-/**
- * 重写 UserDetailsByNameServiceWrapper 支持多帐户类型
- *
- * @author zlt
- * @version 1.0
- * @date 2021/7/24
- * @see UserDetailsByNameServiceWrapper
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-public class UserDetailsByNameServiceFactoryWrapper implements
- AuthenticationUserDetailsService, InitializingBean {
- @Setter
- private UserDetailServiceFactory userDetailServiceFactory;
-
- public UserDetailsByNameServiceFactoryWrapper() {
-
- }
-
- public UserDetailsByNameServiceFactoryWrapper(final UserDetailServiceFactory userDetailServiceFactory) {
- Assert.notNull(userDetailServiceFactory, "userDetailServiceFactory cannot be null.");
- this.userDetailServiceFactory = userDetailServiceFactory;
- }
-
- /**
- * Check whether all required properties have been set.
- *
- * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
- */
- @Override
- public void afterPropertiesSet() {
- Assert.notNull(this.userDetailServiceFactory, "UserDetailServiceFactory must be set");
- }
-
- /**
- * Get the UserDetails object from the wrapped UserDetailsService implementation
- */
- @Override
- public UserDetails loadUserDetails(T authentication) throws UsernameNotFoundException {
- ZltUserDetailsService userDetailsService;
- if (authentication instanceof PreAuthenticatedAuthenticationToken) {
- userDetailsService = this.userDetailServiceFactory.getService((Authentication)authentication.getPrincipal());
- } else {
- userDetailsService = this.userDetailServiceFactory.getService(authentication);
- }
- return userDetailsService.loadUserByUsername(authentication.getName());
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/ValidateCodeServiceImpl.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/ValidateCodeServiceImpl.java
index e217587c..7504b902 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/ValidateCodeServiceImpl.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/ValidateCodeServiceImpl.java
@@ -2,34 +2,34 @@ package com.central.oauth.service.impl;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
-import com.central.common.feign.UserService;
-import com.central.common.redis.template.RedisRepository;
import com.central.common.constant.SecurityConstants;
+import com.central.common.feign.UserService;
import com.central.common.model.Result;
import com.central.common.model.SysUser;
-import com.central.oauth.exception.ValidateCodeException;
import com.central.oauth.service.IValidateCodeService;
+import com.central.oauth.exception.CustomOAuth2AuthenticationException;
+import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
+import org.redisson.api.RBucket;
+import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
-import javax.annotation.Resource;
+import java.time.Duration;
/**
* @author zlt
* @date 2018/12/10
*
- * Blog: https://zlt2000.gitee.io
+ * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
+@RequiredArgsConstructor
@Service
public class ValidateCodeServiceImpl implements IValidateCodeService {
- @Autowired
- private RedisRepository redisRepository;
+ private final RedissonClient redisson;
- @Resource
- private UserService userService;
+ private final UserService userService;
/**
* 保存用户验证码,和randomStr绑定
@@ -39,7 +39,8 @@ public class ValidateCodeServiceImpl implements IValidateCodeService {
*/
@Override
public void saveImageCode(String deviceId, String imageCode) {
- redisRepository.setExpire(buildKey(deviceId), imageCode, SecurityConstants.DEFAULT_IMAGE_EXPIRE);
+ this.getBucket(deviceId)
+ .set(imageCode, Duration.ofSeconds(SecurityConstants.DEFAULT_IMAGE_EXPIRE));
}
/**
@@ -54,8 +55,9 @@ public class ValidateCodeServiceImpl implements IValidateCodeService {
* @return true、false
*/
@Override
- public Result sendSmsCode(String mobile) {
- Object tempCode = redisRepository.get(buildKey(mobile));
+ public Result sendSmsCode(String mobile) {
+ RBucket rBucket = this.getBucket(mobile);
+ Object tempCode = rBucket.get();
if (tempCode != null) {
log.error("用户:{}验证码未失效{}", mobile, tempCode);
return Result.failed("验证码未失效,请失效后再次申请");
@@ -69,7 +71,7 @@ public class ValidateCodeServiceImpl implements IValidateCodeService {
String code = RandomUtil.randomNumbers(4);
log.info("短信发送请求消息中心 -> 手机号:{} -> 验证码:{}", mobile, code);
- redisRepository.setExpire(buildKey(mobile), code, SecurityConstants.DEFAULT_IMAGE_EXPIRE);
+ rBucket.set(code, Duration.ofSeconds(SecurityConstants.DEFAULT_IMAGE_EXPIRE));
return Result.succeed("true");
}
@@ -79,7 +81,7 @@ public class ValidateCodeServiceImpl implements IValidateCodeService {
*/
@Override
public String getCode(String deviceId) {
- return (String)redisRepository.get(buildKey(deviceId));
+ return this.getBucket(deviceId).get();
}
/**
@@ -88,7 +90,7 @@ public class ValidateCodeServiceImpl implements IValidateCodeService {
*/
@Override
public void remove(String deviceId) {
- redisRepository.del(buildKey(deviceId));
+ this.getBucket(deviceId).delete();
}
/**
@@ -97,19 +99,19 @@ public class ValidateCodeServiceImpl implements IValidateCodeService {
@Override
public void validate(String deviceId, String validCode) {
if (StrUtil.isBlank(deviceId)) {
- throw new ValidateCodeException("请在请求参数中携带deviceId参数");
+ throw new CustomOAuth2AuthenticationException("请在请求参数中携带deviceId参数");
}
String code = this.getCode(deviceId);
if (StrUtil.isBlank(validCode)) {
- throw new ValidateCodeException("请填写验证码");
+ throw new CustomOAuth2AuthenticationException("请填写验证码");
}
if (code == null) {
- throw new ValidateCodeException("验证码不存在或已过期");
+ throw new CustomOAuth2AuthenticationException("验证码不存在或已过期");
}
if (!StrUtil.equals(code, validCode.toLowerCase())) {
- throw new ValidateCodeException("验证码不正确");
+ throw new CustomOAuth2AuthenticationException("验证码不正确");
}
this.remove(deviceId);
@@ -118,4 +120,8 @@ public class ValidateCodeServiceImpl implements IValidateCodeService {
private String buildKey(String deviceId) {
return SecurityConstants.DEFAULT_CODE_KEY + ":" + deviceId;
}
+
+ private RBucket getBucket(String deviceId) {
+ return redisson.getBucket(buildKey(deviceId));
+ }
}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/support/base/BaseAuthenticationConverter.java b/zlt-uaa/src/main/java/com/central/oauth/support/base/BaseAuthenticationConverter.java
new file mode 100644
index 00000000..2b6d20eb
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/support/base/BaseAuthenticationConverter.java
@@ -0,0 +1,88 @@
+package com.central.oauth.support.base;
+
+import cn.hutool.core.util.ArrayUtil;
+import cn.hutool.core.util.StrUtil;
+import com.central.oauth.utils.OAuthEndpointUtils;
+import com.central.oauth2.common.token.BaseAuthenticationToken;
+import jakarta.servlet.http.HttpServletRequest;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
+import org.springframework.security.web.authentication.AuthenticationConverter;
+import org.springframework.util.MultiValueMap;
+import org.springframework.util.StringUtils;
+
+import java.util.*;
+
+/**
+ * @author: zlt
+ * @date: 2023/11/18
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+public abstract class BaseAuthenticationConverter implements AuthenticationConverter {
+ @Override
+ public Authentication convert(HttpServletRequest request) {
+ String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE);
+ if (!this.supportGrantType().equals(grantType)) {
+ return null;
+ }
+
+ MultiValueMap parameters = OAuthEndpointUtils.getParameters(request);
+ return this.getAuthentication(parameters);
+ }
+
+ public Authentication getAuthentication(MultiValueMap parameters) {
+ Set requestScopes = this.getRequestScopes(parameters);
+
+ Map additionalParameters = getAdditionalParameters(parameters, this.paramNames());
+
+ Authentication clientPrincipal = SecurityContextHolder.getContext().getAuthentication();
+
+ BaseAuthenticationToken baseToken = this.getToken(parameters);
+ baseToken.setScopes(requestScopes);
+ baseToken.setAdditionalParameters(additionalParameters);
+ baseToken.setClientPrincipal(clientPrincipal);
+ return baseToken;
+ };
+
+ public Set getRequestScopes(MultiValueMap parameters) {
+ String scope = parameters.getFirst(OAuth2ParameterNames.SCOPE);
+ Set requestedScopes = null;
+ if (StrUtil.isNotEmpty(scope)) {
+ requestedScopes = new HashSet<>(
+ Arrays.asList(StringUtils.delimitedListToStringArray(scope, " ")));
+ } else {
+ requestedScopes = Collections.emptySet();
+ }
+ return requestedScopes;
+ }
+
+ public Map getAdditionalParameters(MultiValueMap parameters, List paramName) {
+ Map additionalParameters = new HashMap<>();
+ parameters.forEach((key, value) -> {
+ if (!key.equals(OAuth2ParameterNames.GRANT_TYPE) &&
+ !key.equals(OAuth2ParameterNames.SCOPE)) {
+ boolean isAdd = true;
+ if (ArrayUtil.isNotEmpty(paramName)) {
+ for (String name : paramName) {
+ if (key.equals(name)) {
+ isAdd = false;
+ }
+ }
+ }
+ if (isAdd) {
+ additionalParameters.put(key, value.get(0));
+ }
+ }
+ });
+ return additionalParameters;
+ }
+
+ protected abstract String supportGrantType();
+
+ protected abstract List paramNames();
+
+ protected abstract BaseAuthenticationToken getToken(MultiValueMap parameters);
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/support/base/BaseAuthenticationProvider.java b/zlt-uaa/src/main/java/com/central/oauth/support/base/BaseAuthenticationProvider.java
new file mode 100644
index 00000000..07398bb8
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/support/base/BaseAuthenticationProvider.java
@@ -0,0 +1,204 @@
+package com.central.oauth.support.base;
+
+import cn.hutool.core.util.StrUtil;
+import com.central.common.constant.SecurityConstants;
+import com.central.common.context.TenantContextHolder;
+import com.central.oauth2.common.token.BaseAuthenticationToken;
+import lombok.Getter;
+import lombok.Setter;
+import org.springframework.security.authentication.AuthenticationProvider;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.oauth2.core.*;
+import org.springframework.security.oauth2.core.oidc.OidcIdToken;
+import org.springframework.security.oauth2.core.oidc.OidcScopes;
+import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
+import org.springframework.security.oauth2.jwt.Jwt;
+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.authorization.authentication.OAuth2AccessTokenAuthenticationToken;
+import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken;
+import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
+import org.springframework.security.oauth2.server.authorization.context.AuthorizationServerContextHolder;
+import org.springframework.security.oauth2.server.authorization.token.DefaultOAuth2TokenContext;
+import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenContext;
+import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
+import org.springframework.util.Assert;
+import org.springframework.util.CollectionUtils;
+
+import java.security.Principal;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * 基础provider
+ *
+ * @author zlt
+ * @version 1.0
+ * @date 2023/11/18
+ *
+ * Blog: http://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+@Setter
+@Getter
+public abstract class BaseAuthenticationProvider implements AuthenticationProvider {
+ private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-4.3";
+ private static final OAuth2TokenType ID_TOKEN_TOKEN_TYPE = new OAuth2TokenType(OidcParameterNames.ID_TOKEN);
+ private final OAuth2AuthorizationService authorizationService;
+ private final OAuth2TokenGenerator extends OAuth2Token> tokenGenerator;
+
+ public BaseAuthenticationProvider(OAuth2AuthorizationService authorizationService
+ , OAuth2TokenGenerator extends OAuth2Token> tokenGenerator) {
+ Assert.notNull(authorizationService, "authorizationService cannot be null");
+ Assert.notNull(tokenGenerator, "tokenGenerator cannot be null");
+ this.authorizationService = authorizationService;
+ this.tokenGenerator = tokenGenerator;
+ }
+
+ @Override
+ public Authentication authenticate(Authentication authentication) {
+ BaseAuthenticationToken authToken = (BaseAuthenticationToken) authentication;
+
+ OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(authToken);
+ RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
+
+ Set authorizedScopes = authToken.getScopes();
+ if (!CollectionUtils.isEmpty(authToken.getScopes())) {
+ for (String requestedScope : authToken.getScopes()) {
+ if (!registeredClient.getScopes().contains(requestedScope)) {
+ throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_SCOPE);
+ }
+ }
+ }
+
+ // 执行登录验证逻辑
+ TenantContextHolder.setTenant(registeredClient.getClientId());
+ Authentication principal = this.getPrincipal(authentication);
+ TenantContextHolder.clear();
+
+ String accountType = (String)authToken.getAdditionalParameters().get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
+ if (StrUtil.isEmpty(accountType)) {
+ accountType = SecurityConstants.DEF_ACCOUNT_TYPE;
+ authToken.getAdditionalParameters().put(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, accountType);
+ }
+
+ // @formatter:off
+ DefaultOAuth2TokenContext.Builder tokenContextBuilder = DefaultOAuth2TokenContext.builder()
+ .registeredClient(registeredClient)
+ .principal(principal)
+ .authorizationServerContext(AuthorizationServerContextHolder.getContext())
+ .authorizedScopes(authorizedScopes)
+ .authorizationGrantType(this.grantType())
+ .authorizationGrant(authToken);
+ // @formatter:on
+
+ OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization
+ .withRegisteredClient(registeredClient)
+ .principalName(principal.getName())
+ .attribute(Principal.class.getName(), principal)
+ .attribute(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, accountType)
+ .authorizationGrantType(this.grantType())
+ .authorizedScopes(authorizedScopes);
+
+ // ----- Access token -----
+ OAuth2TokenContext tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.ACCESS_TOKEN).build();
+ OAuth2Token generatedAccessToken = this.tokenGenerator.generate(tokenContext);
+ if (generatedAccessToken == null) {
+ OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR,
+ "The token generator failed to generate the access token.", ERROR_URI);
+ throw new OAuth2AuthenticationException(error);
+ }
+ OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
+ generatedAccessToken.getTokenValue(), generatedAccessToken.getIssuedAt(),
+ generatedAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes());
+ authorizationBuilder.id(accessToken.getTokenValue());
+ if (generatedAccessToken instanceof ClaimAccessor) {
+ authorizationBuilder.token(accessToken, (metadata) ->
+ metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, ((ClaimAccessor) generatedAccessToken).getClaims()));
+ } else {
+ authorizationBuilder.accessToken(accessToken);
+ }
+
+ // ----- Refresh token -----
+ OAuth2RefreshToken refreshToken = null;
+ if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN) &&
+ // Do not issue refresh token to public client
+ !clientPrincipal.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.NONE)) {
+
+ tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.REFRESH_TOKEN).build();
+ OAuth2Token generatedRefreshToken = this.tokenGenerator.generate(tokenContext);
+ if (!(generatedRefreshToken instanceof OAuth2RefreshToken)) {
+ OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR,
+ "The token generator failed to generate the refresh token.", ERROR_URI);
+ throw new OAuth2AuthenticationException(error);
+ }
+ refreshToken = (OAuth2RefreshToken) generatedRefreshToken;
+ authorizationBuilder.refreshToken(refreshToken);
+ }
+
+ // ----- ID token -----
+ OidcIdToken idToken;
+ if (authorizedScopes.contains(OidcScopes.OPENID)) {
+ // @formatter:off
+ tokenContext = tokenContextBuilder
+ .tokenType(ID_TOKEN_TOKEN_TYPE)
+ .authorization(authorizationBuilder.build()) // ID token customizer may need access to the access token and/or refresh token
+ .build();
+ // @formatter:on
+ OAuth2Token generatedIdToken = this.tokenGenerator.generate(tokenContext);
+ if (!(generatedIdToken instanceof Jwt)) {
+ OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR,
+ "The token generator failed to generate the ID token.", ERROR_URI);
+ throw new OAuth2AuthenticationException(error);
+ }
+
+ idToken = new OidcIdToken(generatedIdToken.getTokenValue(), generatedIdToken.getIssuedAt(),
+ generatedIdToken.getExpiresAt(), ((Jwt) generatedIdToken).getClaims());
+ authorizationBuilder.token(idToken, (metadata) ->
+ metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims()));
+ } else {
+ idToken = null;
+ }
+
+ OAuth2Authorization authorization = authorizationBuilder.build();
+ this.authorizationService.save(authorization);
+
+ Map additionalParameters = Collections.emptyMap();
+ if (idToken != null) {
+ additionalParameters = new HashMap<>();
+ additionalParameters.put(OidcParameterNames.ID_TOKEN, idToken.getTokenValue());
+ }
+
+ return new OAuth2AccessTokenAuthenticationToken(
+ registeredClient, clientPrincipal, accessToken, refreshToken, additionalParameters);
+ }
+
+ private OAuth2ClientAuthenticationToken getAuthenticatedClientElseThrowInvalidClient(
+ BaseAuthenticationToken authentication) {
+
+ OAuth2ClientAuthenticationToken clientPrincipal = null;
+
+ if (OAuth2ClientAuthenticationToken.class.isAssignableFrom(authentication.getClientPrincipal().getClass())) {
+ clientPrincipal = (OAuth2ClientAuthenticationToken) authentication.getClientPrincipal();
+ }
+
+ if (clientPrincipal != null && clientPrincipal.isAuthenticated()) {
+ return clientPrincipal;
+ }
+
+ throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT);
+ }
+
+ /**
+ * 执行登录验证逻辑
+ */
+ protected abstract Authentication getPrincipal(Authentication authentication);
+
+ /**
+ * 获取 GrantType
+ */
+ protected abstract AuthorizationGrantType grantType();
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/support/mobile/MobileAuthenticationConverter.java b/zlt-uaa/src/main/java/com/central/oauth/support/mobile/MobileAuthenticationConverter.java
new file mode 100644
index 00000000..7e5d33d7
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/support/mobile/MobileAuthenticationConverter.java
@@ -0,0 +1,38 @@
+package com.central.oauth.support.mobile;
+
+import com.central.oauth.support.base.BaseAuthenticationConverter;
+import com.central.oauth.utils.OAuthEndpointUtils;
+import com.central.oauth2.common.token.BaseAuthenticationToken;
+import com.central.oauth2.common.token.MobileAuthenticationToken;
+import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
+import org.springframework.util.MultiValueMap;
+
+import java.util.List;
+
+/**
+ * @author: zlt
+ * @date: 2023/11/18
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+public class MobileAuthenticationConverter extends BaseAuthenticationConverter {
+ private final static String PARAM_MOBILE= "mobile";
+
+ @Override
+ protected String supportGrantType() {
+ return MobileAuthenticationToken.GRANT_TYPE.getValue();
+ }
+
+ @Override
+ protected List paramNames() {
+ return List.of(PARAM_MOBILE, OAuth2ParameterNames.PASSWORD);
+ }
+
+ @Override
+ protected BaseAuthenticationToken getToken(MultiValueMap parameters) {
+ String mobile = OAuthEndpointUtils.getParam(parameters, PARAM_MOBILE);
+ String password = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.PASSWORD);
+ return new MobileAuthenticationToken(mobile, password);
+ }
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/support/mobile/MobileAuthenticationProvider.java b/zlt-uaa/src/main/java/com/central/oauth/support/mobile/MobileAuthenticationProvider.java
new file mode 100644
index 00000000..8323e34a
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/support/mobile/MobileAuthenticationProvider.java
@@ -0,0 +1,67 @@
+package com.central.oauth.support.mobile;
+
+import com.central.oauth.service.impl.UserDetailServiceFactory;
+import com.central.oauth.support.base.BaseAuthenticationProvider;
+import com.central.oauth.exception.CustomOAuth2AuthenticationException;
+import com.central.oauth2.common.token.MobileAuthenticationToken;
+import lombok.Getter;
+import lombok.Setter;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.security.oauth2.core.AuthorizationGrantType;
+import org.springframework.security.oauth2.core.OAuth2Token;
+import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
+import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
+import org.springframework.util.Assert;
+
+/**
+ * @author zlt
+ *
+ * Blog: http://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+@Setter
+@Getter
+public class MobileAuthenticationProvider extends BaseAuthenticationProvider {
+ private UserDetailServiceFactory userDetailsServiceFactory;
+ private PasswordEncoder passwordEncoder;
+
+ public MobileAuthenticationProvider(OAuth2AuthorizationService authorizationService
+ , OAuth2TokenGenerator extends OAuth2Token> tokenGenerator
+ , UserDetailServiceFactory userDetailsServiceFactory, PasswordEncoder passwordEncoder) {
+ super(authorizationService, tokenGenerator);
+ Assert.notNull(userDetailsServiceFactory, "userDetailsServiceFactory cannot be null");
+ Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
+ this.userDetailsServiceFactory = userDetailsServiceFactory;
+ this.passwordEncoder = passwordEncoder;
+ }
+
+ @Override
+ public boolean supports(Class> authentication) {
+ return MobileAuthenticationToken.class.isAssignableFrom(authentication);
+ }
+
+ @Override
+ protected Authentication getPrincipal(Authentication authentication) {
+ MobileAuthenticationToken authToken = (MobileAuthenticationToken) authentication;
+ String mobile = (String) authToken.getPrincipal();
+ String password = authToken.getCredentials();
+ UserDetails userDetails;
+ try {
+ userDetails = userDetailsServiceFactory.getService(authToken).loadUserByMobile(mobile);
+ } catch (AuthenticationException e) {
+ throw new CustomOAuth2AuthenticationException(e.getMessage());
+ }
+ if (userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())) {
+ throw new CustomOAuth2AuthenticationException("手机号或密码错误");
+ }
+ return new MobileAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
+ }
+
+ @Override
+ protected AuthorizationGrantType grantType() {
+ return MobileAuthenticationToken.GRANT_TYPE;
+ }
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/support/openid/OpenIdAuthenticationConverter.java b/zlt-uaa/src/main/java/com/central/oauth/support/openid/OpenIdAuthenticationConverter.java
new file mode 100644
index 00000000..82127a80
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/support/openid/OpenIdAuthenticationConverter.java
@@ -0,0 +1,36 @@
+package com.central.oauth.support.openid;
+
+import com.central.oauth.support.base.BaseAuthenticationConverter;
+import com.central.oauth.utils.OAuthEndpointUtils;
+import com.central.oauth2.common.token.BaseAuthenticationToken;
+import com.central.oauth2.common.token.OpenIdAuthenticationToken;
+import org.springframework.util.MultiValueMap;
+
+import java.util.List;
+
+/**
+ * @author: zlt
+ * @date: 2023/11/18
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+public class OpenIdAuthenticationConverter extends BaseAuthenticationConverter {
+ private final static String PARAM_OPENID = "openId";
+
+ @Override
+ protected String supportGrantType() {
+ return OpenIdAuthenticationToken.GRANT_TYPE.getValue();
+ }
+
+ @Override
+ protected List paramNames() {
+ return List.of(PARAM_OPENID);
+ }
+
+ @Override
+ protected BaseAuthenticationToken getToken(MultiValueMap parameters) {
+ String openId = OAuthEndpointUtils.getParam(parameters, PARAM_OPENID);
+ return new OpenIdAuthenticationToken(openId);
+ }
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/support/openid/OpenIdAuthenticationProvider.java b/zlt-uaa/src/main/java/com/central/oauth/support/openid/OpenIdAuthenticationProvider.java
new file mode 100644
index 00000000..151d9b0d
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/support/openid/OpenIdAuthenticationProvider.java
@@ -0,0 +1,63 @@
+package com.central.oauth.support.openid;
+
+import com.central.oauth.service.impl.UserDetailServiceFactory;
+import com.central.oauth.support.base.BaseAuthenticationProvider;
+import com.central.oauth.exception.CustomOAuth2AuthenticationException;
+import com.central.oauth2.common.token.OpenIdAuthenticationToken;
+import lombok.Getter;
+import lombok.Setter;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.oauth2.core.AuthorizationGrantType;
+import org.springframework.security.oauth2.core.OAuth2Token;
+import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
+import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
+import org.springframework.util.Assert;
+
+/**
+ * @author: zlt
+ * @date: 2023/11/18
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+@Setter
+@Getter
+public class OpenIdAuthenticationProvider extends BaseAuthenticationProvider {
+ private UserDetailServiceFactory userDetailsServiceFactory;
+
+ public OpenIdAuthenticationProvider(OAuth2AuthorizationService authorizationService
+ , OAuth2TokenGenerator extends OAuth2Token> tokenGenerator
+ , UserDetailServiceFactory userDetailsServiceFactory) {
+ super(authorizationService, tokenGenerator);
+ Assert.notNull(userDetailsServiceFactory, "userDetailsServiceFactory cannot be null");
+ this.userDetailsServiceFactory = userDetailsServiceFactory;
+ }
+
+ @Override
+ public boolean supports(Class> authentication) {
+ return OpenIdAuthenticationToken.class.isAssignableFrom(authentication);
+ }
+
+ @Override
+ protected Authentication getPrincipal(Authentication authentication) {
+ OpenIdAuthenticationToken authToken = (OpenIdAuthenticationToken) authentication;
+ String openId = (String) authToken.getPrincipal();
+ UserDetails userDetails;
+ try {
+ userDetails = userDetailsServiceFactory.getService(authToken).loadUserByUserId(openId);
+ } catch (AuthenticationException e) {
+ throw new CustomOAuth2AuthenticationException(e.getMessage());
+ }
+ if (userDetails == null) {
+ throw new CustomOAuth2AuthenticationException("openId错误");
+ }
+ return new OpenIdAuthenticationToken(userDetails, userDetails.getAuthorities());
+ }
+
+ @Override
+ protected AuthorizationGrantType grantType() {
+ return OpenIdAuthenticationToken.GRANT_TYPE;
+ }
+}
\ No newline at end of file
diff --git a/zlt-uaa/src/main/java/com/central/oauth/support/password/PasswordAuthenticationConverter.java b/zlt-uaa/src/main/java/com/central/oauth/support/password/PasswordAuthenticationConverter.java
new file mode 100644
index 00000000..80630a7d
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/support/password/PasswordAuthenticationConverter.java
@@ -0,0 +1,36 @@
+package com.central.oauth.support.password;
+
+import com.central.oauth.support.base.BaseAuthenticationConverter;
+import com.central.oauth.utils.OAuthEndpointUtils;
+import com.central.oauth2.common.token.BaseAuthenticationToken;
+import com.central.oauth2.common.token.PasswordAuthenticationToken;
+import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
+import org.springframework.util.MultiValueMap;
+
+import java.util.List;
+
+/**
+ * @author: zlt
+ * @date: 2023/11/18
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+public class PasswordAuthenticationConverter extends BaseAuthenticationConverter {
+ @Override
+ protected String supportGrantType() {
+ return PasswordAuthenticationToken.GRANT_TYPE.getValue();
+ }
+
+ @Override
+ protected List paramNames() {
+ return List.of(OAuth2ParameterNames.USERNAME, OAuth2ParameterNames.PASSWORD);
+ }
+
+ @Override
+ protected BaseAuthenticationToken getToken(MultiValueMap parameters) {
+ String username = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.USERNAME);
+ String password = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.PASSWORD);
+ return new PasswordAuthenticationToken(username, password);
+ }
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/support/password/PasswordAuthenticationProvider.java b/zlt-uaa/src/main/java/com/central/oauth/support/password/PasswordAuthenticationProvider.java
new file mode 100644
index 00000000..fbb82cae
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/support/password/PasswordAuthenticationProvider.java
@@ -0,0 +1,71 @@
+package com.central.oauth.support.password;
+
+import com.central.oauth.service.impl.UserDetailServiceFactory;
+import com.central.oauth.support.base.BaseAuthenticationProvider;
+import com.central.oauth.exception.CustomOAuth2AuthenticationException;
+import com.central.oauth2.common.token.PasswordAuthenticationToken;
+import lombok.Getter;
+import lombok.Setter;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.security.oauth2.core.AuthorizationGrantType;
+import org.springframework.security.oauth2.core.OAuth2Token;
+import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
+import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
+import org.springframework.util.Assert;
+
+/**
+ * 用户名密码 provider
+ *
+ * @author zlt
+ * @version 1.0
+ * @date 2023/11/18
+ *
+ * Blog: http://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+@Setter
+@Getter
+public class PasswordAuthenticationProvider extends BaseAuthenticationProvider {
+ private final UserDetailServiceFactory userDetailsServiceFactory;
+ private final PasswordEncoder passwordEncoder;
+
+ public PasswordAuthenticationProvider(OAuth2AuthorizationService authorizationService
+ , OAuth2TokenGenerator extends OAuth2Token> tokenGenerator
+ , UserDetailServiceFactory userDetailsServiceFactory, PasswordEncoder passwordEncoder) {
+ super(authorizationService, tokenGenerator);
+ Assert.notNull(userDetailsServiceFactory, "userDetailsServiceFactory cannot be null");
+ Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
+ this.userDetailsServiceFactory = userDetailsServiceFactory;
+ this.passwordEncoder = passwordEncoder;
+ }
+
+ @Override
+ public boolean supports(Class> authentication) {
+ return PasswordAuthenticationToken.class.isAssignableFrom(authentication);
+ }
+
+ @Override
+ protected Authentication getPrincipal(Authentication authentication) {
+ PasswordAuthenticationToken authToken = (PasswordAuthenticationToken) authentication;
+ String username = (String) authToken.getPrincipal();
+ String password = authToken.getCredentials();
+ UserDetails userDetails;
+ try {
+ userDetails = userDetailsServiceFactory.getService(authToken).loadUserByUsername(username);
+ } catch (AuthenticationException e) {
+ throw new CustomOAuth2AuthenticationException(e.getMessage());
+ }
+ if (userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())) {
+ throw new CustomOAuth2AuthenticationException("用户名或密码错误");
+ }
+ return new PasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
+ }
+
+ @Override
+ protected AuthorizationGrantType grantType() {
+ return PasswordAuthenticationToken.GRANT_TYPE;
+ }
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/support/passwordCode/PasswordCodeAuthenticationConverter.java b/zlt-uaa/src/main/java/com/central/oauth/support/passwordCode/PasswordCodeAuthenticationConverter.java
new file mode 100644
index 00000000..4aeca5d6
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/support/passwordCode/PasswordCodeAuthenticationConverter.java
@@ -0,0 +1,41 @@
+package com.central.oauth.support.passwordCode;
+
+import com.central.oauth.support.base.BaseAuthenticationConverter;
+import com.central.oauth.utils.OAuthEndpointUtils;
+import com.central.oauth2.common.token.BaseAuthenticationToken;
+import com.central.oauth2.common.token.PasswordCodeAuthenticationToken;
+import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
+import org.springframework.util.MultiValueMap;
+
+import java.util.List;
+
+/**
+ * @author: zlt
+ * @date: 2023/11/18
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+public class PasswordCodeAuthenticationConverter extends BaseAuthenticationConverter {
+ private final static String PARAM_DEVICEID = "deviceId";
+ private final static String PARAM_VALIDCODE = "validCode";
+ @Override
+ protected String supportGrantType() {
+ return PasswordCodeAuthenticationToken.GRANT_TYPE.getValue();
+ }
+
+ @Override
+ protected List paramNames() {
+ return List.of(OAuth2ParameterNames.USERNAME, OAuth2ParameterNames.PASSWORD
+ , PARAM_DEVICEID, PARAM_VALIDCODE);
+ }
+
+ @Override
+ protected BaseAuthenticationToken getToken(MultiValueMap parameters) {
+ String username = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.USERNAME);
+ String password = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.PASSWORD);
+ String deviceId = OAuthEndpointUtils.getParam(parameters, PARAM_DEVICEID);
+ String validCode = OAuthEndpointUtils.getParam(parameters, PARAM_VALIDCODE);
+ return new PasswordCodeAuthenticationToken(username, password, deviceId, validCode);
+ }
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/support/passwordCode/PasswordCodeAuthenticationProvider.java b/zlt-uaa/src/main/java/com/central/oauth/support/passwordCode/PasswordCodeAuthenticationProvider.java
new file mode 100644
index 00000000..f6ef5ba8
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/support/passwordCode/PasswordCodeAuthenticationProvider.java
@@ -0,0 +1,81 @@
+package com.central.oauth.support.passwordCode;
+
+import com.central.oauth.service.IValidateCodeService;
+import com.central.oauth.service.impl.UserDetailServiceFactory;
+import com.central.oauth.support.base.BaseAuthenticationProvider;
+import com.central.oauth.exception.CustomOAuth2AuthenticationException;
+import com.central.oauth2.common.token.PasswordCodeAuthenticationToken;
+import lombok.Getter;
+import lombok.Setter;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.security.oauth2.core.AuthorizationGrantType;
+import org.springframework.security.oauth2.core.OAuth2Token;
+import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
+import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
+import org.springframework.util.Assert;
+
+/**
+ * 用户名密码+图像验证码 provider
+ *
+ * @author zlt
+ * @version 1.0
+ * @date 2023/11/25
+ *
+ * Blog: http://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+@Setter
+@Getter
+public class PasswordCodeAuthenticationProvider extends BaseAuthenticationProvider {
+ private final UserDetailServiceFactory userDetailsServiceFactory;
+ private final PasswordEncoder passwordEncoder;
+ private final IValidateCodeService validateCodeService;
+
+ public PasswordCodeAuthenticationProvider(OAuth2AuthorizationService authorizationService
+ , OAuth2TokenGenerator extends OAuth2Token> tokenGenerator
+ , UserDetailServiceFactory userDetailsServiceFactory, PasswordEncoder passwordEncoder
+ , IValidateCodeService validateCodeService) {
+ super(authorizationService, tokenGenerator);
+ Assert.notNull(userDetailsServiceFactory, "userDetailsServiceFactory cannot be null");
+ Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
+ this.userDetailsServiceFactory = userDetailsServiceFactory;
+ this.passwordEncoder = passwordEncoder;
+ this.validateCodeService = validateCodeService;
+ }
+
+ @Override
+ public boolean supports(Class> authentication) {
+ return PasswordCodeAuthenticationToken.class.isAssignableFrom(authentication);
+ }
+
+ @Override
+ protected Authentication getPrincipal(Authentication authentication) {
+ PasswordCodeAuthenticationToken authToken = (PasswordCodeAuthenticationToken) authentication;
+ String deviceId = authToken.getDeviceId();
+ String validCode = authToken.getValidCode();
+
+ //校验图形验证码
+ validateCodeService.validate(deviceId, validCode);
+
+ String username = (String) authToken.getPrincipal();
+ String password = authToken.getCredentials();
+ UserDetails userDetails;
+ try {
+ userDetails = userDetailsServiceFactory.getService(authToken).loadUserByUsername(username);
+ } catch (AuthenticationException e) {
+ throw new CustomOAuth2AuthenticationException(e.getMessage());
+ }
+ if (userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())) {
+ throw new CustomOAuth2AuthenticationException("用户名或密码错误");
+ }
+ return new PasswordCodeAuthenticationToken(userDetails, userDetails.getPassword(), deviceId, userDetails.getAuthorities());
+ }
+
+ @Override
+ protected AuthorizationGrantType grantType() {
+ return PasswordCodeAuthenticationToken.GRANT_TYPE;
+ }
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/tenant/OauthAuthorizeAspect.java b/zlt-uaa/src/main/java/com/central/oauth/tenant/OauthAuthorizeAspect.java
deleted file mode 100644
index 8dec5042..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/tenant/OauthAuthorizeAspect.java
+++ /dev/null
@@ -1,64 +0,0 @@
-package com.central.oauth.tenant;
-
-import com.central.common.context.TenantContextHolder;
-import com.central.common.model.LoginAppUser;
-import com.central.oauth.service.impl.UserDetailServiceFactory;
-import com.central.oauth2.common.token.TenantUsernamePasswordAuthenticationToken;
-import lombok.extern.slf4j.Slf4j;
-import org.aspectj.lang.ProceedingJoinPoint;
-import org.aspectj.lang.annotation.Around;
-import org.aspectj.lang.annotation.Aspect;
-import org.springframework.security.oauth2.common.util.OAuth2Utils;
-import org.springframework.stereotype.Component;
-
-import java.security.Principal;
-import java.util.Map;
-
-/**
- * /oauth/authorize拦截器
- * 解决不同租户单点登录时角色没变化
- *
- * @author zlt
- * @date 2020/6/10
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Slf4j
-@Component
-@Aspect
-public class OauthAuthorizeAspect {
- private final UserDetailServiceFactory userDetailsServiceFactory;
-
- public OauthAuthorizeAspect(UserDetailServiceFactory userDetailsServiceFactory) {
- this.userDetailsServiceFactory = userDetailsServiceFactory;
- }
-
- @Around("execution(* org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.authorize(..))")
- public Object doAroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
- Object[] args = joinPoint.getArgs();
- Map parameters = (Map) args[1];
- Principal principal = (Principal) args[3];
- if (principal instanceof TenantUsernamePasswordAuthenticationToken) {
- TenantUsernamePasswordAuthenticationToken tenantToken = (TenantUsernamePasswordAuthenticationToken)principal;
- String clientId = tenantToken.getClientId();
- String requestClientId = parameters.get(OAuth2Utils.CLIENT_ID);
- //判断是否不同租户单点登录
- if (!requestClientId.equals(clientId)) {
- Object details = tenantToken.getDetails();
- try {
- TenantContextHolder.setTenant(requestClientId);
- //重新查询对应该租户的角色等信息
- LoginAppUser user = (LoginAppUser)userDetailsServiceFactory.getService(tenantToken)
- .loadUserByUsername(tenantToken.getName());
- tenantToken = new TenantUsernamePasswordAuthenticationToken(user, tenantToken.getCredentials(), user.getAuthorities(), requestClientId);
- tenantToken.setDetails(details);
- args[3] = tenantToken;
- } finally {
- TenantContextHolder.clear();
- }
- }
- }
- return joinPoint.proceed(args);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/tenant/TenantAuthenticationProvider.java b/zlt-uaa/src/main/java/com/central/oauth/tenant/TenantAuthenticationProvider.java
deleted file mode 100644
index c76d0ddc..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/tenant/TenantAuthenticationProvider.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package com.central.oauth.tenant;
-
-import com.central.oauth.password.PasswordAuthenticationProvider;
-import com.central.oauth2.common.token.TenantUsernamePasswordAuthenticationToken;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.userdetails.UserDetails;
-
-/**
- * 增加租户id,解决不同租户单点登录时角色没变化
- *
- * @author zlt
- * @date 2020/6/10
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-public class TenantAuthenticationProvider extends PasswordAuthenticationProvider {
- @Override
- protected Authentication createSuccessAuthentication(Object principal,
- Authentication authentication, UserDetails user) {
- TenantUsernamePasswordAuthenticationToken authenticationToken = (TenantUsernamePasswordAuthenticationToken) authentication;
- TenantUsernamePasswordAuthenticationToken result = new TenantUsernamePasswordAuthenticationToken(
- principal, authentication.getCredentials(), user.getAuthorities(), authenticationToken.getClientId());
- result.setDetails(authenticationToken.getDetails());
- return result;
- }
-
- @Override
- public boolean supports(Class> authentication) {
- return TenantUsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/tenant/TenantAuthenticationSecurityConfig.java b/zlt-uaa/src/main/java/com/central/oauth/tenant/TenantAuthenticationSecurityConfig.java
deleted file mode 100644
index 1d00c9a9..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/tenant/TenantAuthenticationSecurityConfig.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.central.oauth.tenant;
-
-import com.central.oauth.service.impl.UserDetailServiceFactory;
-import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
-import org.springframework.security.config.annotation.web.builders.HttpSecurity;
-import org.springframework.security.crypto.password.PasswordEncoder;
-import org.springframework.security.web.DefaultSecurityFilterChain;
-import org.springframework.stereotype.Component;
-
-/**
- * @author zlt
- * @date 2020/6/10
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Component
-public class TenantAuthenticationSecurityConfig extends SecurityConfigurerAdapter {
- private final UserDetailServiceFactory userDetailsServiceFactory;
-
- private final PasswordEncoder passwordEncoder;
-
- public TenantAuthenticationSecurityConfig(UserDetailServiceFactory userDetailsServiceFactory, PasswordEncoder passwordEncoder) {
- this.userDetailsServiceFactory = userDetailsServiceFactory;
- this.passwordEncoder = passwordEncoder;
- }
-
- @Override
- public void configure(HttpSecurity http) {
- TenantAuthenticationProvider provider = new TenantAuthenticationProvider();
- provider.setUserDetailsServiceFactory(userDetailsServiceFactory);
- provider.setPasswordEncoder(passwordEncoder);
- http.authenticationProvider(provider);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/tenant/TenantUsernamePasswordAuthenticationFilter.java b/zlt-uaa/src/main/java/com/central/oauth/tenant/TenantUsernamePasswordAuthenticationFilter.java
deleted file mode 100644
index 2b6779d9..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/tenant/TenantUsernamePasswordAuthenticationFilter.java
+++ /dev/null
@@ -1,59 +0,0 @@
-package com.central.oauth.tenant;
-
-import com.central.common.context.TenantContextHolder;
-import com.central.oauth2.common.token.TenantUsernamePasswordAuthenticationToken;
-import lombok.Setter;
-import org.springframework.security.authentication.AuthenticationServiceException;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-/**
- * 替换 UsernamePasswordAuthenticationFilter 增加租户id
- *
- * @author zlt
- * @date 2020/6/10
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Setter
-public class TenantUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
- private boolean postOnly = true;
-
- public TenantUsernamePasswordAuthenticationFilter () {
- super();
- }
-
- @Override
- public Authentication attemptAuthentication(HttpServletRequest request,
- HttpServletResponse response) throws AuthenticationException {
- if (postOnly && !request.getMethod().equals("POST")) {
- throw new AuthenticationServiceException(
- "Authentication method not supported: " + request.getMethod());
- }
-
- String username = obtainUsername(request);
- String password = obtainPassword(request);
- String clientId = TenantContextHolder.getTenant();
-
- if (username == null) {
- username = "";
- }
-
- if (password == null) {
- password = "";
- }
-
- username = username.trim();
-
- TenantUsernamePasswordAuthenticationToken authRequest = new TenantUsernamePasswordAuthenticationToken(username, password, clientId);
-
- setDetails(request, authRequest);
-
- return getAuthenticationManager().authenticate(authRequest);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/utils/OAuth2ConfigurerUtils.java b/zlt-uaa/src/main/java/com/central/oauth/utils/OAuth2ConfigurerUtils.java
new file mode 100644
index 00000000..010bcaab
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/utils/OAuth2ConfigurerUtils.java
@@ -0,0 +1,197 @@
+package com.central.oauth.utils;
+
+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
+ *
+ * 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 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 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 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 getJwkSource(HttpSecurity httpSecurity) {
+ JWKSource 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 getJwtCustomizer(HttpSecurity httpSecurity) {
+ ResolvableType type = ResolvableType.forClassWithGenerics(OAuth2TokenCustomizer.class, JwtEncodingContext.class);
+ return getOptionalBean(httpSecurity, type);
+ }
+
+ private static OAuth2TokenCustomizer 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 getBean(HttpSecurity httpSecurity, Class type) {
+ return httpSecurity.getSharedObject(ApplicationContext.class).getBean(type);
+ }
+
+ @SuppressWarnings("unchecked")
+ public static 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 getOptionalBean(HttpSecurity httpSecurity, Class type) {
+ Map 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 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;
+ }
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/utils/OAuthEndpointUtils.java b/zlt-uaa/src/main/java/com/central/oauth/utils/OAuthEndpointUtils.java
new file mode 100644
index 00000000..96d0ed1a
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/utils/OAuthEndpointUtils.java
@@ -0,0 +1,94 @@
+package com.central.oauth.utils;
+
+import jakarta.servlet.http.HttpServletRequest;
+import org.springframework.security.oauth2.core.AuthorizationGrantType;
+import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
+import org.springframework.security.oauth2.core.OAuth2Error;
+import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
+import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
+import org.springframework.security.oauth2.core.endpoint.PkceParameterNames;
+import org.springframework.util.Assert;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
+import org.springframework.util.StringUtils;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @author: zlt
+ * @date: 2023/11/14
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+public class OAuthEndpointUtils {
+ public static final String ACCESS_TOKEN_REQUEST_ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2";
+ private OAuthEndpointUtils() {
+ }
+
+ public static MultiValueMap getParameters(HttpServletRequest request) {
+ Map parameterMap = request.getParameterMap();
+ MultiValueMap