feat: 替换swagger2为OpenAPI3

This commit is contained in:
zlt2000
2023-11-24 17:28:19 +08:00
parent 61640eb237
commit 387b524f67
67 changed files with 494 additions and 2380 deletions
-1
View File
@@ -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通用操作逻辑
+13 -48
View File
@@ -14,8 +14,8 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>17</java.version>
<spring-cloud-alibaba-dependencies.version>2022.0.0.0</spring-cloud-alibaba-dependencies.version>
<spring-boot-dependencies.version>3.0.9</spring-boot-dependencies.version>
<spring-cloud-dependencies.version>2022.0.3</spring-cloud-dependencies.version>
<spring-boot-dependencies.version>3.1.6</spring-boot-dependencies.version>
<spring-cloud-dependencies.version>2022.0.4</spring-cloud-dependencies.version>
<commons-collections4.version>4.4</commons-collections4.version>
<swagger.butler.version>2.0.1</swagger.butler.version>
<jjwt.version>0.9.1</jjwt.version>
@@ -24,10 +24,9 @@
<sharding-sphere.version>3.1.0</sharding-sphere.version>
<security-oauth2.version>2.3.8.RELEASE</security-oauth2.version>
<security-jwt.version>1.1.0.RELEASE</security-jwt.version>
<redisson-starter.version>3.23.2</redisson-starter.version>
<easyCaptcha.version>1.6.2</easyCaptcha.version>
<redisson-starter.version>3.24.3</redisson-starter.version>
<hutool.version>5.7.20</hutool.version>
<mybatis-plus-boot-starter.version>3.5.3.1</mybatis-plus-boot-starter.version>
<mybatis-plus-boot-starter.version>3.5.4.1</mybatis-plus-boot-starter.version>
<aliyun-sdk-oss>3.8.1</aliyun-sdk-oss>
<qiniu-java-sdk>7.2.28</qiniu-java-sdk>
<easypoi.version>4.1.3</easypoi.version>
@@ -35,7 +34,6 @@
<spring-boot-admin.version>2.5.6</spring-boot-admin.version>
<velocity.version>1.7</velocity.version>
<commons-configuration2.version>2.7</commons-configuration2.version>
<txlcn.version>5.0.2.RELEASE</txlcn.version>
<fastdfs-client.version>1.27.2</fastdfs-client.version>
<userAgent.version>1.21</userAgent.version>
<transmittable.version>2.14.3</transmittable.version>
@@ -43,20 +41,17 @@
<commons-beanutils.version>1.9.4</commons-beanutils.version>
<spring-social-security.version>1.1.6.RELEASE</spring-social-security.version>
<commons-io.version>2.7</commons-io.version>
<servlet-api.version>4.0.1</servlet-api.version>
<spring-data-elasticsearch.version>4.2.3</spring-data-elasticsearch.version>
<elasticsearch.version>7.13.4</elasticsearch.version>
<knife4j.version>3.0.3</knife4j.version>
<knife4j.version>4.3.0</knife4j.version>
<hibernate-validator.version>8.0.1.Final</hibernate-validator.version>
<dubbo.version>2.7.8</dubbo.version>
<curator.version>5.1.0</curator.version>
<jackson-databind.version>2.13.4</jackson-databind.version>
<commons-configuration.version>1.10</commons-configuration.version>
<zuul.version>2.2.9.RELEASE</zuul.version>
<aws-java-sdk-s3.version>1.12.40</aws-java-sdk-s3.version>
<spring-cloud-starter-oauth2.version>2.2.5.RELEASE</spring-cloud-starter-oauth2.version>
<docker-maven-plugin.version>1.2.2</docker-maven-plugin.version>
<sonar.exclusions>zlt-job/**/*, zlt-register/**/*, zlt-web/**/*</sonar.exclusions>
<docker.baseImage>openjdk:8-jre-alpine</docker.baseImage>
<docker.volumes>/tmp</docker.volumes>
<docker.image.prefix>hub.zlt.com:8080/microservices-platform</docker.image.prefix>
@@ -69,6 +64,7 @@
<javax.annotation-api.version>1.3.2</javax.annotation-api.version>
<tomcat-embed-core.version>10.1.11</tomcat-embed-core.version>
<httpclient.version>5.2.1</httpclient.version>
<spring.authorization.version>1.1.1</spring.authorization.version>
</properties>
<dependencies>
@@ -136,11 +132,6 @@
<artifactId>zlt-redis-spring-boot-starter</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-swagger2-spring-boot-starter</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-loadbalancer-spring-boot-starter</artifactId>
@@ -221,12 +212,6 @@
<artifactId>swagger-butler-core</artifactId>
<version>${swagger.butler.version}</version>
</dependency>
<!-- 验证码生成工具 -->
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>${easyCaptcha.version}</version>
</dependency>
<!-- hutool java工具类库 -->
<dependency>
<groupId>cn.hutool</groupId>
@@ -275,21 +260,6 @@
<artifactId>commons-configuration2</artifactId>
<version>${commons-configuration2.version}</version>
</dependency>
<dependency>
<groupId>com.codingapi.txlcn</groupId>
<artifactId>txlcn-tm</artifactId>
<version>${txlcn.version}</version>
</dependency>
<dependency>
<groupId>com.codingapi.txlcn</groupId>
<artifactId>txlcn-tc</artifactId>
<version>${txlcn.version}</version>
</dependency>
<dependency>
<groupId>com.codingapi.txlcn</groupId>
<artifactId>txlcn-txmsg-netty</artifactId>
<version>${txlcn.version}</version>
</dependency>
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
@@ -330,11 +300,6 @@
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet-api.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
@@ -405,6 +370,11 @@
<artifactId>jackson-databind</artifactId>
<version>${jackson-databind.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-authorization-server</artifactId>
<version>${spring.authorization.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
@@ -415,11 +385,6 @@
<artifactId>aws-java-sdk-s3</artifactId>
<version>${aws-java-sdk-s3.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
<version>${zuul.version}</version>
</dependency>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
@@ -467,13 +432,13 @@
<artifactId>httpclient5</artifactId>
<version>${httpclient.version}</version>
</dependency>
<!--<dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-dependencies</artifactId>
<version>${knife4j.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>-->
</dependency>
</dependencies>
</dependencyManagement>
+2 -2
View File
@@ -26,8 +26,8 @@
<artifactId>zlt-db-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-swagger2-spring-boot-starter</artifactId>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
@@ -3,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
@@ -8,4 +8,23 @@ spring:
mybatis-plus:
mapper-locations: classpath:/mapper/*Mapper.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.central.generator.model
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: 代码生成器接口文档
@@ -2,12 +2,13 @@ package ${package}.${moduleName}.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import lombok.extern.slf4j.Slf4j;
import ${package}.${moduleName}.model.${className};
@@ -24,18 +25,18 @@ import com.central.common.model.Result;
@Slf4j
@RestController
@RequestMapping("/${pathName}")
@Api(tags = "${comments}")
@Tag(name = "${comments}")
@RequiredArgsConstructor
public class ${className}Controller {
@Autowired
private I${className}Service ${classname}Service;
private final I${className}Service ${classname}Service;
/**
* 列表
*/
@ApiOperation(value = "查询列表")
@ApiImplicitParams({
@ApiImplicitParam(name = "page", value = "分页起始位置", required = true, dataType = "Integer"),
@ApiImplicitParam(name = "limit", value = "分页结束位置", required = true, dataType = "Integer")
@Operation(summary = "查询列表")
@Parameters({
@Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY),
@Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY)
})
@GetMapping
public PageResult list(@RequestParam Map<String, Object> params) {
@@ -45,7 +46,7 @@ public class ${className}Controller {
/**
* 查询
*/
@ApiOperation(value = "查询")
@Operation(summary = "查询")
@GetMapping("/{${pk.attrname}}")
public Result findUserById(@PathVariable Long ${pk.attrname}) {
${className} model = ${classname}Service.getById(${pk.attrname});
@@ -55,7 +56,7 @@ public class ${className}Controller {
/**
* 新增or更新
*/
@ApiOperation(value = "保存")
@Operation(summary = "保存")
@PostMapping
public Result save(@RequestBody ${className} ${classname}) {
${classname}Service.saveOrUpdate(${classname});
@@ -65,7 +66,8 @@ public class ${className}Controller {
/**
* 删除
*/
@ApiOperation(value = "删除")
@Operation(summary = "删除")
@Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true)
@DeleteMapping("/{id}")
public Result delete(@PathVariable Long ${pk.attrname}) {
${classname}Service.removeById(${pk.attrname});
+2 -2
View File
@@ -55,8 +55,8 @@
<!-- swagger -->
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-swagger2-spring-boot-starter</artifactId>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
</dependency>
<dependency>
@@ -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
@@ -51,10 +51,9 @@
<!-- swagger -->
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-swagger2-spring-boot-starter</artifactId>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
@@ -5,7 +5,7 @@ import com.central.admin.properties.IndexProperties;
import com.central.admin.service.IIndexService;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@@ -20,7 +20,7 @@ import java.util.*;
*/
@Slf4j
@RestController
@Api(tags = "索引管理api")
@Tag(name = "索引管理api")
@RequestMapping("/admin")
public class IndexController {
@Autowired
@@ -1,7 +1,7 @@
package com.central.search.controller;
import com.central.search.service.IAggregationService;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
@@ -16,7 +16,7 @@ import java.util.Map;
*/
@Slf4j
@RestController
@Api(tags = "搜索模块api")
@Tag(name = "搜索模块api")
@RequestMapping("/agg")
public class AggregationController {
private final IAggregationService aggregationService;
@@ -5,9 +5,9 @@ import com.central.common.model.*;
import com.central.search.model.SearchDto;
import com.central.search.service.ISearchService;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
@@ -19,7 +19,7 @@ import java.io.IOException;
*/
@Slf4j
@RestController
@Api(tags = "搜索模块api")
@Tag(name = "搜索模块api")
@RequestMapping("/search")
public class SearchController {
private final ISearchService searchService;
@@ -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
show: sys-log-*,mysql-slowlog-*,sys_user,point-log-*,audit-log-*
+2 -2
View File
@@ -40,8 +40,8 @@
</dependency>
<!-- swagger -->
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-swagger2-spring-boot-starter</artifactId>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
@@ -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<Map<String, Object>> findMenusByRoleId(@PathVariable Long roleId) {
Set<Long> 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<SysMenu> findAlls() {
List<SysMenu> list = menuService.findAll();
return PageResult.<SysMenu>builder().data(list).code(0).count((long) list.size()).build();
}
@ApiOperation(value = "获取菜单以及顶级菜单")
@Operation(summary = "获取菜单以及顶级菜单")
@GetMapping("/findOnes")
public PageResult<SysMenu> findOnes() {
List<SysMenu> list = menuService.findOnes();
@@ -144,7 +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<SysMenu> findMyMenu(@LoginUser SysUser user) {
List<SysRole> roles = user.getRoles();
if (CollectionUtil.isEmpty(roles)) {
@@ -3,6 +3,8 @@ package com.central.user.controller;
import java.util.List;
import java.util.Map;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
@@ -18,16 +20,13 @@ import com.central.common.model.Result;
import com.central.common.model.SysRole;
import com.central.user.service.ISysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
* @author 作者 owen E-mail: 624191343@qq.com
* 角色管理
*/
@Slf4j
@RestController
@Api(tags = "角色模块api")
@Tag(name = "角色模块api")
public class SysRoleController {
@Autowired
private ISysRoleService sysRoleService;
@@ -37,7 +36,7 @@ public class SysRoleController {
* @param params
* @return
*/
@ApiOperation(value = "后台管理查询角色")
@Operation(summary = "后台管理查询角色")
@GetMapping("/roles")
public PageResult<SysRole> findRoles(@RequestParam Map<String, Object> params) {
return sysRoleService.findRoles(params);
@@ -47,7 +46,7 @@ public class SysRoleController {
* 用户管理查询所有角色
* @return
*/
@ApiOperation(value = "后台管理查询角色")
@Operation(summary = "后台管理查询角色")
@GetMapping("/allRoles")
public Result<List<SysRole>> findAll() {
List<SysRole> result = sysRoleService.findAll();
@@ -71,7 +70,7 @@ public class SysRoleController {
*
* @param id
*/
@ApiOperation(value = "后台管理删除角色")
@Operation(summary = "后台管理删除角色")
@DeleteMapping("/roles/{id}")
public Result deleteRole(@PathVariable Long id) {
try {
@@ -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<LoginAppUser> 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<SysUser> findUsers(@RequestParam Map<String, Object> params) {
@@ -170,11 +171,11 @@ public class SysUserController {
* @param params
* @return
*/
@ApiOperation(value = "修改用户状态")
@Operation(summary = "修改用户状态")
@GetMapping("/users/updateEnabled")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Integer"),
@ApiImplicitParam(name = "enabled", value = "是否启用", required = true, dataType = "Boolean")
@Parameters({
@Parameter(name = "id",description = "用户id",required = true,in=ParameterIn.QUERY),
@Parameter(name = "enabled",description = "是否启用",required = true,in= ParameterIn.QUERY)
})
public Result updateEnabled(@RequestParam Map<String, Object> params) {
Long id = MapUtils.getLong(params, "id");
@@ -273,11 +274,11 @@ public class SysUserController {
return Result.succeed("导入数据成功,一共【"+rowNum+"】行");
}
@ApiOperation(value = "用户全文搜索列表")
@ApiImplicitParams({
@ApiImplicitParam(name = "page", value = "分页起始位置", required = true, dataType = "Integer"),
@ApiImplicitParam(name = "limit", value = "分页结束位置", required = true, dataType = "Integer"),
@ApiImplicitParam(name = "queryStr", value = "搜索关键字", dataType = "String")
@Operation(summary = "用户全文搜索列表")
@Parameters({
@Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY),
@Parameter(name = "limit",description = "分页结束位置",required = true,in= ParameterIn.QUERY),
@Parameter(name = "queryStr",description = "搜索关键字",in= ParameterIn.QUERY)
})
@GetMapping("/users/search")
public PageResult<JsonNode> search(SearchDto searchDto) {
@@ -292,7 +293,7 @@ public class SysUserController {
* @return
*/
@GetMapping(value = "/users/roleUser/{username}")
@ApiOperation(value = "查询用户-带角色信息")
@Operation(summary = "查询用户-带角色信息")
@Cacheable(value = "userRoles", key = "#username")
public SysUser selectRoleUser(@PathVariable("username") String username){
SysUser sysUser = selectByUsername(username);
@@ -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
-1
View File
@@ -14,7 +14,6 @@
<module>zlt-redis-spring-boot-starter</module>
<module>zlt-common-spring-boot-starter</module>
<module>zlt-db-spring-boot-starter</module>
<module>zlt-swagger2-spring-boot-starter</module>
<module>zlt-log-spring-boot-starter</module>
<module>zlt-loadbalancer-spring-boot-starter</module>
<module>zlt-auth-client-spring-boot-starter</module>
@@ -13,8 +13,8 @@
<description>认证客户端通用组件</description>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-authorization-server</artifactId>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
@@ -42,9 +42,5 @@
<artifactId>tomcat-embed-websocket</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
</dependencies>
</project>
@@ -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<HttpSecurity>.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<HttpSecurity>.AuthorizedUrl authorizedUrl) {
return authorizedUrl.authenticated().and();
}
/**
* 留给子类重写扩展功能
* @param http
*/
public HttpSecurity setHttp(HttpSecurity http) {
return http;
}
}
@@ -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());
}
};
}
}
@@ -1,89 +0,0 @@
package com.central.oauth2.common.constants;
/**
* id_token属性名常量
*
* @author zlt
* @version 1.0
* @date 2021/4/23
* <p>
* 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";
}
@@ -1,96 +0,0 @@
package com.central.oauth2.common.converter;
import com.central.common.model.LoginAppUser;
import com.central.common.model.SysUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.util.StringUtils;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 优化自org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter
* jwt返回的principal改为返回SysUser,增加扩展字段
*
* @author zlt
* @date 2019/8/5
*/
public class CustomUserAuthenticationConverter implements UserAuthenticationConverter {
private Collection<? extends GrantedAuthority> defaultAuthorities;
private UserDetailsService userDetailsService;
/**
* Optional {@link UserDetailsService} to use when extracting an {@link Authentication} from the incoming map.
*
* @param userDetailsService the userDetailsService to set
*/
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
/**
* Default value for authorities if an Authentication is being created and the input has no data for authorities.
* Note that unless this property is set, the default Authentication created by {@link #extractAuthentication(Map)}
* will be unauthenticated.
*
* @param defaultAuthorities the defaultAuthorities to set. Default null.
*/
public void setDefaultAuthorities(String[] defaultAuthorities) {
this.defaultAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
.arrayToCommaDelimitedString(defaultAuthorities));
}
@Override
public Map<String, ?> convertUserAuthentication(Authentication authentication) {
Map<String, Object> response = new LinkedHashMap<String, Object>();
response.put(USERNAME, authentication.getName());
if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
}
return response;
}
@Override
public Authentication extractAuthentication(Map<String, ?> map) {
if (map.containsKey(USERNAME)) {
Object principal = map.get(USERNAME);
Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
if (userDetailsService != null) {
UserDetails user = userDetailsService.loadUserByUsername((String) map.get(USERNAME));
authorities = user.getAuthorities();
principal = user;
} else {
Integer id = (Integer)map.get("id");
LoginAppUser user = new LoginAppUser();
user.setUsername((String)principal);
user.setId(Long.valueOf(id));
principal = user;
}
return new UsernamePasswordAuthenticationToken(principal, "N/A", authorities);
}
return null;
}
private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
if (!map.containsKey(AUTHORITIES)) {
return defaultAuthorities;
}
Object authorities = map.get(AUTHORITIES);
if (authorities instanceof String) {
return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
}
if (authorities instanceof Collection) {
return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
.collectionToCommaDelimitedString((Collection<?>) authorities));
}
throw new IllegalArgumentException("Authorities must be either a String or a Collection");
}
}
@@ -0,0 +1,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
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class CustomOAuth2AuthenticationException extends OAuth2AuthenticationException {
public CustomOAuth2AuthenticationException(String msg) {
super(new OAuth2Error(msg), msg);
}
}
@@ -1,44 +0,0 @@
package com.central.oauth2.common.service.impl;
import com.central.oauth2.common.properties.SecurityProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
* 自定义 TokenExtractor
*
* @author zlt
* @version 1.0
* @date 2022/6/4
* <p>
* Blog: 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);
}
}
@@ -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
* <p>
* 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 (?<token>[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())));
}
}
@@ -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
* <p>
* 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<SysMenu> findMenuByRoleCodes(String roleCodes);
public boolean hasPermission(Authentication authentication, String requestMethod, String requestURI) {
// 前端跨域OPTIONS请求预检放行 也可通过前端配置代理实现
if (HttpMethod.OPTIONS.name().equalsIgnoreCase(requestMethod)) {
return true;
}
if (!(authentication instanceof AnonymousAuthenticationToken)) {
//判断是否开启url权限验证
if (!securityProperties.getAuth().getUrlPermission().getEnable()) {
return true;
}
//超级管理员admin不需认证
String username = AuthUtils.getUsername(authentication);
if (CommonConstant.ADMIN_USER_NAME.equals(username)) {
return true;
}
OAuth2Authentication auth2Authentication = (OAuth2Authentication)authentication;
//判断应用黑白名单
if (!isNeedAuth(auth2Authentication.getOAuth2Request().getClientId())) {
return true;
}
//判断不进行url权限认证的api,所有已登录用户都能访问的url
for (String path : securityProperties.getAuth().getUrlPermission().getIgnoreUrls()) {
if (antPathMatcher.match(path, requestURI)) {
return true;
}
}
List<SimpleGrantedAuthority> grantedAuthorityList = (List<SimpleGrantedAuthority>) authentication.getAuthorities();
if (CollectionUtil.isEmpty(grantedAuthorityList)) {
log.warn("角色列表为空:{}", authentication.getPrincipal());
return false;
}
//保存租户信息
String clientId = auth2Authentication.getOAuth2Request().getClientId();
TenantContextHolder.setTenant(clientId);
String roleCodes = grantedAuthorityList.stream().map(SimpleGrantedAuthority::getAuthority).collect(Collectors.joining(", "));
List<SysMenu> menuList = findMenuByRoleCodes(roleCodes);
for (SysMenu menu : menuList) {
if (StringUtils.isNotEmpty(menu.getUrl()) && antPathMatcher.match(menu.getUrl(), requestURI)) {
if (StrUtil.isNotEmpty(menu.getPathMethod())) {
return requestMethod.equalsIgnoreCase(menu.getPathMethod());
} else {
return true;
}
}
}
}
return false;
}
/**
* 判断应用是否满足白名单和黑名单的过滤逻辑
* @param clientId 应用id
* @return true(需要认证),false(不需要认证)
*/
private boolean isNeedAuth(String clientId) {
boolean result = true;
//白名单
List<String> includeClientIds = securityProperties.getAuth().getUrlPermission().getIncludeClientIds();
//黑名单
List<String> exclusiveClientIds = securityProperties.getAuth().getUrlPermission().getExclusiveClientIds();
if (includeClientIds.size() > 0) {
result = includeClientIds.contains(clientId);
} else if(exclusiveClientIds.size() > 0) {
result = !exclusiveClientIds.contains(clientId);
}
return result;
}
}
@@ -1,28 +0,0 @@
package com.central.oauth2.common.store;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import javax.sql.DataSource;
/**
* 认证服务器使用数据库存取令牌
*
* @author zlt
* @date 2018/7/24 16:23
*/
@Configuration
@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "db")
public class AuthDbTokenStore {
@Autowired
private DataSource dataSource;
@Bean
public TokenStore tokenStore(){
return new JdbcTokenStore(dataSource);
}
}
@@ -1,55 +0,0 @@
package com.central.oauth2.common.store;
import com.central.common.model.SysUser;
import com.central.oauth2.common.converter.CustomUserAuthenticationConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import javax.annotation.Resource;
import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;
/**
* 认证服务器使用 JWT RSA 非对称加密令牌
*
* @author zlt
* @date 2018/7/24 16:21
* <p>
* Blog: 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;
}
}
@@ -1,29 +0,0 @@
package com.central.oauth2.common.store;
import com.central.oauth2.common.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.security.oauth2.provider.token.TokenStore;
/**
* 认证服务器使用Redis存取令牌
* 注意: 需要配置redis参数
*
* @author zlt
* @date 2018/7/25 9:36
* <p>
* Blog: 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<Object> redisValueSerializer) {
return new CustomRedisTokenStore(connectionFactory, securityProperties, redisValueSerializer);
}
}
@@ -1,543 +0,0 @@
package com.central.oauth2.common.store;
import com.central.common.constant.SecurityConstants;
import com.central.oauth2.common.properties.SecurityProperties;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.JdkSerializationStrategy;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStoreSerializationStrategy;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* 优化自Spring Security的RedisTokenStore
* 1. 支持redis所有集群模式包括cluster模式
* 2. 使用pipeline减少连接次数,提升性能
* 3. 自动续签token(可配置是否开启)
*
* @author zlt
* @date 2019/7/7
*/
public class CustomRedisTokenStore implements TokenStore {
private static final String ACCESS = "access:";
private static final String ACCESS_BAK = "access_bak:";
private static final String AUTH_TO_ACCESS = "auth_to_access:";
private static final String REFRESH_AUTH = "refresh_auth:";
private static final String ACCESS_TO_REFRESH = "access_to_refresh:";
private static final String REFRESH = "refresh:";
private static final String REFRESH_TO_ACCESS = "refresh_to_access:";
private static final boolean springDataRedis_2_0 = ClassUtils.isPresent(
"org.springframework.data.redis.connection.RedisStandaloneConfiguration",
RedisTokenStore.class.getClassLoader());
private final RedisConnectionFactory connectionFactory;
private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator();
private RedisTokenStoreSerializationStrategy serializationStrategy = new JdkSerializationStrategy();
private String prefix = "";
private Method redisConnectionSet_2_0;
/**
* 认证配置
*/
private SecurityProperties securityProperties;
/**
* 业务redis的value序列化
*/
private RedisSerializer<Object> redisValueSerializer;
public CustomRedisTokenStore(RedisConnectionFactory connectionFactory, SecurityProperties securityProperties, RedisSerializer<Object> redisValueSerializer) {
this.connectionFactory = connectionFactory;
this.securityProperties = securityProperties;
this.redisValueSerializer = redisValueSerializer;
if (springDataRedis_2_0) {
this.loadRedisConnectionMethods_2_0();
}
}
public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) {
this.authenticationKeyGenerator = authenticationKeyGenerator;
}
public void setSerializationStrategy(RedisTokenStoreSerializationStrategy serializationStrategy) {
this.serializationStrategy = serializationStrategy;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
private void loadRedisConnectionMethods_2_0() {
this.redisConnectionSet_2_0 = ReflectionUtils.findMethod(
RedisConnection.class, "set", byte[].class, byte[].class);
}
private RedisConnection getConnection() {
return connectionFactory.getConnection();
}
private byte[] serialize(Object object) {
return serializationStrategy.serialize(object);
}
private byte[] serializeKey(String object) {
return serialize(prefix + object);
}
private OAuth2AccessToken deserializeAccessToken(byte[] bytes) {
return serializationStrategy.deserialize(bytes, OAuth2AccessToken.class);
}
private OAuth2Authentication deserializeAuthentication(byte[] bytes) {
return serializationStrategy.deserialize(bytes, OAuth2Authentication.class);
}
private OAuth2RefreshToken deserializeRefreshToken(byte[] bytes) {
return serializationStrategy.deserialize(bytes, OAuth2RefreshToken.class);
}
private ClientDetails deserializeClientDetails(byte[] bytes) {
return (ClientDetails) redisValueSerializer.deserialize(bytes);
}
private byte[] serialize(String string) {
return serializationStrategy.serialize(string);
}
private String deserializeString(byte[] bytes) {
return serializationStrategy.deserializeString(bytes);
}
@Override
public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
String key = authenticationKeyGenerator.extractKey(authentication);
byte[] serializedKey = serializeKey(AUTH_TO_ACCESS + key);
byte[] bytes;
RedisConnection conn = getConnection();
try {
bytes = conn.get(serializedKey);
} finally {
conn.close();
}
OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
if (accessToken != null) {
OAuth2Authentication storedAuthentication = readAuthentication(accessToken.getValue());
if ((storedAuthentication == null || !key.equals(authenticationKeyGenerator.extractKey(storedAuthentication)))) {
// Keep the stores consistent (maybe the same user is
// represented by this authentication but the details have
// changed)
storeAccessToken(accessToken, authentication);
}
}
return accessToken;
}
@Override
public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
OAuth2Authentication auth2Authentication = readAuthentication(token.getValue());
//是否开启token续签
boolean isRenew = securityProperties.getAuth().getRenew().getEnable();
if (isRenew && auth2Authentication != null) {
OAuth2Request clientAuth = auth2Authentication.getOAuth2Request();
//判断当前应用是否需要自动续签
if (checkRenewClientId(clientAuth.getClientId())) {
//获取过期时长
int validitySeconds = getAccessTokenValiditySeconds(clientAuth.getClientId());
if (validitySeconds > 0) {
double expiresRatio = token.getExpiresIn() / (double) validitySeconds;
//判断是否需要续签,当前剩余时间小于过期时长的50%则续签
if (expiresRatio <= securityProperties.getAuth().getRenew().getTimeRatio()) {
//更新AccessToken过期时间
DefaultOAuth2AccessToken oAuth2AccessToken = (DefaultOAuth2AccessToken) token;
oAuth2AccessToken.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
storeAccessToken(oAuth2AccessToken, auth2Authentication, true);
}
}
}
}
return auth2Authentication;
}
/**
* 判断应用自动续签是否满足白名单和黑名单的过滤逻辑
*
* @param clientId 应用id
* @return 是否满足
*/
private boolean checkRenewClientId(String clientId) {
boolean result = true;
//白名单
List<String> includeClientIds = securityProperties.getAuth().getRenew().getIncludeClientIds();
//黑名单
List<String> exclusiveClientIds = securityProperties.getAuth().getRenew().getExclusiveClientIds();
if (includeClientIds.size() > 0) {
result = includeClientIds.contains(clientId);
} else if (exclusiveClientIds.size() > 0) {
result = !exclusiveClientIds.contains(clientId);
}
return result;
}
/**
* 获取token的总有效时长
*
* @param clientId 应用id
*/
private int getAccessTokenValiditySeconds(String clientId) {
RedisConnection conn = getConnection();
byte[] bytes;
try {
bytes = conn.get(serializeKey(SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId));
} finally {
conn.close();
}
if (bytes != null) {
ClientDetails clientDetails = deserializeClientDetails(bytes);
if (clientDetails.getAccessTokenValiditySeconds() != null) {
return clientDetails.getAccessTokenValiditySeconds();
}
}
//返回默认值
return SecurityConstants.ACCESS_TOKEN_VALIDITY_SECONDS;
}
@Override
public OAuth2Authentication readAuthentication(String token) {
byte[] bytes;
RedisConnection conn = getConnection();
try {
bytes = conn.get(serializeKey(SecurityConstants.REDIS_TOKEN_AUTH + token));
} finally {
conn.close();
}
return deserializeAuthentication(bytes);
}
@Override
public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) {
return readAuthenticationForRefreshToken(token.getValue());
}
public OAuth2Authentication readAuthenticationForRefreshToken(String token) {
RedisConnection conn = getConnection();
try {
byte[] bytes = conn.get(serializeKey(REFRESH_AUTH + token));
return deserializeAuthentication(bytes);
} finally {
conn.close();
}
}
@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
storeAccessToken(token, authentication, false);
}
/**
* 存储token
*
* @param isRenew 是否续签
*/
private void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication, boolean isRenew) {
byte[] serializedAccessToken = serialize(token);
byte[] serializedAuth = serialize(authentication);
byte[] accessKey = serializeKey(ACCESS + token.getValue());
byte[] accessBakKey = serializeKey(ACCESS_BAK + token.getValue());
byte[] authKey = serializeKey(SecurityConstants.REDIS_TOKEN_AUTH + token.getValue());
byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication));
byte[] approvalKey = serializeKey(SecurityConstants.REDIS_UNAME_TO_ACCESS + getApprovalKey(authentication));
byte[] clientId = serializeKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());
RedisConnection conn = getConnection();
try {
byte[] oldAccessToken = conn.get(accessKey);
//如果token已存在,并且不是续签的话直接返回
if (!isRenew && oldAccessToken != null) {
return;
}
conn.openPipeline();
if (springDataRedis_2_0) {
try {
this.redisConnectionSet_2_0.invoke(conn, accessKey, serializedAccessToken);
this.redisConnectionSet_2_0.invoke(conn, accessBakKey, serializedAccessToken);
this.redisConnectionSet_2_0.invoke(conn, authKey, serializedAuth);
this.redisConnectionSet_2_0.invoke(conn, authToAccessKey, serializedAccessToken);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
} else {
conn.set(accessKey, serializedAccessToken);
conn.set(accessBakKey, serializedAccessToken);
conn.set(authKey, serializedAuth);
conn.set(authToAccessKey, serializedAccessToken);
}
//如果是续签token,需要先删除集合里旧的值
if (oldAccessToken != null) {
if (!authentication.isClientOnly()) {
conn.lRem(approvalKey, 1, oldAccessToken);
}
conn.lRem(clientId, 1, oldAccessToken);
}
if (!authentication.isClientOnly()) {
conn.rPush(approvalKey, serializedAccessToken);
}
conn.rPush(clientId, serializedAccessToken);
if (token.getExpiration() != null) {
int seconds = token.getExpiresIn();
conn.expire(accessKey, seconds);
conn.expire(accessBakKey, seconds + 60);
conn.expire(authKey, seconds);
conn.expire(authToAccessKey, seconds);
conn.expire(clientId, seconds);
conn.expire(approvalKey, seconds);
}
OAuth2RefreshToken refreshToken = token.getRefreshToken();
if (refreshToken != null && refreshToken.getValue() != null) {
byte[] refresh = serialize(token.getRefreshToken().getValue());
byte[] auth = serialize(token.getValue());
byte[] refreshToAccessKey = serializeKey(REFRESH_TO_ACCESS + token.getRefreshToken().getValue());
byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + token.getValue());
if (springDataRedis_2_0) {
try {
this.redisConnectionSet_2_0.invoke(conn, refreshToAccessKey, auth);
this.redisConnectionSet_2_0.invoke(conn, accessToRefreshKey, refresh);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
} else {
conn.set(refreshToAccessKey, auth);
conn.set(accessToRefreshKey, refresh);
}
expireRefreshToken(refreshToken, conn, refreshToAccessKey, accessToRefreshKey);
}
conn.closePipeline();
} finally {
conn.close();
}
}
private static String getApprovalKey(OAuth2Authentication authentication) {
String userName = authentication.getUserAuthentication() == null ? ""
: authentication.getUserAuthentication().getName();
return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName);
}
private static String getApprovalKey(String clientId, String userName) {
return clientId + (userName == null ? "" : ":" + userName);
}
@Override
public void removeAccessToken(OAuth2AccessToken accessToken) {
removeAccessToken(accessToken.getValue());
}
@Override
public OAuth2AccessToken readAccessToken(String tokenValue) {
byte[] key = serializeKey(ACCESS + tokenValue);
byte[] bytes;
RedisConnection conn = getConnection();
try {
bytes = conn.get(key);
} finally {
conn.close();
}
return deserializeAccessToken(bytes);
}
public void removeAccessToken(String tokenValue) {
byte[] accessKey = serializeKey(ACCESS + tokenValue);
byte[] accessBakKey = serializeKey(ACCESS_BAK + tokenValue);
byte[] authKey = serializeKey(SecurityConstants.REDIS_TOKEN_AUTH + tokenValue);
byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue);
RedisConnection conn = getConnection();
try {
byte[] access = conn.get(accessKey);
byte[] auth = conn.get(authKey);
conn.openPipeline();
conn.del(accessKey);
conn.del(accessBakKey);
conn.del(accessToRefreshKey);
// Don't remove the refresh token - it's up to the caller to do that
conn.del(authKey);
conn.closePipeline();
OAuth2Authentication authentication = deserializeAuthentication(auth);
if (authentication != null) {
String key = authenticationKeyGenerator.extractKey(authentication);
byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + key);
byte[] unameKey = serializeKey(SecurityConstants.REDIS_UNAME_TO_ACCESS + getApprovalKey(authentication));
byte[] clientId = serializeKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());
conn.openPipeline();
conn.del(authToAccessKey);
conn.lRem(unameKey, 1, access);
conn.lRem(clientId, 1, access);
conn.del(serialize(ACCESS + key));
conn.closePipeline();
}
} finally {
conn.close();
}
}
@Override
public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
byte[] refreshKey = serializeKey(REFRESH + refreshToken.getValue());
byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + refreshToken.getValue());
byte[] serializedRefreshToken = serialize(refreshToken);
RedisConnection conn = getConnection();
try {
conn.openPipeline();
if (springDataRedis_2_0) {
try {
this.redisConnectionSet_2_0.invoke(conn, refreshKey, serializedRefreshToken);
this.redisConnectionSet_2_0.invoke(conn, refreshAuthKey, serialize(authentication));
} catch (Exception ex) {
throw new RuntimeException(ex);
}
} else {
conn.set(refreshKey, serializedRefreshToken);
conn.set(refreshAuthKey, serialize(authentication));
}
expireRefreshToken(refreshToken, conn, refreshKey, refreshAuthKey);
conn.closePipeline();
} finally {
conn.close();
}
}
private void expireRefreshToken(OAuth2RefreshToken refreshToken, RedisConnection conn, byte[] refreshKey, byte[] refreshAuthKey) {
if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken;
Date expiration = expiringRefreshToken.getExpiration();
if (expiration != null) {
int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L)
.intValue();
conn.expire(refreshKey, seconds);
conn.expire(refreshAuthKey, seconds);
}
}
}
@Override
public OAuth2RefreshToken readRefreshToken(String tokenValue) {
byte[] key = serializeKey(REFRESH + tokenValue);
byte[] bytes;
RedisConnection conn = getConnection();
try {
bytes = conn.get(key);
} finally {
conn.close();
}
return deserializeRefreshToken(bytes);
}
@Override
public void removeRefreshToken(OAuth2RefreshToken refreshToken) {
removeRefreshToken(refreshToken.getValue());
}
public void removeRefreshToken(String tokenValue) {
byte[] refreshKey = serializeKey(REFRESH + tokenValue);
byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + tokenValue);
byte[] refresh2AccessKey = serializeKey(REFRESH_TO_ACCESS + tokenValue);
byte[] access2RefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue);
RedisConnection conn = getConnection();
try {
conn.openPipeline();
conn.del(refreshKey);
conn.del(refreshAuthKey);
conn.del(refresh2AccessKey);
conn.del(access2RefreshKey);
conn.closePipeline();
} finally {
conn.close();
}
}
@Override
public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) {
removeAccessTokenUsingRefreshToken(refreshToken.getValue());
}
private void removeAccessTokenUsingRefreshToken(String refreshToken) {
byte[] key = serializeKey(REFRESH_TO_ACCESS + refreshToken);
RedisConnection conn = getConnection();
byte[] bytes = null;
try {
bytes = conn.get(key);
conn.del(key);
} finally {
conn.close();
}
if (bytes == null) {
return;
}
String accessToken = deserializeString(bytes);
if (accessToken != null) {
removeAccessToken(accessToken);
}
}
@Override
public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
byte[] approvalKey = serializeKey(SecurityConstants.REDIS_UNAME_TO_ACCESS + getApprovalKey(clientId, userName));
List<byte[]> byteList;
RedisConnection conn = getConnection();
try {
byteList = conn.lRange(approvalKey, 0, -1);
} finally {
conn.close();
}
return getTokenCollections(byteList);
}
@Override
public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
byte[] key = serializeKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + clientId);
List<byte[]> byteList;
RedisConnection conn = getConnection();
try {
byteList = conn.lRange(key, 0, -1);
} finally {
conn.close();
}
return getTokenCollections(byteList);
}
private Collection<OAuth2AccessToken> getTokenCollections(List<byte[]> byteList) {
if (byteList == null || byteList.size() == 0) {
return Collections.emptySet();
}
List<OAuth2AccessToken> accessTokens = new ArrayList<>(byteList.size());
for (byte[] bytes : byteList) {
OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
accessTokens.add(accessToken);
}
return Collections.unmodifiableCollection(accessTokens);
}
}
@@ -1,89 +0,0 @@
package com.central.oauth2.common.store;
import cn.hutool.core.util.StrUtil;
import com.central.common.constant.SecurityConstants;
import com.central.oauth2.common.converter.CustomUserAuthenticationConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.web.client.RestTemplate;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Base64;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 资源服务器 TokenStore 配置类,使用 JWT RSA 非对称加密
*
* @author zlt
* @date 2018/8/20 9:25
*/
@Configuration
@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "resJwt")
public class ResJwtTokenStore {
@Autowired
private ResourceServerProperties resource;
@Bean
public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
return new JwtTokenStore(jwtAccessTokenConverter);
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setVerifierKey(getPubKey());
DefaultAccessTokenConverter tokenConverter = (DefaultAccessTokenConverter)converter.getAccessTokenConverter();
tokenConverter.setUserTokenConverter(new CustomUserAuthenticationConverter());
return converter;
}
/**
* 获取非对称加密公钥 Key
* @return 公钥 Key
*/
private String getPubKey() {
Resource res = new ClassPathResource(SecurityConstants.RSA_PUBLIC_KEY);
try (BufferedReader br = new BufferedReader(new InputStreamReader(res.getInputStream()))) {
return br.lines().collect(Collectors.joining("\n"));
} catch (IOException ioe) {
return getKeyFromAuthorizationServer();
}
}
/**
* 通过访问授权服务器获取非对称加密公钥 Key
* @return 公钥 Key
*/
private String getKeyFromAuthorizationServer() {
if (StrUtil.isNotEmpty(this.resource.getJwt().getKeyUri())) {
final HttpHeaders headers = new HttpHeaders();
final String username = this.resource.getClientId();
final String password = this.resource.getClientSecret();
if (username != null && password != null) {
final byte[] token = Base64.getEncoder().encode((username + ":" + password).getBytes());
headers.add("Authorization", "Basic " + new String(token));
}
final HttpEntity<Void> request = new HttpEntity<>(headers);
final String url = this.resource.getJwt().getKeyUri();
return (String) new RestTemplate()
.exchange(url, HttpMethod.GET, request, Map.class).getBody()
.get("value");
}
return null;
}
}
@@ -0,0 +1,66 @@
package com.central.oauth2.common.token;
import lombok.Getter;
import lombok.Setter;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.server.authorization.util.SpringAuthorizationServerVersion;
import java.io.Serial;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
/**
* @author: zlt
* @date: 2023/11/15
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Getter
@Setter
public class BaseAuthenticationToken extends AbstractAuthenticationToken {
@Serial
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
private final AuthorizationGrantType grantType;
private Authentication clientPrincipal;
private Map<String, Object> additionalParameters;
private Set<String> scopes;
public BaseAuthenticationToken(AuthorizationGrantType authorizationGrantType) {
super(null);
this.grantType = authorizationGrantType;
}
public BaseAuthenticationToken(AuthorizationGrantType authorizationGrantType, Set<String> scopes
, Authentication clientPrincipal, @Nullable Map<String, Object> additionalParameters) {
super(null);
this.grantType = authorizationGrantType;
this.scopes = Collections.unmodifiableSet(scopes != null ? scopes : Collections.emptySet());
this.clientPrincipal = clientPrincipal;
this.additionalParameters = additionalParameters;
}
public BaseAuthenticationToken(Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.grantType = null;
this.clientPrincipal = null;
this.additionalParameters = null;
this.scopes = null;
}
@Override
public Object getPrincipal() {
return this.clientPrincipal;
}
@Override
public Object getCredentials() {
return "";
}
}
@@ -0,0 +1,19 @@
package com.central.oauth2.common.token;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import java.util.Map;
/**
* @author: zlt
* @date: 2023/11/20
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class CustomAccessToken extends OAuth2Authorization.Token<OAuth2AccessToken> {
protected CustomAccessToken(OAuth2AccessToken token, Map metadata) {
super(token, metadata);
}
}
@@ -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<String> headers = request.getHeaders(CommonConstant.TOKEN_HEADER);
while (headers.hasMoreElements()) {
String value = headers.nextElement();
if ((value.startsWith(OAuth2AccessToken.BEARER_TYPE))) {
String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim();
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<String, String> detailsMap = (Map<String, String>) details;
if (detailsMap != null) {
accountType = detailsMap.get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
}
}
if (authentication instanceof BaseAuthenticationToken authenticationToken) {
accountType = (String)authenticationToken.getAdditionalParameters().get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
}
}
return accountType;
@@ -1,108 +0,0 @@
package com.central.oauth2.common.util;
import com.central.common.constant.SecurityConstants;
import com.central.common.utils.JsonUtil;
import com.central.common.utils.RsaUtils;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.jwt.crypto.sign.SignatureVerifier;
import org.springframework.security.jwt.crypto.sign.Signer;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.stream.Collectors;
/**
* jwt工具类
*
* @author zlt
* @date 2019/7/21
*/
public class JwtUtils {
private static final String PUBKEY_START = "-----BEGIN PUBLIC KEY-----";
private static final String PUBKEY_END = "-----END PUBLIC KEY-----";
/**
* 通过classpath获取公钥值
*/
public static RSAPublicKey getPubKeyObj() {
Resource res = new ClassPathResource(SecurityConstants.RSA_PUBLIC_KEY);
try (BufferedReader br = new BufferedReader(new InputStreamReader(res.getInputStream()))) {
String pubKey = br.lines().collect(Collectors.joining("\n"));
pubKey = pubKey.substring(PUBKEY_START.length(), pubKey.indexOf(PUBKEY_END));
return RsaUtils.getPublicKey(pubKey);
} catch (Exception ioe) {
ioe.printStackTrace();
}
return null;
}
/**
* {"exp":1563256084,"user_name":"admin","authorities":["ADMIN"],"jti":"4ce02f54-3d1c-4461-8af1-73f0841a35df","client_id":"webApp","scope":["app"]}
* @param jwtToken token值
* @param rsaPublicKey 公钥
* @return
*/
public static JsonNode decodeAndVerify(String jwtToken, RSAPublicKey rsaPublicKey) {
SignatureVerifier rsaVerifier = new RsaVerifier(rsaPublicKey);
Jwt jwt = JwtHelper.decodeAndVerify(jwtToken, rsaVerifier);
return JsonUtil.parse(jwt.getClaims());
}
/**
* {"exp":1563256084,"user_name":"admin","authorities":["ADMIN"],"jti":"4ce02f54-3d1c-4461-8af1-73f0841a35df","client_id":"webApp","scope":["app"]}
* @param jwtToken token值
* @return
*/
public static JsonNode decodeAndVerify(String jwtToken) {
return decodeAndVerify(jwtToken, getPubKeyObj());
}
/**
* 判断jwt是否过期
* @param claims jwt内容
* @param currTime 当前时间
* @return 未过期:true,已过期:false
*/
public static boolean checkExp(JsonNode claims, long currTime) {
long exp = claims.get("exp").asLong();
if (exp < currTime) {
return false;
}
return true;
}
/**
* 判断jwt是否过期
* @param claims jwt内容
* @return 未过期:true,已过期:false
*/
public static boolean checkExp(JsonNode claims) {
return checkExp(claims, System.currentTimeMillis());
}
public static Jwt encode(CharSequence content, KeyProperties keyProperties) {
KeyPair keyPair = new KeyStoreKeyFactory(
keyProperties.getKeyStore().getLocation(),
keyProperties.getKeyStore().getSecret().toCharArray())
.getKeyPair(keyProperties.getKeyStore().getAlias());
PrivateKey privateKey = keyPair.getPrivate();
Signer rsaSigner = new RsaSigner((RSAPrivateKey) privateKey);
return JwtHelper.encode(content, rsaSigner);
}
public static String encodeStr(CharSequence content, KeyProperties keyProperties) {
return encode(content, keyProperties).getEncoded();
}
}
-5
View File
@@ -27,11 +27,6 @@
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
@@ -33,12 +33,6 @@
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
@@ -1,29 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.zlt</groupId>
<artifactId>zlt-commons</artifactId>
<version>5.6.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<artifactId>zlt-swagger2-spring-boot-starter</artifactId>
<description>swagger通用组件</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-micro-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
</project>
@@ -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
* <p>
* 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<Docket> createRestApi(SwaggerProperties swaggerProperties) {
ConfigurableBeanFactory configurableBeanFactory = (ConfigurableBeanFactory) beanFactory;
List<Docket> 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<Predicate<String>> basePath = new ArrayList<>(docketInfo.getBasePath().size());
for (String path : docketInfo.getBasePath()) {
basePath.add(PathSelectors.ant(path));
}
// exclude-path处理
List<Predicate<String>> 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<Predicate<String>> basePath = new ArrayList<>();
for (String path : swaggerProperties.getBasePath()) {
basePath.add(PathSelectors.ant(path));
}
// exclude-path处理
List<Predicate<String>> 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<SecurityContext> securityContexts() {
List<SecurityContext> contexts = new ArrayList<>(1);
SecurityContext securityContext = SecurityContext.builder()
.securityReferences(defaultAuth())
//.forPaths(PathSelectors.regex("^(?!auth).*$"))
.build();
contexts.add(securityContext);
return contexts;
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> references = new ArrayList<>(1);
references.add(new SecurityReference(AUTH_KEY, authorizationScopes));
return references;
}
private List<ApiKey> securitySchemes() {
List<ApiKey> apiKeys = new ArrayList<>(1);
ApiKey apiKey = new ApiKey(AUTH_KEY, AUTH_KEY, "header");
apiKeys.add(apiKey);
return apiKeys;
}
private List<Parameter> buildGlobalOperationParametersFromSwaggerProperties(
List<SwaggerProperties.GlobalOperationParameter> globalOperationParameters) {
List<Parameter> 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<Parameter> assemblyGlobalOperationParameters(
List<SwaggerProperties.GlobalOperationParameter> globalOperationParameters,
List<SwaggerProperties.GlobalOperationParameter> docketOperationParameters) {
if (Objects.isNull(docketOperationParameters) || docketOperationParameters.isEmpty()) {
return buildGlobalOperationParametersFromSwaggerProperties(globalOperationParameters);
}
Set<String> docketNames = docketOperationParameters.stream()
.map(SwaggerProperties.GlobalOperationParameter::getName)
.collect(Collectors.toSet());
List<SwaggerProperties.GlobalOperationParameter> 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);
}
}
@@ -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<String> basePath = new ArrayList<>();
/**在basePath基础上需要排除的url规则**/
private List<String> excludePath = new ArrayList<>();
/**分组文档**/
private Map<String, DocketInfo> docket = new LinkedHashMap<>();
/**host信息**/
private String host = "";
/**全局参数配置**/
private List<GlobalOperationParameter> 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<String> basePath = new ArrayList<>();
/**在basePath基础上需要排除的url规则**/
private List<String> excludePath = new ArrayList<>();
private List<GlobalOperationParameter> globalOperationParameters;
}
@Data
public static class Contact {
/**联系人**/
private String name = "";
/**联系人url**/
private String url = "";
/**联系人email**/
private String email = "";
}
}
@@ -1,2 +0,0 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.central.common.swagger2.SwaggerAutoConfiguration
@@ -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 {
}
}*/
@@ -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();
}
}
@@ -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 {
}
*/
+4 -5
View File
@@ -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);
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);
@@ -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;
-1
View File
@@ -76,7 +76,6 @@
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-gateway-spring-boot-starter</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
@@ -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
* <p>
* 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<Authentication> 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);
}
}
@@ -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
* <p>
* 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<MatchResult> matches(ServerWebExchange exchange) {
for (String url : securityProperties.getIgnore().getUrls()) {
if (antPathMatcher.match(url, exchange.getRequest().getURI().getPath())) {
return MatchResult.notMatch();
}
}
return MatchResult.match();
}
}
@@ -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
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
public class JsonAccessDeniedHandler implements ServerAccessDeniedHandler {
@Override
public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException e) {
return WebfluxResponseUtil.responseFailed(exchange, HttpStatus.FORBIDDEN.value(), e.getMessage());
}
}
@@ -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
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
public class JsonAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {
@Override
public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException e) {
return WebfluxResponseUtil.responseFailed(exchange, HttpStatus.UNAUTHORIZED.value(), e.getMessage());
}
}
@@ -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
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class Oauth2AuthSuccessHandler implements ServerAuthenticationSuccessHandler {
@Override
public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
MultiValueMap<String, String> 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);
}
}
@@ -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
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@Component
public class PermissionAuthManager extends DefaultPermissionServiceImpl implements ReactiveAuthorizationManager<AuthorizationContext> {
@Resource
private AsynMenuService asynMenuService;
@Override
public Mono<AuthorizationDecision> check(Mono<Authentication> 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<SysMenu> findMenuByRoleCodes(String roleCodes) {
Future<List<SysMenu>> futureResult = asynMenuService.findByRoleCodes(roleCodes);
try {
return futureResult.get();
} catch (Exception e) {
log.error("asynMenuService.findMenuByRoleCodes-error", e);
}
return Collections.emptyList();
}
}
@@ -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
* <p>
* 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();
}
}
@@ -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
+2 -2
View File
@@ -23,8 +23,8 @@
</dependency>
<!-- swagger -->
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-swagger2-spring-boot-starter</artifactId>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
@@ -1,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<String, Object> requestStatAgg() {
return queryService.requestStatAgg("point-log-*","request-statistics");
@@ -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<JsonNode> getPage(SearchDto searchDto) {
searchDto.setIsHighlighter(true);
@@ -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<JsonNode> getPage(SearchDto searchDto) {
searchDto.setIsHighlighter(true);
@@ -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<JsonNode> 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> traceLog(SearchDto searchDto) {
PageResult<JsonNode> pageResult = queryService.strQuery(SYS_LOG_INDEXNAME, searchDto);
-14
View File
@@ -33,14 +33,9 @@
<groupId>com.zlt</groupId>
<artifactId>zlt-loadbalancer-spring-boot-starter</artifactId>
</dependency>
<!--<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-swagger2-spring-boot-starter</artifactId>
</dependency>-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
@@ -67,11 +62,6 @@
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<!-- 验证码生成工具 -->
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@@ -111,10 +101,6 @@
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
</dependencies>
<build>
@@ -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());
}
/**
@@ -17,7 +17,7 @@ public interface IValidateCodeService {
*/
void saveImageCode(String deviceId, String imageCode);
Result sendSmsCode(String mobile);
Result<String> sendSmsCode(String mobile);
/**
* 获取验证码
@@ -54,7 +54,7 @@ public class ValidateCodeServiceImpl implements IValidateCodeService {
* @return true、false
*/
@Override
public Result sendSmsCode(String mobile) {
public Result<String> sendSmsCode(String mobile) {
Object tempCode = redisRepository.get(buildKey(mobile));
if (tempCode != null) {
log.error("用户:{}验证码未失效{}", mobile, tempCode);
+20 -24
View File
@@ -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: 认证中心接口文档
- com.central.oauth.mapper.ClientMapper.findList