From 387b524f675770f4a541561629130eb715e33248 Mon Sep 17 00:00:00 2001 From: zlt2000 Date: Fri, 24 Nov 2023 17:28:19 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=9B=BF=E6=8D=A2swagger2=E4=B8=BAOpen?= =?UTF-8?q?API3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 - pom.xml | 61 +- zlt-business/code-generator/pom.xml | 4 +- .../controller/SysGeneratorController.java | 5 +- .../src/main/resources/application.yml | 21 +- .../resources/template/Controller.java.vm | 32 +- zlt-business/file-center/pom.xml | 4 +- .../src/main/resources/application.yml | 25 +- .../search-center/search-server/pom.xml | 5 +- .../admin/controller/IndexController.java | 4 +- .../controller/AggregationController.java | 4 +- .../search/controller/SearchController.java | 4 +- .../src/main/resources/application.yml | 27 +- zlt-business/user-center/pom.xml | 4 +- .../user/controller/SysMenuController.java | 23 +- .../user/controller/SysRoleController.java | 13 +- .../user/controller/SysUserController.java | 49 +- .../src/main/resources/application.yml | 25 +- zlt-commons/pom.xml | 1 - .../pom.xml | 8 +- .../config/DefaultResourceServerConf.java | 86 --- .../config/DefaultSecurityHandlerConfig.java | 54 -- .../common/constants/IdTokenClaimNames.java | 89 --- .../CustomUserAuthenticationConverter.java | 96 ---- .../CustomOAuth2AuthenticationException.java | 17 + .../impl/CustomBearerTokenExtractor.java | 44 -- .../impl/CustomBearerTokenResolver.java | 112 ++++ .../impl/DefaultPermissionServiceImpl.java | 120 ---- .../oauth2/common/store/AuthDbTokenStore.java | 28 - .../common/store/AuthJwtTokenStore.java | 55 -- .../common/store/AuthRedisTokenStore.java | 29 - .../common/store/CustomRedisTokenStore.java | 543 ------------------ .../oauth2/common/store/ResJwtTokenStore.java | 89 --- .../common/token/BaseAuthenticationToken.java | 66 +++ .../common/token/CustomAccessToken.java | 19 + .../central/oauth2/common/util/AuthUtils.java | 71 +-- .../central/oauth2/common/util/JwtUtils.java | 108 ---- zlt-commons/zlt-common-core/pom.xml | 5 - .../pom.xml | 6 - .../zlt-swagger2-spring-boot-starter/pom.xml | 29 - .../swagger2/SwaggerAutoConfiguration.java | 271 --------- .../common/swagger2/SwaggerProperties.java | 114 ---- .../main/resources/META-INF/spring.factories | 2 - .../java/org/zlt/config/MyResourceConfig.java | 7 +- .../com/sso/demo/config/SecurityConfig.java | 4 +- .../java/org/zlt/config/MyResourceConfig.java | 4 +- zlt-doc/sql/oauth-center.sql | 9 +- zlt-doc/版本升级_sql/旧版本升级v6.0.0.sql | 5 + zlt-gateway/sc-gateway/pom.xml | 1 - .../auth/CustomAuthenticationManager.java | 49 -- .../auth/CustomServerWebExchangeMatchers.java | 38 -- .../gateway/auth/JsonAccessDeniedHandler.java | 26 - .../auth/JsonAuthenticationEntryPoint.java | 26 - .../auth/Oauth2AuthSuccessHandler.java | 54 -- .../gateway/auth/PermissionAuthManager.java | 56 -- .../config/ResourceServerConfiguration.java | 71 --- .../src/main/resources/application.yml | 6 + zlt-monitor/log-center/pom.xml | 4 +- .../log/controller/AggregationController.java | 6 +- .../log/controller/AuditLogController.java | 13 +- .../controller/SlowQueryLogController.java | 13 +- .../log/controller/SysLogController.java | 24 +- zlt-uaa/pom.xml | 14 - .../controller/ValidateCodeController.java | 23 +- .../oauth/service/IValidateCodeService.java | 2 +- .../service/impl/ValidateCodeServiceImpl.java | 2 +- zlt-uaa/src/main/resources/application.yml | 44 +- 67 files changed, 494 insertions(+), 2380 deletions(-) delete mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/DefaultResourceServerConf.java delete mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/DefaultSecurityHandlerConfig.java delete mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/constants/IdTokenClaimNames.java delete mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/converter/CustomUserAuthenticationConverter.java create mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/exception/CustomOAuth2AuthenticationException.java delete mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/CustomBearerTokenExtractor.java create mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/CustomBearerTokenResolver.java delete mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/DefaultPermissionServiceImpl.java delete mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthDbTokenStore.java delete mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthJwtTokenStore.java delete mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthRedisTokenStore.java delete mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/CustomRedisTokenStore.java delete mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/ResJwtTokenStore.java create mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/BaseAuthenticationToken.java create mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/CustomAccessToken.java delete mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/JwtUtils.java delete mode 100644 zlt-commons/zlt-swagger2-spring-boot-starter/pom.xml delete mode 100644 zlt-commons/zlt-swagger2-spring-boot-starter/src/main/java/com/central/common/swagger2/SwaggerAutoConfiguration.java delete mode 100644 zlt-commons/zlt-swagger2-spring-boot-starter/src/main/java/com/central/common/swagger2/SwaggerProperties.java delete mode 100644 zlt-commons/zlt-swagger2-spring-boot-starter/src/main/resources/META-INF/spring.factories create mode 100644 zlt-doc/版本升级_sql/旧版本升级v6.0.0.sql delete mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/CustomAuthenticationManager.java delete mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/CustomServerWebExchangeMatchers.java delete mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/JsonAccessDeniedHandler.java delete mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/JsonAuthenticationEntryPoint.java delete mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2AuthSuccessHandler.java delete mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/PermissionAuthManager.java delete mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java diff --git a/README.md b/README.md index 24d34509..41513486 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,6 @@ central-platform -- 父项目,公共依赖 │ │ ├─zlt-redis-spring-boot-starter -- 封装Redis通用操作逻辑 │ │ ├─zlt-loadbalancer-spring-boot-starter -- 封装Loadbalancer和Feign的通用操作逻辑 │ │ ├─zlt-sentinel-spring-boot-starter -- 封装Sentinel的通用操作逻辑 -│ │ ├─zlt-swagger2-spring-boot-starter -- 封装Swagger通用操作逻辑 │ │ ├─zlt-elasticsearch-spring-boot-starter -- 封装Elasticsearch通用操作逻辑 │ │ ├─zlt-oss-spring-boot-starter -- 封装对象存储通用操作逻辑 │ │ ├─zlt-zookeeper-spring-boot-starter -- 封装Zookeeper通用操作逻辑 diff --git a/pom.xml b/pom.xml index f2c8f453..60bb2608 100644 --- a/pom.xml +++ b/pom.xml @@ -14,8 +14,8 @@ UTF-8 17 2022.0.0.0 - 3.0.9 - 2022.0.3 + 3.1.6 + 2022.0.4 4.4 2.0.1 0.9.1 @@ -24,10 +24,9 @@ 3.1.0 2.3.8.RELEASE 1.1.0.RELEASE - 3.23.2 - 1.6.2 + 3.24.3 5.7.20 - 3.5.3.1 + 3.5.4.1 3.8.1 7.2.28 4.1.3 @@ -35,7 +34,6 @@ 2.5.6 1.7 2.7 - 5.0.2.RELEASE 1.27.2 1.21 2.14.3 @@ -43,20 +41,17 @@ 1.9.4 1.1.6.RELEASE 2.7 - 4.0.1 4.2.3 7.13.4 - 3.0.3 + 4.3.0 8.0.1.Final 2.7.8 5.1.0 2.13.4 1.10 - 2.2.9.RELEASE 1.12.40 2.2.5.RELEASE 1.2.2 - zlt-job/**/*, zlt-register/**/*, zlt-web/**/* openjdk:8-jre-alpine /tmp hub.zlt.com:8080/microservices-platform @@ -69,6 +64,7 @@ 1.3.2 10.1.11 5.2.1 + 1.1.1 @@ -136,11 +132,6 @@ zlt-redis-spring-boot-starter ${project.version} - - com.zlt - zlt-swagger2-spring-boot-starter - ${project.version} - com.zlt zlt-loadbalancer-spring-boot-starter @@ -221,12 +212,6 @@ swagger-butler-core ${swagger.butler.version} - - - com.github.whvcse - easy-captcha - ${easyCaptcha.version} - cn.hutool @@ -275,21 +260,6 @@ commons-configuration2 ${commons-configuration2.version} - - com.codingapi.txlcn - txlcn-tm - ${txlcn.version} - - - com.codingapi.txlcn - txlcn-tc - ${txlcn.version} - - - com.codingapi.txlcn - txlcn-txmsg-netty - ${txlcn.version} - io.shardingsphere sharding-jdbc-spring-boot-starter @@ -330,11 +300,6 @@ commons-io ${commons-io.version} - - javax.servlet - javax.servlet-api - ${servlet-api.version} - org.springframework.data spring-data-elasticsearch @@ -405,6 +370,11 @@ jackson-databind ${jackson-databind.version} + + org.springframework.security + spring-security-oauth2-authorization-server + ${spring.authorization.version} + org.springframework.cloud spring-cloud-starter-oauth2 @@ -415,11 +385,6 @@ aws-java-sdk-s3 ${aws-java-sdk-s3.version} - - org.springframework.cloud - spring-cloud-starter-netflix-zuul - ${zuul.version} - commons-configuration commons-configuration @@ -467,13 +432,13 @@ httpclient5 ${httpclient.version} - + diff --git a/zlt-business/code-generator/pom.xml b/zlt-business/code-generator/pom.xml index d7f26bc2..9710d51f 100644 --- a/zlt-business/code-generator/pom.xml +++ b/zlt-business/code-generator/pom.xml @@ -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 f4c1641e..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,6 +3,7 @@ package com.central.generator.controller; import java.io.IOException; import java.util.Map; +import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletResponse; import com.central.common.model.PageResult; @@ -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..db1a0bc2 100644 --- a/zlt-business/code-generator/src/main/resources/application.yml +++ b/zlt-business/code-generator/src/main/resources/application.yml @@ -8,4 +8,23 @@ 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: + swagger-ui: + path: /swagger-ui.html + tags-sorter: alpha + operations-sorter: alpha + api-docs: + path: /v3/api-docs + group-configs: + - group: 'code' + paths-to-match: '/**' + packages-to-scan: com.central.generator.controller + default-flat-param-object: true + +knife4j: + enable: true + setting: + language: zh_cn + 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..24b9cc54 100644 --- a/zlt-business/file-center/pom.xml +++ b/zlt-business/file-center/pom.xml @@ -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/resources/application.yml b/zlt-business/file-center/src/main/resources/application.yml index 839effbe..a0ee2d8d 100644 --- a/zlt-business/file-center/src/main/resources/application.yml +++ b/zlt-business/file-center/src/main/resources/application.yml @@ -13,6 +13,25 @@ mybatis-plus: db-config: id-type: INPUT +springdoc: + swagger-ui: + path: /swagger-ui.html + tags-sorter: alpha + operations-sorter: alpha + api-docs: + path: /v3/api-docs + group-configs: + - group: 'file' + paths-to-match: '/**' + packages-to-scan: com.central.file.controller + default-flat-param-object: true + +knife4j: + enable: true + setting: + language: zh_cn + swagger-model-name: 文件中心接口文档 + zlt: file-server: type: s3 @@ -23,12 +42,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/search-center/search-server/pom.xml b/zlt-business/search-center/search-server/pom.xml index caac10f4..169d653f 100644 --- a/zlt-business/search-center/search-server/pom.xml +++ b/zlt-business/search-center/search-server/pom.xml @@ -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/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/resources/application.yml b/zlt-business/search-center/search-server/src/main/resources/application.yml index e7502fd3..8a1c3e80 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 @@ -4,12 +4,25 @@ spring: username: ${zlt.elasticsearch.username} password: ${zlt.elasticsearch.password} +springdoc: + swagger-ui: + path: /swagger-ui.html + tags-sorter: alpha + operations-sorter: alpha + api-docs: + path: /v3/api-docs + group-configs: + - group: 'search' + paths-to-match: '/**' + packages-to-scan: com.central.search.controller + default-flat-param-object: true + +knife4j: + enable: true + setting: + language: zh_cn + 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..c87dd05e 100644 --- a/zlt-business/user-center/pom.xml +++ b/zlt-business/user-center/pom.xml @@ -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/controller/SysMenuController.java b/zlt-business/user-center/src/main/java/com/central/user/controller/SysMenuController.java index eaf16e99..dfe8727c 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 @@ -10,6 +10,8 @@ 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 +20,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 +60,7 @@ public class SysMenuController { * * @param id */ - @ApiOperation(value = "删除菜单") + @Operation(summary = "删除菜单") @DeleteMapping("/{id}") public Result delete(@PathVariable Long id) { try { @@ -73,7 +72,7 @@ public class SysMenuController { } } - @ApiOperation(value = "根据roleId获取对应的菜单") + @Operation(summary = "根据roleId获取对应的菜单") @GetMapping("/{roleId}/menus") public List> findMenusByRoleId(@PathVariable Long roleId) { Set roleIds = new HashSet<>(); @@ -101,7 +100,7 @@ public class SysMenuController { return authTrees; } - @ApiOperation(value = "根据roleCodes获取对应的权限") + @Operation(summary = "根据roleCodes获取对应的权限") @SuppressWarnings("unchecked") @Cacheable(value = "menu", key ="#roleCodes") @GetMapping("/{roleCodes}") @@ -117,21 +116,21 @@ public class SysMenuController { /** * 给角色分配菜单 */ - @ApiOperation(value = "角色分配菜单") + @Operation(summary = "角色分配菜单") @PostMapping("/granted") public Result setMenuToRole(@RequestBody SysMenu sysMenu) { menuService.setMenuToRole(sysMenu.getRoleId(), sysMenu.getMenuIds()); return Result.succeed("操作成功"); } - @ApiOperation(value = "查询所有菜单") + @Operation(summary = "查询所有菜单") @GetMapping("/findAlls") public PageResult findAlls() { List list = menuService.findAll(); return PageResult.builder().data(list).code(0).count((long) list.size()).build(); } - @ApiOperation(value = "获取菜单以及顶级菜单") + @Operation(summary = "获取菜单以及顶级菜单") @GetMapping("/findOnes") public PageResult findOnes() { List list = menuService.findOnes(); @@ -144,7 +143,7 @@ public class SysMenuController { * @param menu * @return */ - @ApiOperation(value = "新增菜单") + @Operation(summary = "新增菜单") @PostMapping("saveOrUpdate") public Result saveOrUpdate(@RequestBody SysMenu menu) { try { @@ -165,7 +164,7 @@ public class SysMenuController { * @return */ @GetMapping("/current") - @ApiOperation(value = "查询当前用户菜单") + @Operation(summary = "查询当前用户菜单") public List findMyMenu(@LoginUser SysUser user) { List roles = user.getRoles(); if (CollectionUtil.isEmpty(roles)) { diff --git a/zlt-business/user-center/src/main/java/com/central/user/controller/SysRoleController.java b/zlt-business/user-center/src/main/java/com/central/user/controller/SysRoleController.java index 80de7d23..d1351214 100644 --- a/zlt-business/user-center/src/main/java/com/central/user/controller/SysRoleController.java +++ b/zlt-business/user-center/src/main/java/com/central/user/controller/SysRoleController.java @@ -3,6 +3,8 @@ package com.central.user.controller; import java.util.List; import java.util.Map; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; @@ -18,16 +20,13 @@ import com.central.common.model.Result; import com.central.common.model.SysRole; import com.central.user.service.ISysRoleService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; - /** * @author 作者 owen E-mail: 624191343@qq.com * 角色管理 */ @Slf4j @RestController -@Api(tags = "角色模块api") +@Tag(name = "角色模块api") public class SysRoleController { @Autowired private ISysRoleService sysRoleService; @@ -37,7 +36,7 @@ public class SysRoleController { * @param params * @return */ - @ApiOperation(value = "后台管理查询角色") + @Operation(summary = "后台管理查询角色") @GetMapping("/roles") public PageResult findRoles(@RequestParam Map params) { return sysRoleService.findRoles(params); @@ -47,7 +46,7 @@ public class SysRoleController { * 用户管理查询所有角色 * @return */ - @ApiOperation(value = "后台管理查询角色") + @Operation(summary = "后台管理查询角色") @GetMapping("/allRoles") public Result> findAll() { List result = sysRoleService.findAll(); @@ -71,7 +70,7 @@ public class SysRoleController { * * @param id */ - @ApiOperation(value = "后台管理删除角色") + @Operation(summary = "后台管理删除角色") @DeleteMapping("/roles/{id}") public Result deleteRole(@PathVariable Long id) { try { diff --git a/zlt-business/user-center/src/main/java/com/central/user/controller/SysUserController.java b/zlt-business/user-center/src/main/java/com/central/user/controller/SysUserController.java index 12eeace9..fc53459f 100644 --- a/zlt-business/user-center/src/main/java/com/central/user/controller/SysUserController.java +++ b/zlt-business/user-center/src/main/java/com/central/user/controller/SysUserController.java @@ -18,6 +18,11 @@ import com.central.search.model.LogicDelDto; import com.central.search.model.SearchDto; import com.central.user.model.SysUserExcel; import com.fasterxml.jackson.databind.JsonNode; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; import org.apache.commons.collections4.MapUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; @@ -27,10 +32,6 @@ import org.springframework.web.bind.annotation.*; import com.central.user.service.ISysUserService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.web.multipart.MultipartFile; @@ -42,7 +43,7 @@ import jakarta.servlet.http.HttpServletResponse; */ @Slf4j @RestController -@Api(tags = "用户模块api") +@Tag(name = "用户模块api") public class SysUserController { private static final String ADMIN_CHANGE_MSG = "超级管理员不给予修改"; @@ -62,7 +63,7 @@ public class SysUserController { * * @return */ - @ApiOperation(value = "根据access_token当前登录用户") + @Operation(summary = "根据access_token当前登录用户") @GetMapping("/users/current") public Result getLoginAppUser(@LoginUser(isFull = true) SysUser user) { return Result.succeed(appUserService.getLoginAppUser(user)); @@ -72,7 +73,7 @@ public class SysUserController { * 查询用户实体对象SysUser */ @GetMapping(value = "/users/name/{username}") - @ApiOperation(value = "根据用户名查询用户实体") + @Operation(summary = "根据用户名查询用户实体") @Cacheable(value = "user", key = "#username") public SysUser selectByUsername(@PathVariable String username) { return appUserService.selectByUsername(username); @@ -82,7 +83,7 @@ public class SysUserController { * 查询用户登录对象LoginAppUser */ @GetMapping(value = "/users-anon/login", params = "username") - @ApiOperation(value = "根据用户名查询用户") + @Operation(summary = "根据用户名查询用户") public LoginAppUser findByUsername(String username) { return appUserService.findByUsername(username); } @@ -93,7 +94,7 @@ public class SysUserController { * @param mobile 手机号 */ @GetMapping(value = "/users-anon/mobile", params = "mobile") - @ApiOperation(value = "根据手机号查询用户") + @Operation(summary = "根据手机号查询用户") public SysUser findByMobile(String mobile) { return appUserService.findByMobile(mobile); } @@ -104,7 +105,7 @@ public class SysUserController { * @param openId openId */ @GetMapping(value = "/users-anon/openId", params = "openId") - @ApiOperation(value = "根据OpenId查询用户") + @Operation(summary = "根据OpenId查询用户") public SysUser findByOpenId(String openId) { return appUserService.findByOpenId(openId); } @@ -154,10 +155,10 @@ public class SysUserController { * @param params * @return */ - @ApiOperation(value = "用户查询列表") - @ApiImplicitParams({ - @ApiImplicitParam(name = "page", value = "分页起始位置", required = true, dataType = "Integer"), - @ApiImplicitParam(name = "limit", value = "分页结束位置", required = true, dataType = "Integer") + @Operation(summary = "用户查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in= ParameterIn.QUERY) }) @GetMapping("/users") public PageResult findUsers(@RequestParam Map params) { @@ -170,11 +171,11 @@ public class SysUserController { * @param params * @return */ - @ApiOperation(value = "修改用户状态") + @Operation(summary = "修改用户状态") @GetMapping("/users/updateEnabled") - @ApiImplicitParams({ - @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Integer"), - @ApiImplicitParam(name = "enabled", value = "是否启用", required = true, dataType = "Boolean") + @Parameters({ + @Parameter(name = "id",description = "用户id",required = true,in=ParameterIn.QUERY), + @Parameter(name = "enabled",description = "是否启用",required = true,in= ParameterIn.QUERY) }) public Result updateEnabled(@RequestParam Map params) { Long id = MapUtils.getLong(params, "id"); @@ -273,11 +274,11 @@ public class SysUserController { return Result.succeed("导入数据成功,一共【"+rowNum+"】行"); } - @ApiOperation(value = "用户全文搜索列表") - @ApiImplicitParams({ - @ApiImplicitParam(name = "page", value = "分页起始位置", required = true, dataType = "Integer"), - @ApiImplicitParam(name = "limit", value = "分页结束位置", required = true, dataType = "Integer"), - @ApiImplicitParam(name = "queryStr", value = "搜索关键字", dataType = "String") + @Operation(summary = "用户全文搜索列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in= ParameterIn.QUERY), + @Parameter(name = "queryStr",description = "搜索关键字",in= ParameterIn.QUERY) }) @GetMapping("/users/search") public PageResult search(SearchDto searchDto) { @@ -292,7 +293,7 @@ public class SysUserController { * @return */ @GetMapping(value = "/users/roleUser/{username}") - @ApiOperation(value = "查询用户-带角色信息") + @Operation(summary = "查询用户-带角色信息") @Cacheable(value = "userRoles", key = "#username") public SysUser selectRoleUser(@PathVariable("username") String username){ SysUser sysUser = selectByUsername(username); diff --git a/zlt-business/user-center/src/main/resources/application.yml b/zlt-business/user-center/src/main/resources/application.yml index b5a9296a..123f260d 100644 --- a/zlt-business/user-center/src/main/resources/application.yml +++ b/zlt-business/user-center/src/main/resources/application.yml @@ -13,13 +13,26 @@ mybatis-plus: db-config: id-type: auto +springdoc: + swagger-ui: + path: /swagger-ui.html + tags-sorter: alpha + operations-sorter: alpha + api-docs: + path: /v3/api-docs + group-configs: + - group: 'user' + paths-to-match: '/**' + packages-to-scan: com.central.user.controller + default-flat-param-object: true + +knife4j: + enable: true + setting: + language: zh_cn + swagger-model-name: 用户中心接口文档 + zlt: - swagger: - enabled: true - title: 用户中心 - description: 用户中心接口文档 - version: 1.0 - base-package: com.central.user.controller cache-manager: configs: - key: menu diff --git a/zlt-commons/pom.xml b/zlt-commons/pom.xml index 2df13283..fbea07e1 100644 --- a/zlt-commons/pom.xml +++ b/zlt-commons/pom.xml @@ -14,7 +14,6 @@ zlt-redis-spring-boot-starter zlt-common-spring-boot-starter zlt-db-spring-boot-starter - zlt-swagger2-spring-boot-starter zlt-log-spring-boot-starter zlt-loadbalancer-spring-boot-starter zlt-auth-client-spring-boot-starter diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/pom.xml b/zlt-commons/zlt-auth-client-spring-boot-starter/pom.xml index a303d2e9..f2fedfc5 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/pom.xml +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/pom.xml @@ -13,8 +13,8 @@ 认证客户端通用组件 - org.springframework.cloud - spring-cloud-starter-oauth2 + org.springframework.security + spring-security-oauth2-authorization-server com.zlt @@ -42,9 +42,5 @@ tomcat-embed-websocket true - - javax.servlet - javax.servlet-api - diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/DefaultResourceServerConf.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/DefaultResourceServerConf.java deleted file mode 100644 index f84bbe85..00000000 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/DefaultResourceServerConf.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.central.oauth2.common.config; - -import com.central.oauth2.common.properties.SecurityProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Import; -import org.springframework.http.HttpMethod; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; -import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; -import org.springframework.security.oauth2.provider.authentication.TokenExtractor; -import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler; -import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.web.AuthenticationEntryPoint; - -import javax.annotation.Resource; - -/** - * @author zlt - */ -@Import(DefaultSecurityHandlerConfig.class) -public class DefaultResourceServerConf extends ResourceServerConfigurerAdapter { - @Autowired - private TokenStore tokenStore; - - @Resource - private AuthenticationEntryPoint authenticationEntryPoint; - - @Resource - private OAuth2WebSecurityExpressionHandler expressionHandler; - - @Resource - private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler; - - @Autowired - private SecurityProperties securityProperties; - - @Resource - private TokenExtractor tokenExtractor; - - @Override - public void configure(ResourceServerSecurityConfigurer resources) { - resources.tokenStore(tokenStore) - .stateless(true) - .authenticationEntryPoint(authenticationEntryPoint) - .expressionHandler(expressionHandler) - .accessDeniedHandler(oAuth2AccessDeniedHandler) - .tokenExtractor(tokenExtractor); - } - - @Override - public void configure(HttpSecurity http) throws Exception { - AuthorizeHttpRequestsConfigurer.AuthorizedUrl authorizedUrl = setHttp(http) - .authorizeHttpRequests() - .requestMatchers(securityProperties.getIgnore().getUrls()).permitAll() - .requestMatchers(HttpMethod.OPTIONS).permitAll() - .anyRequest(); - setAuthenticate(authorizedUrl); - - http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) - .and() - .httpBasic().disable() - .headers() - .frameOptions().disable() - .and() - .csrf().disable(); - } - - /** - * url权限控制,默认是认证就通过,可以重写实现个性化 - * @param authorizedUrl - */ - public HttpSecurity setAuthenticate(AuthorizeHttpRequestsConfigurer.AuthorizedUrl authorizedUrl) { - return authorizedUrl.authenticated().and(); - } - - /** - * 留给子类重写扩展功能 - * @param http - */ - public HttpSecurity setHttp(HttpSecurity http) { - return http; - } -} \ No newline at end of file diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/DefaultSecurityHandlerConfig.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/DefaultSecurityHandlerConfig.java deleted file mode 100644 index d12d9cad..00000000 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/DefaultSecurityHandlerConfig.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.central.oauth2.common.config; - -import com.central.common.utils.ResponseUtil; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.security.access.AccessDeniedException; -import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler; -import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler; -import org.springframework.security.web.AuthenticationEntryPoint; - -import javax.annotation.Resource; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import java.io.IOException; - -/** - * @author zlt - */ -public class DefaultSecurityHandlerConfig { - @Resource - private ObjectMapper objectMapper; - - /** - * 未登录,返回401 - * - * @return - */ - @Bean - public AuthenticationEntryPoint authenticationEntryPoint() { - return (request, response, authException) -> ResponseUtil.responseFailed(objectMapper, response, authException.getMessage()); - } - - @Bean - public OAuth2WebSecurityExpressionHandler oAuth2WebSecurityExpressionHandler(ApplicationContext applicationContext) { - OAuth2WebSecurityExpressionHandler expressionHandler = new OAuth2WebSecurityExpressionHandler(); - expressionHandler.setApplicationContext(applicationContext); - return expressionHandler; - } - - /** - * 处理spring security oauth 处理失败返回消息格式 - */ - @Bean - public OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler() { - return new OAuth2AccessDeniedHandler() { - - @Override - public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException { - ResponseUtil.responseFailed(objectMapper, response, authException.getMessage()); - } - }; - } -} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/constants/IdTokenClaimNames.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/constants/IdTokenClaimNames.java deleted file mode 100644 index 5c1840de..00000000 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/constants/IdTokenClaimNames.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.central.oauth2.common.constants; - -/** - * id_token属性名常量 - * - * @author zlt - * @version 1.0 - * @date 2021/4/23 - *

- * Blog: http://zlt2000.gitee.io - * Github: https://github.com/zlt2000 - */ -public class IdTokenClaimNames { - /** - * {@code iss} - the Issuer identifier - */ - public final static String ISS = "iss"; - - /** - * {@code sub} - the Subject identifier - */ - public final static String SUB = "sub"; - - /** - * {@code aud} - the Audience(s) that the ID Token is intended for - */ - public final static String AUD = "aud"; - - /** - * {@code exp} - the Expiration time on or after which the ID Token MUST NOT be accepted - */ - public final static String EXP = "exp"; - - /** - * {@code iat} - the time at which the ID Token was issued - */ - public final static String IAT = "iat"; - - /** - * {@code auth_time} - the time when the End-User authentication occurred - */ - public final static String AUTH_TIME = "auth_time"; - - /** - * {@code nonce} - a {@code String} value used to associate a Client session with an ID Token, - * and to mitigate replay attacks. - */ - public final static String NONCE = "nonce"; - - /** - * {@code acr} - the Authentication Context Class Reference - */ - public final static String ACR = "acr"; - - /** - * {@code amr} - the Authentication Methods References - */ - public final static String AMR = "amr"; - - /** - * {@code azp} - the Authorized party to which the ID Token was issued - */ - public final static String AZP = "azp"; - - /** - * {@code at_hash} - the Access Token hash value - */ - public final static String AT_HASH = "at_hash"; - - /** - * {@code c_hash} - the Authorization Code hash value - */ - public final static String C_HASH = "c_hash"; - - /** - * {@code name} - 用户姓名 - */ - public final static String NAME = "name"; - - /** - * {@code login_name} - 登录名 - */ - public final static String L_NAME = "login_name"; - - /** - * {@code picture} - 头像照片 - */ - public final static String PIC = "picture"; -} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/converter/CustomUserAuthenticationConverter.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/converter/CustomUserAuthenticationConverter.java deleted file mode 100644 index fbc86581..00000000 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/converter/CustomUserAuthenticationConverter.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.central.oauth2.common.converter; - -import com.central.common.model.LoginAppUser; -import com.central.common.model.SysUser; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter; -import org.springframework.util.StringUtils; - -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * 优化自org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter - * jwt返回的principal改为返回SysUser,增加扩展字段 - * - * @author zlt - * @date 2019/8/5 - */ -public class CustomUserAuthenticationConverter implements UserAuthenticationConverter { - private Collection defaultAuthorities; - - private UserDetailsService userDetailsService; - - /** - * Optional {@link UserDetailsService} to use when extracting an {@link Authentication} from the incoming map. - * - * @param userDetailsService the userDetailsService to set - */ - public void setUserDetailsService(UserDetailsService userDetailsService) { - this.userDetailsService = userDetailsService; - } - - /** - * Default value for authorities if an Authentication is being created and the input has no data for authorities. - * Note that unless this property is set, the default Authentication created by {@link #extractAuthentication(Map)} - * will be unauthenticated. - * - * @param defaultAuthorities the defaultAuthorities to set. Default null. - */ - public void setDefaultAuthorities(String[] defaultAuthorities) { - this.defaultAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils - .arrayToCommaDelimitedString(defaultAuthorities)); - } - - @Override - public Map convertUserAuthentication(Authentication authentication) { - Map response = new LinkedHashMap(); - response.put(USERNAME, authentication.getName()); - if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) { - response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities())); - } - return response; - } - - @Override - public Authentication extractAuthentication(Map map) { - if (map.containsKey(USERNAME)) { - Object principal = map.get(USERNAME); - Collection authorities = getAuthorities(map); - if (userDetailsService != null) { - UserDetails user = userDetailsService.loadUserByUsername((String) map.get(USERNAME)); - authorities = user.getAuthorities(); - principal = user; - } else { - Integer id = (Integer)map.get("id"); - LoginAppUser user = new LoginAppUser(); - user.setUsername((String)principal); - user.setId(Long.valueOf(id)); - principal = user; - } - return new UsernamePasswordAuthenticationToken(principal, "N/A", authorities); - } - return null; - } - - private Collection getAuthorities(Map map) { - if (!map.containsKey(AUTHORITIES)) { - return defaultAuthorities; - } - Object authorities = map.get(AUTHORITIES); - if (authorities instanceof String) { - return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities); - } - if (authorities instanceof Collection) { - return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils - .collectionToCommaDelimitedString((Collection) authorities)); - } - throw new IllegalArgumentException("Authorities must be either a String or a Collection"); - } -} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/exception/CustomOAuth2AuthenticationException.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/exception/CustomOAuth2AuthenticationException.java new file mode 100644 index 00000000..585ecc53 --- /dev/null +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/exception/CustomOAuth2AuthenticationException.java @@ -0,0 +1,17 @@ +package com.central.oauth2.common.exception; + +import org.springframework.security.oauth2.core.OAuth2AuthenticationException; +import org.springframework.security.oauth2.core.OAuth2Error; + +/** + * @author: zlt + * @date: 2023/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-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/CustomBearerTokenExtractor.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/CustomBearerTokenExtractor.java deleted file mode 100644 index 1346be29..00000000 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/CustomBearerTokenExtractor.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.central.oauth2.common.service.impl; - -import com.central.oauth2.common.properties.SecurityProperties; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.security.core.Authentication; -import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor; -import org.springframework.stereotype.Component; -import org.springframework.util.AntPathMatcher; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; - -/** - * 自定义 TokenExtractor - * - * @author zlt - * @version 1.0 - * @date 2022/6/4 - *

- * Blog: http://zlt2000.gitee.io - * Github: https://github.com/zlt2000 - */ -@ConditionalOnClass(HttpServletRequest.class) -@Component -public class CustomBearerTokenExtractor extends BearerTokenExtractor { - @Resource - private SecurityProperties securityProperties; - - private final AntPathMatcher antPathMatcher = new AntPathMatcher(); - - /** - * 解决只要请求携带access_token,排除鉴权的url依然会被拦截 - */ - @Override - public Authentication extract(HttpServletRequest request) { - //判断当前请求为排除鉴权的url时,直接返回null - for (String url : securityProperties.getIgnore().getUrls()) { - if (antPathMatcher.match(url, request.getRequestURI())) { - return null; - } - } - return super.extract(request); - } -} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/CustomBearerTokenResolver.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/CustomBearerTokenResolver.java new file mode 100644 index 00000000..833d1ca2 --- /dev/null +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/CustomBearerTokenResolver.java @@ -0,0 +1,112 @@ +package com.central.oauth2.common.service.impl; + +import com.central.oauth2.common.properties.PermitProperties; +import com.central.oauth2.common.properties.SecurityProperties; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.security.oauth2.core.OAuth2AuthenticationException; +import org.springframework.security.oauth2.server.resource.BearerTokenError; +import org.springframework.security.oauth2.server.resource.BearerTokenErrors; +import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver; +import org.springframework.stereotype.Component; +import org.springframework.util.AntPathMatcher; +import org.springframework.util.PathMatcher; +import org.springframework.util.StringUtils; + +import java.util.Arrays; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @author: zlt + * @date: 2023/11/8 + *

+ * Blog: http://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +@ConditionalOnClass(HttpServletRequest.class) +@Component +public class CustomBearerTokenResolver implements BearerTokenResolver { + private static final Pattern authorizationPattern = Pattern.compile("^Bearer (?[a-zA-Z0-9-:._~+/]+=*)$", + Pattern.CASE_INSENSITIVE); + + private final boolean allowFormEncodedBodyParameter = false; + + private final boolean allowUriQueryParameter = true; + + private final String bearerTokenHeaderName = HttpHeaders.AUTHORIZATION; + + private final PathMatcher pathMatcher = new AntPathMatcher(); + + private final PermitProperties permitProperties; + + public CustomBearerTokenResolver(SecurityProperties securityProperties) { + this.permitProperties = securityProperties.getIgnore(); + } + + @Override + public String resolve(HttpServletRequest request) { + boolean match = Arrays.stream(permitProperties.getUrls()) + .anyMatch(url -> pathMatcher.match(url, request.getRequestURI())); + + if (match) { + return null; + } + + final String authorizationHeaderToken = resolveFromAuthorizationHeader(request); + final String parameterToken = isParameterTokenSupportedForRequest(request) + ? resolveFromRequestParameters(request) : null; + if (authorizationHeaderToken != null) { + if (parameterToken != null) { + final BearerTokenError error = BearerTokenErrors + .invalidRequest("Found multiple bearer tokens in the request"); + throw new OAuth2AuthenticationException(error); + } + return authorizationHeaderToken; + } + if (parameterToken != null && isParameterTokenEnabledForRequest(request)) { + return parameterToken; + } + return null; + } + + private String resolveFromAuthorizationHeader(HttpServletRequest request) { + String authorization = request.getHeader(this.bearerTokenHeaderName); + if (!StringUtils.startsWithIgnoreCase(authorization, "bearer")) { + return null; + } + Matcher matcher = authorizationPattern.matcher(authorization); + if (!matcher.matches()) { + BearerTokenError error = BearerTokenErrors.invalidToken("Bearer token is malformed"); + throw new OAuth2AuthenticationException(error); + } + return matcher.group("token"); + } + + private static String resolveFromRequestParameters(HttpServletRequest request) { + String[] values = request.getParameterValues("access_token"); + if (values == null || values.length == 0) { + return null; + } + if (values.length == 1) { + return values[0]; + } + BearerTokenError error = BearerTokenErrors.invalidRequest("Found multiple bearer tokens in the request"); + throw new OAuth2AuthenticationException(error); + } + + private boolean isParameterTokenSupportedForRequest(final HttpServletRequest request) { + return (("POST".equals(request.getMethod()) + && MediaType.APPLICATION_FORM_URLENCODED_VALUE.equals(request.getContentType())) + || "GET".equals(request.getMethod())); + } + + private boolean isParameterTokenEnabledForRequest(final HttpServletRequest request) { + return ((this.allowFormEncodedBodyParameter && "POST".equals(request.getMethod()) + && MediaType.APPLICATION_FORM_URLENCODED_VALUE.equals(request.getContentType())) + || (this.allowUriQueryParameter && "GET".equals(request.getMethod()))); + } + +} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/DefaultPermissionServiceImpl.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/DefaultPermissionServiceImpl.java deleted file mode 100644 index 1724a092..00000000 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/DefaultPermissionServiceImpl.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.central.oauth2.common.service.impl; - -import cn.hutool.core.collection.CollectionUtil; -import cn.hutool.core.util.StrUtil; -import com.central.common.constant.CommonConstant; -import com.central.common.context.TenantContextHolder; -import com.central.common.model.SysMenu; -import com.central.oauth2.common.properties.SecurityProperties; -import com.central.oauth2.common.util.AuthUtils; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpMethod; -import org.springframework.security.authentication.AnonymousAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.oauth2.provider.OAuth2Authentication; -import org.springframework.util.AntPathMatcher; - -import java.util.List; -import java.util.stream.Collectors; - -/** - * 请求权限判断service - * - * @author zlt - * @date 2018/10/28 - *

- * Blog: http://zlt2000.gitee.io - * Github: https://github.com/zlt2000 - */ -@Slf4j -public abstract class DefaultPermissionServiceImpl { - - @Autowired - private SecurityProperties securityProperties; - - private final AntPathMatcher antPathMatcher = new AntPathMatcher(); - - /** - * 查询当前用户拥有的资源权限 - * @param roleCodes 角色code列表,多个以','隔开 - * @return - */ - public abstract List findMenuByRoleCodes(String roleCodes); - - public boolean hasPermission(Authentication authentication, String requestMethod, String requestURI) { - // 前端跨域OPTIONS请求预检放行 也可通过前端配置代理实现 - if (HttpMethod.OPTIONS.name().equalsIgnoreCase(requestMethod)) { - return true; - } - if (!(authentication instanceof AnonymousAuthenticationToken)) { - //判断是否开启url权限验证 - if (!securityProperties.getAuth().getUrlPermission().getEnable()) { - return true; - } - //超级管理员admin不需认证 - String username = AuthUtils.getUsername(authentication); - if (CommonConstant.ADMIN_USER_NAME.equals(username)) { - return true; - } - - OAuth2Authentication auth2Authentication = (OAuth2Authentication)authentication; - //判断应用黑白名单 - if (!isNeedAuth(auth2Authentication.getOAuth2Request().getClientId())) { - return true; - } - - //判断不进行url权限认证的api,所有已登录用户都能访问的url - for (String path : securityProperties.getAuth().getUrlPermission().getIgnoreUrls()) { - if (antPathMatcher.match(path, requestURI)) { - return true; - } - } - - List grantedAuthorityList = (List) authentication.getAuthorities(); - if (CollectionUtil.isEmpty(grantedAuthorityList)) { - log.warn("角色列表为空:{}", authentication.getPrincipal()); - return false; - } - - //保存租户信息 - String clientId = auth2Authentication.getOAuth2Request().getClientId(); - TenantContextHolder.setTenant(clientId); - - String roleCodes = grantedAuthorityList.stream().map(SimpleGrantedAuthority::getAuthority).collect(Collectors.joining(", ")); - List menuList = findMenuByRoleCodes(roleCodes); - for (SysMenu menu : menuList) { - if (StringUtils.isNotEmpty(menu.getUrl()) && antPathMatcher.match(menu.getUrl(), requestURI)) { - if (StrUtil.isNotEmpty(menu.getPathMethod())) { - return requestMethod.equalsIgnoreCase(menu.getPathMethod()); - } else { - return true; - } - } - } - } - - return false; - } - - /** - * 判断应用是否满足白名单和黑名单的过滤逻辑 - * @param clientId 应用id - * @return true(需要认证),false(不需要认证) - */ - private boolean isNeedAuth(String clientId) { - boolean result = true; - //白名单 - List includeClientIds = securityProperties.getAuth().getUrlPermission().getIncludeClientIds(); - //黑名单 - List exclusiveClientIds = securityProperties.getAuth().getUrlPermission().getExclusiveClientIds(); - if (includeClientIds.size() > 0) { - result = includeClientIds.contains(clientId); - } else if(exclusiveClientIds.size() > 0) { - result = !exclusiveClientIds.contains(clientId); - } - return result; - } -} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthDbTokenStore.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthDbTokenStore.java deleted file mode 100644 index 1d0b1ec9..00000000 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthDbTokenStore.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.central.oauth2.common.store; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; - -import javax.sql.DataSource; - -/** - * 认证服务器使用数据库存取令牌 - * - * @author zlt - * @date 2018/7/24 16:23 - */ -@Configuration -@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "db") -public class AuthDbTokenStore { - @Autowired - private DataSource dataSource; - - @Bean - public TokenStore tokenStore(){ - return new JdbcTokenStore(dataSource); - } -} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthJwtTokenStore.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthJwtTokenStore.java deleted file mode 100644 index a61a90f7..00000000 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthJwtTokenStore.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.central.oauth2.common.store; - -import com.central.common.model.SysUser; -import com.central.oauth2.common.converter.CustomUserAuthenticationConverter; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.bootstrap.encrypt.KeyProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.annotation.Order; -import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; -import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter; -import org.springframework.security.oauth2.provider.token.TokenEnhancer; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; -import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; -import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory; - -import javax.annotation.Resource; -import java.security.KeyPair; -import java.util.HashMap; -import java.util.Map; - -/** - * 认证服务器使用 JWT RSA 非对称加密令牌 - * - * @author zlt - * @date 2018/7/24 16:21 - *

- * Blog: http://zlt2000.gitee.io - * Github: https://github.com/zlt2000 - */ -@Configuration -@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "authJwt") -public class AuthJwtTokenStore { - @Resource - private KeyProperties keyProperties; - - @Bean - public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) { - return new JwtTokenStore(jwtAccessTokenConverter); - } - - @Bean - @Order(2) - public JwtAccessTokenConverter jwtAccessTokenConverter() { - final JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); - KeyPair keyPair = new KeyStoreKeyFactory - (keyProperties.getKeyStore().getLocation(), keyProperties.getKeyStore().getSecret().toCharArray()) - .getKeyPair(keyProperties.getKeyStore().getAlias()); - converter.setKeyPair(keyPair); - DefaultAccessTokenConverter tokenConverter = (DefaultAccessTokenConverter)converter.getAccessTokenConverter(); - tokenConverter.setUserTokenConverter(new CustomUserAuthenticationConverter()); - return converter; - } -} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthRedisTokenStore.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthRedisTokenStore.java deleted file mode 100644 index 124df21f..00000000 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthRedisTokenStore.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.central.oauth2.common.store; - -import com.central.oauth2.common.properties.SecurityProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.serializer.RedisSerializer; -import org.springframework.security.oauth2.provider.token.TokenStore; - -/** - * 认证服务器使用Redis存取令牌 - * 注意: 需要配置redis参数 - * - * @author zlt - * @date 2018/7/25 9:36 - *

- * Blog: http://zlt2000.gitee.io - * Github: https://github.com/zlt2000 - */ -@Configuration -@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "redis", matchIfMissing = true) -public class AuthRedisTokenStore { - @Bean - public TokenStore tokenStore(RedisConnectionFactory connectionFactory, SecurityProperties securityProperties, RedisSerializer redisValueSerializer) { - return new CustomRedisTokenStore(connectionFactory, securityProperties, redisValueSerializer); - } -} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/CustomRedisTokenStore.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/CustomRedisTokenStore.java deleted file mode 100644 index f07ddb0d..00000000 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/CustomRedisTokenStore.java +++ /dev/null @@ -1,543 +0,0 @@ -package com.central.oauth2.common.store; - -import com.central.common.constant.SecurityConstants; -import com.central.oauth2.common.properties.SecurityProperties; -import org.springframework.data.redis.connection.RedisConnection; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.serializer.RedisSerializer; -import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; -import org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken; -import org.springframework.security.oauth2.common.OAuth2AccessToken; -import org.springframework.security.oauth2.common.OAuth2RefreshToken; -import org.springframework.security.oauth2.provider.ClientDetails; -import org.springframework.security.oauth2.provider.OAuth2Authentication; -import org.springframework.security.oauth2.provider.OAuth2Request; -import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator; -import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.oauth2.provider.token.store.redis.JdkSerializationStrategy; -import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore; -import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStoreSerializationStrategy; -import org.springframework.util.ClassUtils; -import org.springframework.util.ReflectionUtils; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -/** - * 优化自Spring Security的RedisTokenStore - * 1. 支持redis所有集群模式包括cluster模式 - * 2. 使用pipeline减少连接次数,提升性能 - * 3. 自动续签token(可配置是否开启) - * - * @author zlt - * @date 2019/7/7 - */ -public class CustomRedisTokenStore implements TokenStore { - private static final String ACCESS = "access:"; - private static final String ACCESS_BAK = "access_bak:"; - private static final String AUTH_TO_ACCESS = "auth_to_access:"; - private static final String REFRESH_AUTH = "refresh_auth:"; - private static final String ACCESS_TO_REFRESH = "access_to_refresh:"; - private static final String REFRESH = "refresh:"; - private static final String REFRESH_TO_ACCESS = "refresh_to_access:"; - - private static final boolean springDataRedis_2_0 = ClassUtils.isPresent( - "org.springframework.data.redis.connection.RedisStandaloneConfiguration", - RedisTokenStore.class.getClassLoader()); - - private final RedisConnectionFactory connectionFactory; - private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator(); - private RedisTokenStoreSerializationStrategy serializationStrategy = new JdkSerializationStrategy(); - - private String prefix = ""; - - private Method redisConnectionSet_2_0; - - /** - * 认证配置 - */ - private SecurityProperties securityProperties; - - /** - * 业务redis的value序列化 - */ - private RedisSerializer redisValueSerializer; - - public CustomRedisTokenStore(RedisConnectionFactory connectionFactory, SecurityProperties securityProperties, RedisSerializer redisValueSerializer) { - this.connectionFactory = connectionFactory; - this.securityProperties = securityProperties; - this.redisValueSerializer = redisValueSerializer; - if (springDataRedis_2_0) { - this.loadRedisConnectionMethods_2_0(); - } - } - - public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) { - this.authenticationKeyGenerator = authenticationKeyGenerator; - } - - public void setSerializationStrategy(RedisTokenStoreSerializationStrategy serializationStrategy) { - this.serializationStrategy = serializationStrategy; - } - - public void setPrefix(String prefix) { - this.prefix = prefix; - } - - private void loadRedisConnectionMethods_2_0() { - this.redisConnectionSet_2_0 = ReflectionUtils.findMethod( - RedisConnection.class, "set", byte[].class, byte[].class); - } - - private RedisConnection getConnection() { - return connectionFactory.getConnection(); - } - - private byte[] serialize(Object object) { - return serializationStrategy.serialize(object); - } - - private byte[] serializeKey(String object) { - return serialize(prefix + object); - } - - private OAuth2AccessToken deserializeAccessToken(byte[] bytes) { - return serializationStrategy.deserialize(bytes, OAuth2AccessToken.class); - } - - private OAuth2Authentication deserializeAuthentication(byte[] bytes) { - return serializationStrategy.deserialize(bytes, OAuth2Authentication.class); - } - - private OAuth2RefreshToken deserializeRefreshToken(byte[] bytes) { - return serializationStrategy.deserialize(bytes, OAuth2RefreshToken.class); - } - - private ClientDetails deserializeClientDetails(byte[] bytes) { - return (ClientDetails) redisValueSerializer.deserialize(bytes); - } - - private byte[] serialize(String string) { - return serializationStrategy.serialize(string); - } - - private String deserializeString(byte[] bytes) { - return serializationStrategy.deserializeString(bytes); - } - - @Override - public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) { - String key = authenticationKeyGenerator.extractKey(authentication); - byte[] serializedKey = serializeKey(AUTH_TO_ACCESS + key); - byte[] bytes; - RedisConnection conn = getConnection(); - try { - bytes = conn.get(serializedKey); - } finally { - conn.close(); - } - OAuth2AccessToken accessToken = deserializeAccessToken(bytes); - if (accessToken != null) { - OAuth2Authentication storedAuthentication = readAuthentication(accessToken.getValue()); - if ((storedAuthentication == null || !key.equals(authenticationKeyGenerator.extractKey(storedAuthentication)))) { - // Keep the stores consistent (maybe the same user is - // represented by this authentication but the details have - // changed) - storeAccessToken(accessToken, authentication); - } - - } - return accessToken; - } - - @Override - public OAuth2Authentication readAuthentication(OAuth2AccessToken token) { - OAuth2Authentication auth2Authentication = readAuthentication(token.getValue()); - //是否开启token续签 - boolean isRenew = securityProperties.getAuth().getRenew().getEnable(); - if (isRenew && auth2Authentication != null) { - OAuth2Request clientAuth = auth2Authentication.getOAuth2Request(); - //判断当前应用是否需要自动续签 - if (checkRenewClientId(clientAuth.getClientId())) { - //获取过期时长 - int validitySeconds = getAccessTokenValiditySeconds(clientAuth.getClientId()); - if (validitySeconds > 0) { - double expiresRatio = token.getExpiresIn() / (double) validitySeconds; - //判断是否需要续签,当前剩余时间小于过期时长的50%则续签 - if (expiresRatio <= securityProperties.getAuth().getRenew().getTimeRatio()) { - //更新AccessToken过期时间 - DefaultOAuth2AccessToken oAuth2AccessToken = (DefaultOAuth2AccessToken) token; - oAuth2AccessToken.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L))); - storeAccessToken(oAuth2AccessToken, auth2Authentication, true); - } - } - } - } - return auth2Authentication; - } - - /** - * 判断应用自动续签是否满足白名单和黑名单的过滤逻辑 - * - * @param clientId 应用id - * @return 是否满足 - */ - private boolean checkRenewClientId(String clientId) { - boolean result = true; - //白名单 - List includeClientIds = securityProperties.getAuth().getRenew().getIncludeClientIds(); - //黑名单 - List exclusiveClientIds = securityProperties.getAuth().getRenew().getExclusiveClientIds(); - if (includeClientIds.size() > 0) { - result = includeClientIds.contains(clientId); - } else if (exclusiveClientIds.size() > 0) { - result = !exclusiveClientIds.contains(clientId); - } - return result; - } - - /** - * 获取token的总有效时长 - * - * @param clientId 应用id - */ - private int getAccessTokenValiditySeconds(String clientId) { - RedisConnection conn = getConnection(); - byte[] bytes; - try { - bytes = conn.get(serializeKey(SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId)); - } finally { - conn.close(); - } - if (bytes != null) { - ClientDetails clientDetails = deserializeClientDetails(bytes); - if (clientDetails.getAccessTokenValiditySeconds() != null) { - return clientDetails.getAccessTokenValiditySeconds(); - } - } - - //返回默认值 - return SecurityConstants.ACCESS_TOKEN_VALIDITY_SECONDS; - } - - @Override - public OAuth2Authentication readAuthentication(String token) { - byte[] bytes; - RedisConnection conn = getConnection(); - try { - bytes = conn.get(serializeKey(SecurityConstants.REDIS_TOKEN_AUTH + token)); - } finally { - conn.close(); - } - return deserializeAuthentication(bytes); - } - - @Override - public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) { - return readAuthenticationForRefreshToken(token.getValue()); - } - - public OAuth2Authentication readAuthenticationForRefreshToken(String token) { - RedisConnection conn = getConnection(); - try { - byte[] bytes = conn.get(serializeKey(REFRESH_AUTH + token)); - return deserializeAuthentication(bytes); - } finally { - conn.close(); - } - } - - @Override - public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { - storeAccessToken(token, authentication, false); - } - - /** - * 存储token - * - * @param isRenew 是否续签 - */ - private void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication, boolean isRenew) { - byte[] serializedAccessToken = serialize(token); - byte[] serializedAuth = serialize(authentication); - byte[] accessKey = serializeKey(ACCESS + token.getValue()); - byte[] accessBakKey = serializeKey(ACCESS_BAK + token.getValue()); - byte[] authKey = serializeKey(SecurityConstants.REDIS_TOKEN_AUTH + token.getValue()); - byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication)); - byte[] approvalKey = serializeKey(SecurityConstants.REDIS_UNAME_TO_ACCESS + getApprovalKey(authentication)); - byte[] clientId = serializeKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId()); - - RedisConnection conn = getConnection(); - try { - byte[] oldAccessToken = conn.get(accessKey); - //如果token已存在,并且不是续签的话直接返回 - if (!isRenew && oldAccessToken != null) { - return; - } - - conn.openPipeline(); - if (springDataRedis_2_0) { - try { - this.redisConnectionSet_2_0.invoke(conn, accessKey, serializedAccessToken); - this.redisConnectionSet_2_0.invoke(conn, accessBakKey, serializedAccessToken); - this.redisConnectionSet_2_0.invoke(conn, authKey, serializedAuth); - this.redisConnectionSet_2_0.invoke(conn, authToAccessKey, serializedAccessToken); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } else { - conn.set(accessKey, serializedAccessToken); - conn.set(accessBakKey, serializedAccessToken); - conn.set(authKey, serializedAuth); - conn.set(authToAccessKey, serializedAccessToken); - } - //如果是续签token,需要先删除集合里旧的值 - if (oldAccessToken != null) { - if (!authentication.isClientOnly()) { - conn.lRem(approvalKey, 1, oldAccessToken); - } - conn.lRem(clientId, 1, oldAccessToken); - } - if (!authentication.isClientOnly()) { - conn.rPush(approvalKey, serializedAccessToken); - } - conn.rPush(clientId, serializedAccessToken); - if (token.getExpiration() != null) { - int seconds = token.getExpiresIn(); - conn.expire(accessKey, seconds); - conn.expire(accessBakKey, seconds + 60); - conn.expire(authKey, seconds); - conn.expire(authToAccessKey, seconds); - conn.expire(clientId, seconds); - conn.expire(approvalKey, seconds); - } - OAuth2RefreshToken refreshToken = token.getRefreshToken(); - if (refreshToken != null && refreshToken.getValue() != null) { - byte[] refresh = serialize(token.getRefreshToken().getValue()); - byte[] auth = serialize(token.getValue()); - byte[] refreshToAccessKey = serializeKey(REFRESH_TO_ACCESS + token.getRefreshToken().getValue()); - byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + token.getValue()); - if (springDataRedis_2_0) { - try { - this.redisConnectionSet_2_0.invoke(conn, refreshToAccessKey, auth); - this.redisConnectionSet_2_0.invoke(conn, accessToRefreshKey, refresh); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } else { - conn.set(refreshToAccessKey, auth); - conn.set(accessToRefreshKey, refresh); - } - expireRefreshToken(refreshToken, conn, refreshToAccessKey, accessToRefreshKey); - } - conn.closePipeline(); - } finally { - conn.close(); - } - } - - private static String getApprovalKey(OAuth2Authentication authentication) { - String userName = authentication.getUserAuthentication() == null ? "" - : authentication.getUserAuthentication().getName(); - return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName); - } - - private static String getApprovalKey(String clientId, String userName) { - return clientId + (userName == null ? "" : ":" + userName); - } - - @Override - public void removeAccessToken(OAuth2AccessToken accessToken) { - removeAccessToken(accessToken.getValue()); - } - - @Override - public OAuth2AccessToken readAccessToken(String tokenValue) { - byte[] key = serializeKey(ACCESS + tokenValue); - byte[] bytes; - RedisConnection conn = getConnection(); - try { - bytes = conn.get(key); - } finally { - conn.close(); - } - return deserializeAccessToken(bytes); - } - - public void removeAccessToken(String tokenValue) { - byte[] accessKey = serializeKey(ACCESS + tokenValue); - byte[] accessBakKey = serializeKey(ACCESS_BAK + tokenValue); - byte[] authKey = serializeKey(SecurityConstants.REDIS_TOKEN_AUTH + tokenValue); - byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue); - RedisConnection conn = getConnection(); - try { - byte[] access = conn.get(accessKey); - byte[] auth = conn.get(authKey); - conn.openPipeline(); - conn.del(accessKey); - conn.del(accessBakKey); - conn.del(accessToRefreshKey); - // Don't remove the refresh token - it's up to the caller to do that - conn.del(authKey); - conn.closePipeline(); - - OAuth2Authentication authentication = deserializeAuthentication(auth); - if (authentication != null) { - String key = authenticationKeyGenerator.extractKey(authentication); - byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + key); - byte[] unameKey = serializeKey(SecurityConstants.REDIS_UNAME_TO_ACCESS + getApprovalKey(authentication)); - byte[] clientId = serializeKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId()); - conn.openPipeline(); - conn.del(authToAccessKey); - conn.lRem(unameKey, 1, access); - conn.lRem(clientId, 1, access); - conn.del(serialize(ACCESS + key)); - conn.closePipeline(); - } - } finally { - conn.close(); - } - } - - @Override - public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) { - byte[] refreshKey = serializeKey(REFRESH + refreshToken.getValue()); - byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + refreshToken.getValue()); - byte[] serializedRefreshToken = serialize(refreshToken); - RedisConnection conn = getConnection(); - try { - conn.openPipeline(); - if (springDataRedis_2_0) { - try { - this.redisConnectionSet_2_0.invoke(conn, refreshKey, serializedRefreshToken); - this.redisConnectionSet_2_0.invoke(conn, refreshAuthKey, serialize(authentication)); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } else { - conn.set(refreshKey, serializedRefreshToken); - conn.set(refreshAuthKey, serialize(authentication)); - } - expireRefreshToken(refreshToken, conn, refreshKey, refreshAuthKey); - conn.closePipeline(); - } finally { - conn.close(); - } - } - - private void expireRefreshToken(OAuth2RefreshToken refreshToken, RedisConnection conn, byte[] refreshKey, byte[] refreshAuthKey) { - if (refreshToken instanceof ExpiringOAuth2RefreshToken) { - ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken; - Date expiration = expiringRefreshToken.getExpiration(); - if (expiration != null) { - int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L) - .intValue(); - conn.expire(refreshKey, seconds); - conn.expire(refreshAuthKey, seconds); - } - } - } - - @Override - public OAuth2RefreshToken readRefreshToken(String tokenValue) { - byte[] key = serializeKey(REFRESH + tokenValue); - byte[] bytes; - RedisConnection conn = getConnection(); - try { - bytes = conn.get(key); - } finally { - conn.close(); - } - return deserializeRefreshToken(bytes); - } - - @Override - public void removeRefreshToken(OAuth2RefreshToken refreshToken) { - removeRefreshToken(refreshToken.getValue()); - } - - public void removeRefreshToken(String tokenValue) { - byte[] refreshKey = serializeKey(REFRESH + tokenValue); - byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + tokenValue); - byte[] refresh2AccessKey = serializeKey(REFRESH_TO_ACCESS + tokenValue); - byte[] access2RefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue); - RedisConnection conn = getConnection(); - try { - conn.openPipeline(); - conn.del(refreshKey); - conn.del(refreshAuthKey); - conn.del(refresh2AccessKey); - conn.del(access2RefreshKey); - conn.closePipeline(); - } finally { - conn.close(); - } - } - - @Override - public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) { - removeAccessTokenUsingRefreshToken(refreshToken.getValue()); - } - - private void removeAccessTokenUsingRefreshToken(String refreshToken) { - byte[] key = serializeKey(REFRESH_TO_ACCESS + refreshToken); - RedisConnection conn = getConnection(); - byte[] bytes = null; - try { - bytes = conn.get(key); - conn.del(key); - } finally { - conn.close(); - } - if (bytes == null) { - return; - } - String accessToken = deserializeString(bytes); - if (accessToken != null) { - removeAccessToken(accessToken); - } - } - - @Override - public Collection findTokensByClientIdAndUserName(String clientId, String userName) { - byte[] approvalKey = serializeKey(SecurityConstants.REDIS_UNAME_TO_ACCESS + getApprovalKey(clientId, userName)); - List byteList; - RedisConnection conn = getConnection(); - try { - byteList = conn.lRange(approvalKey, 0, -1); - } finally { - conn.close(); - } - return getTokenCollections(byteList); - } - - @Override - public Collection findTokensByClientId(String clientId) { - byte[] key = serializeKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + clientId); - List byteList; - RedisConnection conn = getConnection(); - try { - byteList = conn.lRange(key, 0, -1); - } finally { - conn.close(); - } - return getTokenCollections(byteList); - } - - private Collection getTokenCollections(List byteList) { - if (byteList == null || byteList.size() == 0) { - return Collections.emptySet(); - } - List accessTokens = new ArrayList<>(byteList.size()); - for (byte[] bytes : byteList) { - OAuth2AccessToken accessToken = deserializeAccessToken(bytes); - accessTokens.add(accessToken); - } - return Collections.unmodifiableCollection(accessTokens); - } -} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/ResJwtTokenStore.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/ResJwtTokenStore.java deleted file mode 100644 index c7655696..00000000 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/ResJwtTokenStore.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.central.oauth2.common.store; - -import cn.hutool.core.util.StrUtil; -import com.central.common.constant.SecurityConstants; -import com.central.oauth2.common.converter.CustomUserAuthenticationConverter; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; -import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; -import org.springframework.web.client.RestTemplate; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.Base64; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * 资源服务器 TokenStore 配置类,使用 JWT RSA 非对称加密 - * - * @author zlt - * @date 2018/8/20 9:25 - */ -@Configuration -@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "resJwt") -public class ResJwtTokenStore { - @Autowired - private ResourceServerProperties resource; - - @Bean - public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) { - return new JwtTokenStore(jwtAccessTokenConverter); - } - - @Bean - public JwtAccessTokenConverter jwtAccessTokenConverter() { - JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); - converter.setVerifierKey(getPubKey()); - DefaultAccessTokenConverter tokenConverter = (DefaultAccessTokenConverter)converter.getAccessTokenConverter(); - tokenConverter.setUserTokenConverter(new CustomUserAuthenticationConverter()); - return converter; - } - - /** - * 获取非对称加密公钥 Key - * @return 公钥 Key - */ - private String getPubKey() { - Resource res = new ClassPathResource(SecurityConstants.RSA_PUBLIC_KEY); - try (BufferedReader br = new BufferedReader(new InputStreamReader(res.getInputStream()))) { - return br.lines().collect(Collectors.joining("\n")); - } catch (IOException ioe) { - return getKeyFromAuthorizationServer(); - } - } - - /** - * 通过访问授权服务器获取非对称加密公钥 Key - * @return 公钥 Key - */ - private String getKeyFromAuthorizationServer() { - if (StrUtil.isNotEmpty(this.resource.getJwt().getKeyUri())) { - final HttpHeaders headers = new HttpHeaders(); - final String username = this.resource.getClientId(); - final String password = this.resource.getClientSecret(); - if (username != null && password != null) { - final byte[] token = Base64.getEncoder().encode((username + ":" + password).getBytes()); - headers.add("Authorization", "Basic " + new String(token)); - } - final HttpEntity request = new HttpEntity<>(headers); - final String url = this.resource.getJwt().getKeyUri(); - return (String) new RestTemplate() - .exchange(url, HttpMethod.GET, request, Map.class).getBody() - .get("value"); - } - return null; - } -} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/BaseAuthenticationToken.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/BaseAuthenticationToken.java new file mode 100644 index 00000000..5c5b96fc --- /dev/null +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/BaseAuthenticationToken.java @@ -0,0 +1,66 @@ +package com.central.oauth2.common.token; + +import lombok.Getter; +import lombok.Setter; +import org.springframework.lang.Nullable; +import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.oauth2.core.AuthorizationGrantType; +import org.springframework.security.oauth2.server.authorization.util.SpringAuthorizationServerVersion; + +import java.io.Serial; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Set; + +/** + * @author: zlt + * @date: 2023/11/15 + *

+ * Blog: http://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +@Getter +@Setter +public class BaseAuthenticationToken extends AbstractAuthenticationToken { + @Serial + private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID; + private final AuthorizationGrantType grantType; + private Authentication clientPrincipal; + private Map additionalParameters; + private Set scopes; + + public BaseAuthenticationToken(AuthorizationGrantType authorizationGrantType) { + super(null); + this.grantType = authorizationGrantType; + } + + public BaseAuthenticationToken(AuthorizationGrantType authorizationGrantType, Set scopes + , Authentication clientPrincipal, @Nullable Map additionalParameters) { + super(null); + this.grantType = authorizationGrantType; + this.scopes = Collections.unmodifiableSet(scopes != null ? scopes : Collections.emptySet()); + this.clientPrincipal = clientPrincipal; + this.additionalParameters = additionalParameters; + } + + public BaseAuthenticationToken(Collection authorities) { + super(authorities); + this.grantType = null; + this.clientPrincipal = null; + this.additionalParameters = null; + this.scopes = null; + } + + @Override + public Object getPrincipal() { + return this.clientPrincipal; + } + + @Override + public Object getCredentials() { + return ""; + } +} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/CustomAccessToken.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/CustomAccessToken.java new file mode 100644 index 00000000..0c53f6b2 --- /dev/null +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/CustomAccessToken.java @@ -0,0 +1,19 @@ +package com.central.oauth2.common.token; + +import org.springframework.security.oauth2.core.OAuth2AccessToken; +import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; + +import java.util.Map; + +/** + * @author: zlt + * @date: 2023/11/20 + *

+ * Blog: https://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +public class CustomAccessToken extends OAuth2Authorization.Token { + protected CustomAccessToken(OAuth2AccessToken token, Map metadata) { + super(token, metadata); + } +} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java index df836dd2..4ef3d8a1 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java @@ -1,22 +1,24 @@ package com.central.oauth2.common.util; +import cn.hutool.extra.spring.SpringUtil; import com.central.common.constant.CommonConstant; import com.central.common.constant.SecurityConstants; import com.central.common.context.LoginUserContextHolder; import com.central.common.model.SysUser; -import com.central.common.utils.SpringUtil; -import com.central.oauth2.common.token.CustomWebAuthenticationDetails; +import com.central.oauth2.common.exception.CustomOAuth2AuthenticationException; +import com.central.oauth2.common.token.BaseAuthenticationToken; import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.oauth2.common.OAuth2AccessToken; -import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; -import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException; -import org.springframework.security.oauth2.provider.OAuth2Authentication; -import org.springframework.security.oauth2.provider.token.TokenStore; +import org.springframework.security.oauth2.core.OAuth2AccessToken; +import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import jakarta.servlet.http.HttpServletRequest; +import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; +import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; +import org.springframework.security.oauth2.server.authorization.OAuth2TokenType; + import java.nio.charset.StandardCharsets; import java.util.*; @@ -45,7 +47,7 @@ public class AuthUtils { public static String extractToken(HttpServletRequest request) { String token = extractHeaderToken(request); if (token == null) { - token = request.getParameter(OAuth2AccessToken.ACCESS_TOKEN); + token = request.getParameter(OAuth2ParameterNames.ACCESS_TOKEN); if (token == null) { log.debug("Token not found in request parameters. Not an OAuth2 request."); } @@ -62,8 +64,8 @@ public class AuthUtils { Enumeration headers = request.getHeaders(CommonConstant.TOKEN_HEADER); while (headers.hasMoreElements()) { String value = headers.nextElement(); - if ((value.startsWith(OAuth2AccessToken.BEARER_TYPE))) { - String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim(); + if ((value.startsWith(OAuth2AccessToken.TokenType.BEARER.getValue()))) { + String authHeaderValue = value.substring(OAuth2AccessToken.TokenType.BEARER.getValue().length()).trim(); int commaIndex = authHeaderValue.indexOf(','); if (commaIndex > 0) { authHeaderValue = authHeaderValue.substring(0, commaIndex); @@ -83,19 +85,20 @@ public class AuthUtils { } public static SysUser checkAccessToken(String accessTokenValue) { - TokenStore tokenStore = SpringUtil.getBean(TokenStore.class); - OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue); - if (accessToken == null || accessToken.getValue() == null) { - throw new InvalidTokenException("Invalid access token: " + accessTokenValue); - } else if (accessToken.isExpired()) { - tokenStore.removeAccessToken(accessToken); - throw new InvalidTokenException("Access token expired: " + accessTokenValue); + OAuth2AuthorizationService tokenService = SpringUtil.getBean(OAuth2AuthorizationService.class); + OAuth2Authorization oAuth2Authorization = tokenService.findByToken(accessTokenValue, OAuth2TokenType.ACCESS_TOKEN); + if (oAuth2Authorization == null || oAuth2Authorization.getAccessToken() == null) { + throw new CustomOAuth2AuthenticationException("Invalid access token: " + accessTokenValue); + } else if (oAuth2Authorization.getAccessToken().isExpired()) { + tokenService.remove(oAuth2Authorization); + throw new CustomOAuth2AuthenticationException("Access token expired: " + accessTokenValue); } - OAuth2Authentication result = tokenStore.readAuthentication(accessToken); + /*OAuth2Authentication result = tokenStore.readAuthentication(accessToken); if (result == null) { - throw new InvalidTokenException("Invalid access token: " + accessTokenValue); - } - return setContext(result); + throw new OAuth2AuthenticationException("Invalid access token: " + accessTokenValue); + }*/ + // TODO 如何生成 Authentication 对象 + return setContext(null); } /** @@ -114,11 +117,20 @@ public class AuthUtils { public static String[] extractClient(HttpServletRequest request) { String header = request.getHeader("Authorization"); if (header == null || !header.startsWith(BASIC_)) { - throw new UnapprovedClientAuthenticationException("请求头中client信息为空"); + throw new CustomOAuth2AuthenticationException("The client information in the request header is empty"); } return extractHeaderClient(header); } + public static String extractClientId(HttpServletRequest request) { + String header = request.getHeader("Authorization"); + if (header == null || !header.startsWith(BASIC_)) { + throw new CustomOAuth2AuthenticationException("The client information in the request header is empty"); + } + String[] clientArr = extractHeaderClient(header); + return clientArr[0]; + } + /** * 从header 请求中的clientId:clientSecret * @@ -130,7 +142,7 @@ public class AuthUtils { String clientStr = new String(decoded, StandardCharsets.UTF_8); String[] clientArr = clientStr.split(":"); if (clientArr.length != 2) { - throw new RuntimeException("Invalid basic authentication token"); + throw new CustomOAuth2AuthenticationException("Invalid basic authentication token"); } return clientArr; } @@ -170,17 +182,8 @@ public class AuthUtils { public static String getAccountType(Authentication authentication) { String accountType = null; if (authentication != null) { - Object details = authentication.getDetails(); - if (details != null) { - if (details instanceof CustomWebAuthenticationDetails) { - CustomWebAuthenticationDetails detailsObj = (CustomWebAuthenticationDetails) details; - accountType = detailsObj.getAccountType(); - } else { - Map detailsMap = (Map) details; - if (detailsMap != null) { - accountType = detailsMap.get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME); - } - } + if (authentication instanceof BaseAuthenticationToken authenticationToken) { + accountType = (String)authenticationToken.getAdditionalParameters().get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME); } } return accountType; diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/JwtUtils.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/JwtUtils.java deleted file mode 100644 index e5627405..00000000 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/JwtUtils.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.central.oauth2.common.util; - -import com.central.common.constant.SecurityConstants; -import com.central.common.utils.JsonUtil; -import com.central.common.utils.RsaUtils; -import com.fasterxml.jackson.databind.JsonNode; -import org.springframework.cloud.bootstrap.encrypt.KeyProperties; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.security.jwt.Jwt; -import org.springframework.security.jwt.JwtHelper; -import org.springframework.security.jwt.crypto.sign.RsaSigner; -import org.springframework.security.jwt.crypto.sign.RsaVerifier; -import org.springframework.security.jwt.crypto.sign.SignatureVerifier; -import org.springframework.security.jwt.crypto.sign.Signer; -import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.security.KeyPair; -import java.security.PrivateKey; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.util.stream.Collectors; - -/** - * jwt工具类 - * - * @author zlt - * @date 2019/7/21 - */ -public class JwtUtils { - private static final String PUBKEY_START = "-----BEGIN PUBLIC KEY-----"; - private static final String PUBKEY_END = "-----END PUBLIC KEY-----"; - - /** - * 通过classpath获取公钥值 - */ - public static RSAPublicKey getPubKeyObj() { - Resource res = new ClassPathResource(SecurityConstants.RSA_PUBLIC_KEY); - try (BufferedReader br = new BufferedReader(new InputStreamReader(res.getInputStream()))) { - String pubKey = br.lines().collect(Collectors.joining("\n")); - pubKey = pubKey.substring(PUBKEY_START.length(), pubKey.indexOf(PUBKEY_END)); - return RsaUtils.getPublicKey(pubKey); - } catch (Exception ioe) { - ioe.printStackTrace(); - } - return null; - } - - /** - * {"exp":1563256084,"user_name":"admin","authorities":["ADMIN"],"jti":"4ce02f54-3d1c-4461-8af1-73f0841a35df","client_id":"webApp","scope":["app"]} - * @param jwtToken token值 - * @param rsaPublicKey 公钥 - * @return - */ - public static JsonNode decodeAndVerify(String jwtToken, RSAPublicKey rsaPublicKey) { - SignatureVerifier rsaVerifier = new RsaVerifier(rsaPublicKey); - Jwt jwt = JwtHelper.decodeAndVerify(jwtToken, rsaVerifier); - return JsonUtil.parse(jwt.getClaims()); - } - - /** - * {"exp":1563256084,"user_name":"admin","authorities":["ADMIN"],"jti":"4ce02f54-3d1c-4461-8af1-73f0841a35df","client_id":"webApp","scope":["app"]} - * @param jwtToken token值 - * @return - */ - public static JsonNode decodeAndVerify(String jwtToken) { - return decodeAndVerify(jwtToken, getPubKeyObj()); - } - - /** - * 判断jwt是否过期 - * @param claims jwt内容 - * @param currTime 当前时间 - * @return 未过期:true,已过期:false - */ - public static boolean checkExp(JsonNode claims, long currTime) { - long exp = claims.get("exp").asLong(); - if (exp < currTime) { - return false; - } - return true; - } - - /** - * 判断jwt是否过期 - * @param claims jwt内容 - * @return 未过期:true,已过期:false - */ - public static boolean checkExp(JsonNode claims) { - return checkExp(claims, System.currentTimeMillis()); - } - - public static Jwt encode(CharSequence content, KeyProperties keyProperties) { - KeyPair keyPair = new KeyStoreKeyFactory( - keyProperties.getKeyStore().getLocation(), - keyProperties.getKeyStore().getSecret().toCharArray()) - .getKeyPair(keyProperties.getKeyStore().getAlias()); - PrivateKey privateKey = keyPair.getPrivate(); - Signer rsaSigner = new RsaSigner((RSAPrivateKey) privateKey); - return JwtHelper.encode(content, rsaSigner); - } - - public static String encodeStr(CharSequence content, KeyProperties keyProperties) { - return encode(content, keyProperties).getEncoded(); - } -} diff --git a/zlt-commons/zlt-common-core/pom.xml b/zlt-commons/zlt-common-core/pom.xml index 1f716668..746451ba 100644 --- a/zlt-commons/zlt-common-core/pom.xml +++ b/zlt-commons/zlt-common-core/pom.xml @@ -27,11 +27,6 @@ cn.hutool hutool-all - - javax.servlet - javax.servlet-api - true - com.fasterxml.jackson.core jackson-annotations diff --git a/zlt-commons/zlt-loadbalancer-spring-boot-starter/pom.xml b/zlt-commons/zlt-loadbalancer-spring-boot-starter/pom.xml index f0390a89..ae003e72 100644 --- a/zlt-commons/zlt-loadbalancer-spring-boot-starter/pom.xml +++ b/zlt-commons/zlt-loadbalancer-spring-boot-starter/pom.xml @@ -33,12 +33,6 @@ org.apache.httpcomponents.client5 httpclient5 - - javax.servlet - javax.servlet-api - true - - org.springframework.boot spring-boot-configuration-processor 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 e52f12cb..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: http://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 9bba37dc..00000000 --- a/zlt-commons/zlt-swagger2-spring-boot-starter/src/main/java/com/central/common/swagger2/SwaggerProperties.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.central.common.swagger2; - -import lombok.Data; -import lombok.Getter; -import lombok.Setter; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - -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") -@Component -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-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 1d1af95d..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资源服务器配置 @@ -14,7 +13,7 @@ import org.springframework.security.oauth2.config.annotation.web.configuration.E * Blog: http://zlt2000.gitee.io * Github: https://github.com/zlt2000 */ -@Configuration +/*@Configuration @EnableResourceServer public class MyResourceConfig extends DefaultResourceServerConf { -} +}*/ 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 99d1bd45..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 @@ -31,14 +31,14 @@ public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { - http.authorizeHttpRequests().anyRequest().authenticated() + /*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/websocket-demo/src/main/java/org/zlt/config/MyResourceConfig.java b/zlt-demo/websocket-demo/src/main/java/org/zlt/config/MyResourceConfig.java index 8c00d035..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资源服务器配置 @@ -14,7 +12,9 @@ import org.springframework.security.oauth2.config.annotation.web.configuration.E * Blog: http://zlt2000.gitee.io * Github: https://github.com/zlt2000 */ +/* @Configuration @EnableResourceServer public class MyResourceConfig extends DefaultResourceServerConf { } +*/ diff --git a/zlt-doc/sql/oauth-center.sql b/zlt-doc/sql/oauth-center.sql index 627de1d8..8211ce8f 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(10) 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', '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', '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..4085eef7 --- /dev/null +++ b/zlt-doc/版本升级_sql/旧版本升级v6.0.0.sql @@ -0,0 +1,5 @@ +------------更新语句 +Use `oauth-center`; +alter table oauth_client_details add token_format varchar(10) 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; \ No newline at end of file diff --git a/zlt-gateway/sc-gateway/pom.xml b/zlt-gateway/sc-gateway/pom.xml index 88c12ce5..a1300774 100644 --- a/zlt-gateway/sc-gateway/pom.xml +++ b/zlt-gateway/sc-gateway/pom.xml @@ -76,7 +76,6 @@ com.github.xiaoymin knife4j-gateway-spring-boot-starter - 4.2.0 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 d4263708..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: http://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 a74201d8..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: http://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 9223ede2..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: http://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 45627bad..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: http://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/Oauth2AuthSuccessHandler.java deleted file mode 100644 index 88576fac..00000000 --- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2AuthSuccessHandler.java +++ /dev/null @@ -1,54 +0,0 @@ -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 org.springframework.http.server.reactive.ServerHttpRequest; -import org.springframework.security.core.Authentication; -import org.springframework.security.oauth2.provider.OAuth2Authentication; -import org.springframework.security.web.server.WebFilterExchange; -import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.server.ServerWebExchange; -import reactor.core.publisher.Mono; - -/** - * 认证成功处理类 - * - * @author zlt - * @date 2019/10/7 - *

- * Blog: http://zlt2000.gitee.io - * Github: https://github.com/zlt2000 - */ -public class Oauth2AuthSuccessHandler 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); - } - ServerWebExchange exchange = webFilterExchange.getExchange(); - ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate() - .headers(h -> h.addAll(headerValues)) - .build(); - - ServerWebExchange build = exchange.mutate().request(serverHttpRequest).build(); - return webFilterExchange.getChain().filter(build); - } -} 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 deleted file mode 100644 index 0bd0af65..00000000 --- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/PermissionAuthManager.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.central.gateway.auth; - -import com.central.common.model.SysMenu; -import com.central.gateway.feign.AsynMenuService; -import com.central.oauth2.common.service.impl.DefaultPermissionServiceImpl; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.server.reactive.ServerHttpRequest; -import org.springframework.security.authorization.AuthorizationDecision; -import org.springframework.security.authorization.ReactiveAuthorizationManager; -import org.springframework.security.core.Authentication; -import org.springframework.security.web.server.authorization.AuthorizationContext; -import org.springframework.stereotype.Component; -import org.springframework.web.server.ServerWebExchange; -import reactor.core.publisher.Mono; - -import javax.annotation.Resource; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.Future; - -/** - * url权限认证 - * - * @author zlt - * @date 2019/10/6 - *

- * Blog: http://zlt2000.gitee.io - * Github: https://github.com/zlt2000 - */ -@Slf4j -@Component -public class PermissionAuthManager extends DefaultPermissionServiceImpl implements ReactiveAuthorizationManager { - @Resource - private AsynMenuService asynMenuService; - - @Override - public Mono check(Mono authentication, AuthorizationContext authorizationContext) { - return authentication.map(auth -> { - ServerWebExchange exchange = authorizationContext.getExchange(); - ServerHttpRequest request = exchange.getRequest(); - boolean isPermission = super.hasPermission(auth, request.getMethodValue(), request.getURI().getPath()); - return new AuthorizationDecision(isPermission); - }).defaultIfEmpty(new AuthorizationDecision(false)); - } - - @Override - public List findMenuByRoleCodes(String roleCodes) { - Future> futureResult = asynMenuService.findByRoleCodes(roleCodes); - try { - return futureResult.get(); - } catch (Exception e) { - log.error("asynMenuService.findMenuByRoleCodes-error", e); - } - return Collections.emptyList(); - } -} \ No newline at end of file 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 deleted file mode 100644 index 34305a81..00000000 --- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.central.gateway.config; - -import com.central.gateway.auth.*; -import com.central.oauth2.common.properties.SecurityProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; -import org.springframework.security.authentication.ReactiveAuthenticationManager; -import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; -import org.springframework.security.config.web.server.SecurityWebFiltersOrder; -import org.springframework.security.config.web.server.ServerHttpSecurity; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.oauth2.server.resource.web.server.authentication.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 - *

- * Blog: http://zlt2000.gitee.io - * Github: https://github.com/zlt2000 - */ -@Configuration -@EnableWebFluxSecurity -public class ResourceServerConfiguration { - @Bean - public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http - , SecurityProperties securityProperties, TokenStore tokenStore, PermissionAuthManager permissionAuthManager) { - //认证处理器 - 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/resources/application.yml b/zlt-gateway/sc-gateway/src/main/resources/application.yml index f7f69bf3..dbdfba45 100644 --- a/zlt-gateway/sc-gateway/src/main/resources/application.yml +++ b/zlt-gateway/sc-gateway/src/main/resources/application.yml @@ -82,6 +82,12 @@ spring: # filter: # enabled: true +knife4j: + gateway: + enabled: true + discover: + excluded-services: ${spring.application.name} + zlt: swagger-agg: generate-routes: user,file diff --git a/zlt-monitor/log-center/pom.xml b/zlt-monitor/log-center/pom.xml index eb2d27bf..45909e61 100644 --- a/zlt-monitor/log-center/pom.xml +++ b/zlt-monitor/log-center/pom.xml @@ -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 5631aa13..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; @@ -19,6 +18,7 @@ import org.springframework.web.bind.annotation.RestController; * 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-uaa/pom.xml b/zlt-uaa/pom.xml index b21c593f..5efd2379 100644 --- a/zlt-uaa/pom.xml +++ b/zlt-uaa/pom.xml @@ -33,14 +33,9 @@ com.zlt zlt-loadbalancer-spring-boot-starter - com.github.xiaoymin knife4j-openapi3-jakarta-spring-boot-starter - 4.2.0 com.zlt @@ -67,11 +62,6 @@ commons-io commons-io - - - com.github.whvcse - easy-captcha - org.springframework.boot @@ -111,10 +101,6 @@ org.apache.tomcat.embed tomcat-embed-core - - javax.servlet - javax.servlet-api - 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 dd7170ce..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,6 @@ 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; /** @@ -33,17 +32,19 @@ public class ValidateCodeController { */ @GetMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{deviceId}") 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()); } /** 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 8003650f..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 @@ -17,7 +17,7 @@ public interface IValidateCodeService { */ void saveImageCode(String deviceId, String imageCode); - Result sendSmsCode(String mobile); + Result sendSmsCode(String mobile); /** * 获取验证码 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 08927bb2..04cce984 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 @@ -54,7 +54,7 @@ public class ValidateCodeServiceImpl implements IValidateCodeService { * @return true、false */ @Override - public Result sendSmsCode(String mobile) { + public Result sendSmsCode(String mobile) { Object tempCode = redisRepository.get(buildKey(mobile)); if (tempCode != null) { log.error("用户:{}验证码未失效{}", mobile, tempCode); diff --git a/zlt-uaa/src/main/resources/application.yml b/zlt-uaa/src/main/resources/application.yml index c4910e53..0952ae43 100644 --- a/zlt-uaa/src/main/resources/application.yml +++ b/zlt-uaa/src/main/resources/application.yml @@ -13,17 +13,30 @@ mybatis-plus: db-config: id-type: auto +springdoc: + swagger-ui: + path: /swagger-ui.html + tags-sorter: alpha + operations-sorter: alpha + api-docs: + path: /v3/api-docs + group-configs: + - group: 'uaa' + paths-to-match: '/**' + packages-to-scan: com.central.oauth.controller + default-flat-param-object: true + +knife4j: + enable: true + setting: + language: zh_cn + swagger-model-name: 认证中心接口文档 + zlt: oauth2: token: store: type: redis - swagger: - enabled: true - title: 认证中心 - description: 认证中心接口文档 - version: 1.0 - base-package: com.central.oauth.controller security: code: # 忽略验证码的应用编号 @@ -43,21 +56,4 @@ zlt: enabled: false includeSqls: # 应用列表 - - com.central.oauth.mapper.ClientMapper.findList - -springdoc: - swagger-ui: - path: /doc.html - api-docs: - path: /v3/api-docs - group-configs: - - group: 'uaa' - paths-to-match: '/**' - packages-to-scan: com.central.oauth.controller - default-flat-param-object: true - -knife4j: - enable: true - setting: - language: zh_cn - swagger-model-name: 认证中心接口文档 \ No newline at end of file + - com.central.oauth.mapper.ClientMapper.findList \ No newline at end of file