feat: 升级SpringBoot和SpringCloud版本

This commit is contained in:
zlt2000
2023-11-10 14:59:27 +08:00
parent c7dfbc9e39
commit ec616bc1b5
133 changed files with 639 additions and 3666 deletions
+40 -9
View File
@@ -13,21 +13,21 @@
<maven.compiler.target>17</maven.compiler.target> <maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>17</java.version> <java.version>17</java.version>
<spring-cloud-alibaba-dependencies.version>2021.1</spring-cloud-alibaba-dependencies.version> <spring-cloud-alibaba-dependencies.version>2022.0.0.0</spring-cloud-alibaba-dependencies.version>
<spring-boot-dependencies.version>2.5.14</spring-boot-dependencies.version> <spring-boot-dependencies.version>3.0.9</spring-boot-dependencies.version>
<spring-cloud-dependencies.version>2020.0.6</spring-cloud-dependencies.version> <spring-cloud-dependencies.version>2022.0.3</spring-cloud-dependencies.version>
<commons-collections4.version>4.4</commons-collections4.version> <commons-collections4.version>4.4</commons-collections4.version>
<swagger.butler.version>2.0.1</swagger.butler.version> <swagger.butler.version>2.0.1</swagger.butler.version>
<jjwt.version>0.9.1</jjwt.version> <jjwt.version>0.9.1</jjwt.version>
<druid-starter>1.2.6</druid-starter> <druid-starter>1.2.18</druid-starter>
<jasypt.version>1.14</jasypt.version> <jasypt.version>1.14</jasypt.version>
<sharding-sphere.version>3.1.0</sharding-sphere.version> <sharding-sphere.version>3.1.0</sharding-sphere.version>
<security-oauth2.version>2.3.8.RELEASE</security-oauth2.version> <security-oauth2.version>2.3.8.RELEASE</security-oauth2.version>
<security-jwt.version>1.1.0.RELEASE</security-jwt.version> <security-jwt.version>1.1.0.RELEASE</security-jwt.version>
<redisson-starter.version>3.16.1</redisson-starter.version> <redisson-starter.version>3.23.2</redisson-starter.version>
<easyCaptcha.version>1.6.2</easyCaptcha.version> <easyCaptcha.version>1.6.2</easyCaptcha.version>
<hutool.version>5.7.20</hutool.version> <hutool.version>5.7.20</hutool.version>
<mybatis-plus-boot-starter.version>3.5.1</mybatis-plus-boot-starter.version> <mybatis-plus-boot-starter.version>3.5.3.1</mybatis-plus-boot-starter.version>
<aliyun-sdk-oss>3.8.1</aliyun-sdk-oss> <aliyun-sdk-oss>3.8.1</aliyun-sdk-oss>
<qiniu-java-sdk>7.2.28</qiniu-java-sdk> <qiniu-java-sdk>7.2.28</qiniu-java-sdk>
<easypoi.version>4.1.3</easypoi.version> <easypoi.version>4.1.3</easypoi.version>
@@ -38,7 +38,7 @@
<txlcn.version>5.0.2.RELEASE</txlcn.version> <txlcn.version>5.0.2.RELEASE</txlcn.version>
<fastdfs-client.version>1.27.2</fastdfs-client.version> <fastdfs-client.version>1.27.2</fastdfs-client.version>
<userAgent.version>1.21</userAgent.version> <userAgent.version>1.21</userAgent.version>
<transmittable.version>2.12.1</transmittable.version> <transmittable.version>2.14.3</transmittable.version>
<banner.version>1.0.2</banner.version> <banner.version>1.0.2</banner.version>
<commons-beanutils.version>1.9.4</commons-beanutils.version> <commons-beanutils.version>1.9.4</commons-beanutils.version>
<spring-social-security.version>1.1.6.RELEASE</spring-social-security.version> <spring-social-security.version>1.1.6.RELEASE</spring-social-security.version>
@@ -46,8 +46,8 @@
<servlet-api.version>4.0.1</servlet-api.version> <servlet-api.version>4.0.1</servlet-api.version>
<spring-data-elasticsearch.version>4.2.3</spring-data-elasticsearch.version> <spring-data-elasticsearch.version>4.2.3</spring-data-elasticsearch.version>
<elasticsearch.version>7.13.4</elasticsearch.version> <elasticsearch.version>7.13.4</elasticsearch.version>
<knife4j.version>2.0.5</knife4j.version> <knife4j.version>3.0.3</knife4j.version>
<hibernate-validator.version>6.2.0.Final</hibernate-validator.version> <hibernate-validator.version>8.0.1.Final</hibernate-validator.version>
<dubbo.version>2.7.8</dubbo.version> <dubbo.version>2.7.8</dubbo.version>
<curator.version>5.1.0</curator.version> <curator.version>5.1.0</curator.version>
<jackson-databind.version>2.13.4</jackson-databind.version> <jackson-databind.version>2.13.4</jackson-databind.version>
@@ -65,6 +65,10 @@
<guava.version>20.0</guava.version> <guava.version>20.0</guava.version>
<maven-compiler-plugin.version>3.11.0</maven-compiler-plugin.version> <maven-compiler-plugin.version>3.11.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>3.1.2</maven-surefire-plugin.version> <maven-surefire-plugin.version>3.1.2</maven-surefire-plugin.version>
<mysql-connector-java.version>8.0.33</mysql-connector-java.version>
<javax.annotation-api.version>1.3.2</javax.annotation-api.version>
<tomcat-embed-core.version>10.1.11</tomcat-embed-core.version>
<httpclient.version>5.2.1</httpclient.version>
</properties> </properties>
<dependencies> <dependencies>
@@ -97,6 +101,16 @@
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId> <artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency> </dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>${javax.annotation-api.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>${tomcat-embed-core.version}</version>
</dependency>
</dependencies> </dependencies>
<dependencyManagement> <dependencyManagement>
@@ -411,6 +425,11 @@
<artifactId>commons-configuration</artifactId> <artifactId>commons-configuration</artifactId>
<version>${commons-configuration.version}</version> <version>${commons-configuration.version}</version>
</dependency> </dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
@@ -443,6 +462,18 @@
<artifactId>jackson-core</artifactId> <artifactId>jackson-core</artifactId>
<version>${jackson-databind.version}</version> <version>${jackson-databind.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>${httpclient.version}</version>
</dependency>
<!--<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-dependencies</artifactId>
<version>${knife4j.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>-->
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
@@ -3,7 +3,7 @@ package com.central.generator.controller;
import java.io.IOException; import java.io.IOException;
import java.util.Map; import java.util.Map;
import javax.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import com.central.common.model.PageResult; import com.central.common.model.PageResult;
import com.central.generator.service.SysGeneratorService; import com.central.generator.service.SysGeneratorService;
@@ -11,7 +11,7 @@ import java.util.Map;
/** /**
* @author zlt * @author zlt
*/ */
@FeignClient(name = ServiceNameConstants.SEARCH_SERVICE, fallbackFactory = SearchServiceFallbackFactory.class, decode404 = true) @FeignClient(name = ServiceNameConstants.SEARCH_SERVICE, fallbackFactory = SearchServiceFallbackFactory.class, dismiss404 = true)
public interface AggregationService { public interface AggregationService {
/** /**
* 查询文档列表 * 查询文档列表
@@ -11,7 +11,7 @@ import org.springframework.web.bind.annotation.*;
/** /**
* @author zlt * @author zlt
*/ */
@FeignClient(name = ServiceNameConstants.SEARCH_SERVICE, fallbackFactory = SearchServiceFallbackFactory.class, decode404 = true) @FeignClient(name = ServiceNameConstants.SEARCH_SERVICE, fallbackFactory = SearchServiceFallbackFactory.class, dismiss404 = true)
public interface SearchService { public interface SearchService {
/** /**
* 查询文档列表 * 查询文档列表
@@ -5,6 +5,7 @@ import com.central.search.client.feign.SearchService;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.cloud.openfeign.FallbackFactory; import org.springframework.cloud.openfeign.FallbackFactory;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/** /**
* searchService降级工场 * searchService降级工场
@@ -12,6 +13,7 @@ import lombok.extern.slf4j.Slf4j;
* @author zlt * @author zlt
*/ */
@Slf4j @Slf4j
@Component
public class SearchServiceFallbackFactory implements FallbackFactory<SearchService> { public class SearchServiceFallbackFactory implements FallbackFactory<SearchService> {
@Override @Override
public SearchService create(Throwable throwable) { public SearchService create(Throwable throwable) {
@@ -4,6 +4,7 @@ import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/** /**
* 索引配置 * 索引配置
@@ -14,6 +15,7 @@ import org.springframework.cloud.context.config.annotation.RefreshScope;
@Getter @Getter
@ConfigurationProperties(prefix = "zlt.indices") @ConfigurationProperties(prefix = "zlt.indices")
@RefreshScope @RefreshScope
@Component
public class IndexProperties { public class IndexProperties {
/** /**
* 配置过滤的索引名:默认只显示这些索引 * 配置过滤的索引名:默认只显示这些索引
@@ -1,6 +1,5 @@
spring: spring:
elasticsearch: elasticsearch:
rest:
uris: ${zlt.elasticsearch.uris} uris: ${zlt.elasticsearch.uris}
username: ${zlt.elasticsearch.username} username: ${zlt.elasticsearch.username}
password: ${zlt.elasticsearch.password} password: ${zlt.elasticsearch.password}
@@ -34,7 +34,7 @@ import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
/** /**
* @author 作者 owen E-mail: 624191343@qq.com * @author 作者 owen E-mail: 624191343@qq.com
@@ -37,15 +37,14 @@
<artifactId>spring-boot-configuration-processor</artifactId> <artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.apache.tomcat.embed</groupId> <groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-websocket</artifactId> <artifactId>tomcat-embed-websocket</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>
@@ -5,7 +5,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy; 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.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
@@ -52,10 +52,10 @@ public class DefaultResourceServerConf extends ResourceServerConfigurerAdapter {
@Override @Override
public void configure(HttpSecurity http) throws Exception { public void configure(HttpSecurity http) throws Exception {
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.AuthorizedUrl authorizedUrl = setHttp(http) AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizedUrl authorizedUrl = setHttp(http)
.authorizeRequests() .authorizeHttpRequests()
.antMatchers(securityProperties.getIgnore().getUrls()).permitAll() .requestMatchers(securityProperties.getIgnore().getUrls()).permitAll()
.antMatchers(HttpMethod.OPTIONS).permitAll() .requestMatchers(HttpMethod.OPTIONS).permitAll()
.anyRequest(); .anyRequest();
setAuthenticate(authorizedUrl); setAuthenticate(authorizedUrl);
@@ -72,7 +72,7 @@ public class DefaultResourceServerConf extends ResourceServerConfigurerAdapter {
* url权限控制,默认是认证就通过,可以重写实现个性化 * url权限控制,默认是认证就通过,可以重写实现个性化
* @param authorizedUrl * @param authorizedUrl
*/ */
public HttpSecurity setAuthenticate(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.AuthorizedUrl authorizedUrl) { public HttpSecurity setAuthenticate(AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizedUrl authorizedUrl) {
return authorizedUrl.authenticated().and(); return authorizedUrl.authenticated().and();
} }
@@ -10,9 +10,8 @@ import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurity
import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.AuthenticationEntryPoint;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
/** /**
@@ -47,7 +46,7 @@ public class DefaultSecurityHandlerConfig {
return new OAuth2AccessDeniedHandler() { return new OAuth2AccessDeniedHandler() {
@Override @Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException { public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException {
ResponseUtil.responseFailed(objectMapper, response, authException.getMessage()); ResponseUtil.responseFailed(objectMapper, response, authException.getMessage());
} }
}; };
@@ -1,12 +1,11 @@
package com.central.oauth2.common.config; package com.central.oauth2.common.config;
import com.central.oauth2.common.util.AuthUtils; import com.central.oauth2.common.util.AuthUtils;
import jakarta.websocket.server.ServerEndpointConfig;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import javax.websocket.server.ServerEndpointConfig;
/** /**
* webSocket鉴权配置 * webSocket鉴权配置
* *
@@ -4,6 +4,7 @@ import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/** /**
* @author zlt * @author zlt
@@ -17,6 +18,7 @@ import org.springframework.cloud.context.config.annotation.RefreshScope;
@Getter @Getter
@ConfigurationProperties(prefix = "zlt.security") @ConfigurationProperties(prefix = "zlt.security")
@RefreshScope @RefreshScope
@Component
public class SecurityProperties { public class SecurityProperties {
private AuthProperties auth = new AuthProperties(); private AuthProperties auth = new AuthProperties();
@@ -4,6 +4,7 @@ import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/** /**
* Token配置 * Token配置
@@ -19,6 +20,7 @@ import org.springframework.cloud.context.config.annotation.RefreshScope;
@Getter @Getter
@ConfigurationProperties(prefix = "zlt.oauth2.token.store") @ConfigurationProperties(prefix = "zlt.oauth2.token.store")
@RefreshScope @RefreshScope
@Component
public class TokenStoreProperties { public class TokenStoreProperties {
/** /**
* token存储类型(redis/db/authJwt/resJwt) * token存储类型(redis/db/authJwt/resJwt)
@@ -16,7 +16,7 @@ import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAut
import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.TokenStore;
import javax.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.*; import java.util.*;
@@ -15,7 +15,7 @@ import java.util.List;
/** /**
* @author zlt * @author zlt
*/ */
@FeignClient(name = ServiceNameConstants.USER_SERVICE, fallbackFactory = UserServiceFallbackFactory.class, decode404 = true) @FeignClient(name = ServiceNameConstants.USER_SERVICE, fallbackFactory = UserServiceFallbackFactory.class, dismiss404 = true)
public interface UserService { public interface UserService {
/** /**
* feign rpc访问远程/users/{username}接口 * feign rpc访问远程/users/{username}接口
@@ -6,6 +6,7 @@ import com.central.common.model.SysRole;
import com.central.common.model.SysUser; import com.central.common.model.SysUser;
import org.springframework.cloud.openfeign.FallbackFactory; import org.springframework.cloud.openfeign.FallbackFactory;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@@ -17,6 +18,7 @@ import java.util.List;
* @date 2019/1/18 * @date 2019/1/18
*/ */
@Slf4j @Slf4j
@Component
public class UserServiceFallbackFactory implements FallbackFactory<UserService> { public class UserServiceFallbackFactory implements FallbackFactory<UserService> {
@Override @Override
public UserService create(Throwable throwable) { public UserService create(Throwable throwable) {
@@ -4,6 +4,7 @@ import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import lombok.Data; import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
@@ -16,6 +17,7 @@ import java.util.Set;
*/ */
@ConfigurationProperties(prefix = "zlt.datascope") @ConfigurationProperties(prefix = "zlt.datascope")
@Data @Data
@Component
public class DataScopeProperties { public class DataScopeProperties {
private static final Set<String> INGORE_SQL_ID = ImmutableSet private static final Set<String> INGORE_SQL_ID = ImmutableSet
.of("com.central.user.mapper.findRolesByUserId" .of("com.central.user.mapper.findRolesByUserId"
@@ -4,6 +4,7 @@ import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -17,6 +18,7 @@ import java.util.List;
@Getter @Getter
@ConfigurationProperties(prefix = "zlt.tenant") @ConfigurationProperties(prefix = "zlt.tenant")
@RefreshScope @RefreshScope
@Component
public class TenantProperties { public class TenantProperties {
/** /**
* 是否开启多租户 * 是否开启多租户
@@ -10,7 +10,7 @@ import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
/** /**
* head中的应用参数注入clientId中 * head中的应用参数注入clientId中
@@ -1,27 +1,18 @@
package com.central.common.resolver; package com.central.common.resolver;
import cn.hutool.core.util.StrUtil;
import com.central.common.annotation.LoginUser; import com.central.common.annotation.LoginUser;
import com.central.common.constant.SecurityConstants; import com.central.common.constant.SecurityConstants;
import com.central.common.feign.UserService; import com.central.common.feign.UserService;
import com.central.common.model.SysRole;
import com.central.common.model.SysUser; import com.central.common.model.SysUser;
import com.central.common.utils.LoginUserUtils; import com.central.common.utils.LoginUserUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter; import org.springframework.core.MethodParameter;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/** /**
* Token转化SysUser * Token转化SysUser
* *
@@ -3,7 +3,7 @@ package com.central.common.utils;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
@@ -9,7 +9,7 @@ import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.URLEncoder; import java.net.URLEncoder;
@@ -5,13 +5,13 @@ import com.central.common.constant.SecurityConstants;
import com.central.common.feign.UserService; import com.central.common.feign.UserService;
import com.central.common.model.SysRole; import com.central.common.model.SysRole;
import com.central.common.model.SysUser; import com.central.common.model.SysUser;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@@ -3,9 +3,7 @@ package com.central.common.utils;
import com.central.common.passwordEncoder.SM3PasswordEncoder; import com.central.common.passwordEncoder.SM3PasswordEncoder;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder; import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder; import org.springframework.security.crypto.password.*;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder; import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import org.springframework.util.Assert; import org.springframework.util.Assert;
@@ -26,16 +24,16 @@ public class PwdEncoderUtil {
public static PasswordEncoder getDelegatingPasswordEncoder(String encodingId) { public static PasswordEncoder getDelegatingPasswordEncoder(String encodingId) {
Map<String, PasswordEncoder> encoders = new HashMap<>(); Map<String, PasswordEncoder> encoders = new HashMap<>();
encoders.put("bcrypt", new BCryptPasswordEncoder()); encoders.put("bcrypt", new BCryptPasswordEncoder());
encoders.put("ldap", new org.springframework.security.crypto.password.LdapShaPasswordEncoder()); encoders.put("ldap", new LdapShaPasswordEncoder());
encoders.put("MD4", new org.springframework.security.crypto.password.Md4PasswordEncoder()); encoders.put("MD4", new Md4PasswordEncoder());
encoders.put("MD5", new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("MD5")); encoders.put("MD5", new MessageDigestPasswordEncoder("MD5"));
encoders.put("noop", org.springframework.security.crypto.password.NoOpPasswordEncoder.getInstance()); encoders.put("noop", NoOpPasswordEncoder.getInstance());
encoders.put("pbkdf2", new Pbkdf2PasswordEncoder()); encoders.put("pbkdf2",Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8());
encoders.put("scrypt", new SCryptPasswordEncoder()); encoders.put("scrypt", SCryptPasswordEncoder.defaultsForSpringSecurity_v5_8());
encoders.put("SHA-1", new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("SHA-1")); encoders.put("SHA-1", new MessageDigestPasswordEncoder("SHA-1"));
encoders.put("SHA-256", new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("SHA-256")); encoders.put("SHA-256", new MessageDigestPasswordEncoder("SHA-256"));
encoders.put("sha256", new org.springframework.security.crypto.password.StandardPasswordEncoder()); encoders.put("sha256", new StandardPasswordEncoder());
encoders.put("argon2", new Argon2PasswordEncoder()); encoders.put("argon2", Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8());
encoders.put("SM3", new SM3PasswordEncoder()); encoders.put("SM3", new SM3PasswordEncoder());
Assert.isTrue(encoders.containsKey(encodingId), encodingId + " is not found in idToPasswordEncoder"); Assert.isTrue(encoders.containsKey(encodingId), encodingId + " is not found in idToPasswordEncoder");
@@ -4,7 +4,7 @@ import com.central.common.model.Result;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import javax.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.io.Writer; import java.io.Writer;
@@ -14,11 +14,5 @@
<groupId>com.zlt</groupId> <groupId>com.zlt</groupId>
<artifactId>zlt-common-core</artifactId> <artifactId>zlt-common-core</artifactId>
</dependency> </dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<optional>true</optional>
</dependency>
</dependencies> </dependencies>
</project> </project>
@@ -3,15 +3,15 @@ package com.central.common.filter;
import com.central.common.context.LoginUserContextHolder; import com.central.common.context.LoginUserContextHolder;
import com.central.common.model.SysUser; import com.central.common.model.SysUser;
import com.central.common.utils.LoginUserUtils; import com.central.common.utils.LoginUserUtils;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
/** /**
@@ -4,14 +4,14 @@ import cn.hutool.core.util.StrUtil;
import com.central.common.constant.CommonConstant; import com.central.common.constant.CommonConstant;
import com.central.common.constant.SecurityConstants; import com.central.common.constant.SecurityConstants;
import com.central.common.context.TenantContextHolder; import com.central.common.context.TenantContextHolder;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
/** /**
@@ -4,6 +4,7 @@ import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/** /**
* mybatis-plus 配置 * mybatis-plus 配置
@@ -18,6 +19,7 @@ import org.springframework.cloud.context.config.annotation.RefreshScope;
@Getter @Getter
@ConfigurationProperties(prefix = "zlt.mybatis-plus.auto-fill") @ConfigurationProperties(prefix = "zlt.mybatis-plus.auto-fill")
@RefreshScope @RefreshScope
@Component
public class MybatisPlusAutoFillProperties { public class MybatisPlusAutoFillProperties {
/** /**
* 是否开启自动填充字段 * 是否开启自动填充字段
@@ -1,19 +1,20 @@
package com.central.es.config; package com.central.es.config;
import com.central.es.properties.RestClientPoolProperties; import com.central.es.properties.RestClientPoolProperties;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider; import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchProperties;
import org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientProperties;
import org.springframework.boot.autoconfigure.elasticsearch.RestClientBuilderCustomizer;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.context.properties.PropertyMapper; import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; import javax.annotation.Resource;
import java.util.List;
/** /**
* es自动配置 * es自动配置
@@ -25,51 +26,45 @@ import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
* Github: https://github.com/zlt2000 * Github: https://github.com/zlt2000
*/ */
@EnableConfigurationProperties(RestClientPoolProperties.class) @EnableConfigurationProperties(RestClientPoolProperties.class)
public class RestAutoConfigure { public class RestAutoConfigure extends AbstractElasticsearchConfiguration {
@Bean private final static String SCHEME = "http";
public RestClientBuilderCustomizer restClientBuilderCustomizer(RestClientPoolProperties poolProperties private final static String URI_SPLIT = ":";
, ElasticsearchRestClientProperties restProperties) {
return (builder) -> {
setRequestConfig(builder, poolProperties);
setHttpClientConfig(builder, poolProperties, restProperties); @Resource
}; private ElasticsearchProperties restProperties;
@Resource
private RestClientPoolProperties poolProperties;
@Override
public RestHighLevelClient elasticsearchClient() {
List<String> urlArr = restProperties.getUris();
HttpHost[] httpPostArr = new HttpHost[urlArr.size()];
for (int i = 0; i < urlArr.size(); i++) {
HttpHost httpHost = new HttpHost(urlArr.get(i).split(URI_SPLIT)[0].trim(),
Integer.parseInt(urlArr.get(i).split(URI_SPLIT)[1].trim()), SCHEME);
httpPostArr[i] = httpHost;
} }
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
/** credentialsProvider.setCredentials(AuthScope.ANY,
* 异步httpclient连接延时配置 new UsernamePasswordCredentials(restProperties.getUsername(), restProperties.getPassword()));
*/ RestClientBuilder builder = RestClient.builder(httpPostArr)
private void setRequestConfig(RestClientBuilder builder, RestClientPoolProperties poolProperties){ // 异步httpclient连接数配置
builder.setRequestConfigCallback(requestConfigBuilder -> { .setHttpClientConfigCallback(httpClientBuilder -> {
// 账号密码登录
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
// httpclient连接数配置
httpClientBuilder.setMaxConnTotal(poolProperties.getMaxConnectNum())
.setMaxConnPerRoute(poolProperties.getMaxConnectPerRoute());
return httpClientBuilder;
})
// 异步httpclient连接延时配置
.setRequestConfigCallback(requestConfigBuilder -> {
requestConfigBuilder.setConnectTimeout(poolProperties.getConnectTimeOut()) requestConfigBuilder.setConnectTimeout(poolProperties.getConnectTimeOut())
.setSocketTimeout(poolProperties.getSocketTimeOut()) .setSocketTimeout(poolProperties.getSocketTimeOut())
.setConnectionRequestTimeout(poolProperties.getConnectionRequestTimeOut()); .setConnectionRequestTimeout(poolProperties.getConnectionRequestTimeOut());
return requestConfigBuilder; return requestConfigBuilder;
}); });
} return new RestHighLevelClient(builder);
/**
* 异步httpclient连接数配置
*/
private void setHttpClientConfig(RestClientBuilder builder, RestClientPoolProperties poolProperties, ElasticsearchRestClientProperties restProperties){
builder.setHttpClientConfigCallback(httpClientBuilder -> {
httpClientBuilder.setMaxConnTotal(poolProperties.getMaxConnectNum())
.setMaxConnPerRoute(poolProperties.getMaxConnectPerRoute());
PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();
map.from(restProperties::getUsername).to(username -> {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(username, restProperties.getPassword()));
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
});
return httpClientBuilder;
});
}
@Bean
@ConditionalOnMissingBean
public ElasticsearchRestTemplate elasticsearchRestTemplate(RestHighLevelClient restHighLevelClient) {
return new ElasticsearchRestTemplate(restHighLevelClient);
} }
} }
@@ -4,6 +4,7 @@ import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/** /**
* es的httpClient连接池配置 * es的httpClient连接池配置
@@ -18,6 +19,7 @@ import org.springframework.cloud.context.config.annotation.RefreshScope;
@Getter @Getter
@ConfigurationProperties(prefix = "zlt.elasticsearch.rest-pool") @ConfigurationProperties(prefix = "zlt.elasticsearch.rest-pool")
@RefreshScope @RefreshScope
@Component
public class RestClientPoolProperties { public class RestClientPoolProperties {
/** /**
* 链接建立超时时间 * 链接建立超时时间
@@ -30,8 +30,8 @@
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient</artifactId> <artifactId>httpclient5</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>javax.servlet</groupId> <groupId>javax.servlet</groupId>
@@ -1,20 +1,21 @@
package com.central.common.lb; package com.central.common.lb;
import com.central.common.lb.config.RestTemplateProperties; import com.central.common.lb.config.RestTemplateProperties;
import org.apache.http.client.HttpClient; import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.http.client.config.RequestConfig; import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.http.config.Registry; import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.http.config.RegistryBuilder; import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.hc.client5.http.socket.ConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.hc.core5.http.config.Registry;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.hc.core5.http.config.RegistryBuilder;
import org.apache.hc.core5.util.Timeout;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
@@ -26,6 +27,7 @@ import org.springframework.web.client.RestTemplate;
* Blog: https://zlt2000.gitee.io * Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000 * Github: https://github.com/zlt2000
*/ */
@Configuration
@EnableConfigurationProperties(RestTemplateProperties.class) @EnableConfigurationProperties(RestTemplateProperties.class)
public class RestTemplateAutoConfigure { public class RestTemplateAutoConfigure {
@Autowired @Autowired
@@ -61,19 +63,22 @@ public class RestTemplateAutoConfigure {
// 同路由并发数20 // 同路由并发数20
connectionManager.setDefaultMaxPerRoute(restTemplateProperties.getMaxPerRoute()); connectionManager.setDefaultMaxPerRoute(restTemplateProperties.getMaxPerRoute());
RequestConfig requestConfig = RequestConfig.custom() ConnectionConfig connectConfig = ConnectionConfig.custom()
// 读超时 // 读超时
.setSocketTimeout(restTemplateProperties.getReadTimeout()) .setSocketTimeout(Timeout.ofMicroseconds(restTemplateProperties.getReadTimeout()))
// 链接超时 // 链接超时
.setConnectTimeout(restTemplateProperties.getConnectTimeout()) .setConnectTimeout(Timeout.ofMicroseconds(restTemplateProperties.getConnectTimeout()))
.build();
connectionManager.setDefaultConnectionConfig(connectConfig);
RequestConfig requestConfig = RequestConfig.custom()
// 链接不够用的等待时间 // 链接不够用的等待时间
.setConnectionRequestTimeout(restTemplateProperties.getReadTimeout()) .setConnectionRequestTimeout(Timeout.ofMicroseconds(restTemplateProperties.getReadTimeout()))
.build(); .build();
return HttpClientBuilder.create() return HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig) .setDefaultRequestConfig(requestConfig)
.setConnectionManager(connectionManager) .setConnectionManager(connectionManager)
.setRetryHandler(new DefaultHttpRequestRetryHandler(3, true))
.build(); .build();
} }
} }
@@ -11,7 +11,7 @@ import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.List; import java.util.List;
@@ -3,6 +3,7 @@ package com.central.common.lb.config;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/** /**
* RestTemplate 配置 * RestTemplate 配置
@@ -16,6 +17,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
@Setter @Setter
@Getter @Getter
@ConfigurationProperties(prefix = "zlt.rest-template") @ConfigurationProperties(prefix = "zlt.rest-template")
@Component
public class RestTemplateProperties { public class RestTemplateProperties {
/** /**
* 最大链接数 * 最大链接数
@@ -18,15 +18,6 @@
<artifactId>slf4j-api</artifactId> <artifactId>slf4j-api</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-context</artifactId>
</dependency>
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>transmittable-thread-local</artifactId> <artifactId>transmittable-thread-local</artifactId>
@@ -52,11 +43,6 @@
<artifactId>spring-web</artifactId> <artifactId>spring-web</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<optional>true</optional>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId> <artifactId>spring-boot-starter-jdbc</artifactId>
@@ -72,5 +58,9 @@
<artifactId>feign-core</artifactId> <artifactId>feign-core</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>
@@ -4,6 +4,7 @@ import com.central.log.annotation.AuditLog;
import com.central.log.model.Audit; import com.central.log.model.Audit;
import com.central.log.properties.AuditLogProperties; import com.central.log.properties.AuditLogProperties;
import com.central.log.service.IAuditService; import com.central.log.service.IAuditService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Aspect;
@@ -20,7 +21,6 @@ import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime; import java.time.LocalDateTime;
/** /**
@@ -4,6 +4,7 @@ import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/** /**
* 审计日志配置 * 审计日志配置
@@ -18,6 +19,7 @@ import org.springframework.cloud.context.config.annotation.RefreshScope;
@Getter @Getter
@ConfigurationProperties(prefix = "zlt.audit-log") @ConfigurationProperties(prefix = "zlt.audit-log")
@RefreshScope @RefreshScope
@Component
public class AuditLogProperties { public class AuditLogProperties {
/** /**
* 是否开启审计日志 * 是否开启审计日志
@@ -3,7 +3,9 @@ package com.central.log.properties;
import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariConfig;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/** /**
* 日志数据源配置 * 日志数据源配置
@@ -18,5 +20,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
@Setter @Setter
@Getter @Getter
@ConfigurationProperties(prefix = "zlt.audit-log.datasource") @ConfigurationProperties(prefix = "zlt.audit-log.datasource")
@ConditionalOnClass(HikariConfig.class)
@Component
public class LogDbProperties extends HikariConfig { public class LogDbProperties extends HikariConfig {
} }
@@ -4,6 +4,7 @@ import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/** /**
* 日志链路追踪配置 * 日志链路追踪配置
@@ -15,6 +16,7 @@ import org.springframework.cloud.context.config.annotation.RefreshScope;
@Getter @Getter
@ConfigurationProperties(prefix = "zlt.trace") @ConfigurationProperties(prefix = "zlt.trace")
@RefreshScope @RefreshScope
@Component
public class TraceProperties { public class TraceProperties {
/** /**
* 是否开启日志链路追踪 * 是否开启日志链路追踪
@@ -2,16 +2,16 @@ package com.central.log.trace;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.central.log.properties.TraceProperties; import com.central.log.properties.TraceProperties;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
/** /**
@@ -2,12 +2,10 @@ package org.slf4j;
import ch.qos.logback.classic.util.LogbackMDCAdapter; import ch.qos.logback.classic.util.LogbackMDCAdapter;
import com.alibaba.ttl.TransmittableThreadLocal; import com.alibaba.ttl.TransmittableThreadLocal;
import org.slf4j.helpers.ThreadLocalMapOfStacks;
import org.slf4j.spi.MDCAdapter; import org.slf4j.spi.MDCAdapter;
import java.util.Collections; import java.util.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/** /**
* 重构{@link LogbackMDCAdapter}类,搭配TransmittableThreadLocal实现父子线程之间的数据传递 * 重构{@link LogbackMDCAdapter}类,搭配TransmittableThreadLocal实现父子线程之间的数据传递
@@ -16,17 +14,12 @@ import java.util.Set;
* @date 2019/8/17 * @date 2019/8/17
*/ */
public class TtlMDCAdapter implements MDCAdapter { public class TtlMDCAdapter implements MDCAdapter {
private final ThreadLocal<Map<String, String>> copyOnInheritThreadLocal = new TransmittableThreadLocal<>(); final ThreadLocal<Map<String, String>> readWriteThreadLocalMap = new TransmittableThreadLocal<>();
final ThreadLocal<Map<String, String>> readOnlyThreadLocalMap = new TransmittableThreadLocal<>();
private static final int WRITE_OPERATION = 1; private final ThreadLocalMapOfStacks threadLocalMapOfDeques = new ThreadLocalMapOfStacks();
private static final int MAP_COPY_OPERATION = 2;
private static TtlMDCAdapter mtcMDCAdapter; private static TtlMDCAdapter mtcMDCAdapter;
/**
* keeps track of the last operation performed
*/
private final ThreadLocal<Integer> lastOperation = new ThreadLocal<>();
static { static {
mtcMDCAdapter = new TtlMDCAdapter(); mtcMDCAdapter = new TtlMDCAdapter();
@@ -37,60 +30,39 @@ public class TtlMDCAdapter implements MDCAdapter {
return mtcMDCAdapter; return mtcMDCAdapter;
} }
private Integer getAndSetLastOperation(int op) { public void put(String key, String val) throws IllegalArgumentException {
Integer lastOp = lastOperation.get();
lastOperation.set(op);
return lastOp;
}
private static boolean wasLastOpReadOrNull(Integer lastOp) {
return lastOp == null || lastOp == MAP_COPY_OPERATION;
}
private Map<String, String> duplicateAndInsertNewMap(Map<String, String> oldMap) {
Map<String, String> newMap = Collections.synchronizedMap(new HashMap<>());
if (oldMap != null) {
// we don't want the parent thread modifying oldMap while we are
// iterating over it
synchronized (oldMap) {
newMap.putAll(oldMap);
}
}
copyOnInheritThreadLocal.set(newMap);
return newMap;
}
/**
* Put a context value (the <code>val</code> parameter) as identified with the
* <code>key</code> parameter into the current thread's context map. Note that
* contrary to log4j, the <code>val</code> parameter can be null.
* <p/>
* <p/>
* If the current thread does not have a context map it is created as a side
* effect of this call.
*
* @throws IllegalArgumentException in case the "key" parameter is null
*/
@Override
public void put(String key, String val) {
if (key == null) { if (key == null) {
throw new IllegalArgumentException("key cannot be null"); throw new IllegalArgumentException("key cannot be null");
} }
Map<String, String> current = readWriteThreadLocalMap.get();
if (current == null) {
current = new HashMap<>();
readWriteThreadLocalMap.set(current);
}
Map<String, String> oldMap = copyOnInheritThreadLocal.get(); current.put(key, val);
Integer lastOp = getAndSetLastOperation(WRITE_OPERATION); nullifyReadOnlyThreadLocalMap();
}
if (wasLastOpReadOrNull(lastOp) || oldMap == null) { /**
Map<String, String> newMap = duplicateAndInsertNewMap(oldMap); * Get the context identified by the <code>key</code> parameter.
newMap.put(key, val); * <p/>
* <p/>
* This method has no side effects.
*/
@Override
public String get(String key) {
Map<String, String> hashMap = readWriteThreadLocalMap.get();
if ((hashMap != null) && (key != null)) {
return hashMap.get(key);
} else { } else {
oldMap.put(key, val); return null;
} }
} }
/** /**
* Remove the the context identified by the <code>key</code> parameter. * <p>Remove the context identified by the <code>key</code> parameter.
* <p/> * <p/>
*/ */
@Override @Override
@@ -98,53 +70,58 @@ public class TtlMDCAdapter implements MDCAdapter {
if (key == null) { if (key == null) {
return; return;
} }
Map<String, String> oldMap = copyOnInheritThreadLocal.get();
if (oldMap == null) { Map<String, String> current = readWriteThreadLocalMap.get();
return; if (current != null) {
current.remove(key);
nullifyReadOnlyThreadLocalMap();
}
} }
Integer lastOp = getAndSetLastOperation(WRITE_OPERATION); private void nullifyReadOnlyThreadLocalMap() {
readOnlyThreadLocalMap.set(null);
if (wasLastOpReadOrNull(lastOp)) {
Map<String, String> newMap = duplicateAndInsertNewMap(oldMap);
newMap.remove(key);
} else {
oldMap.remove(key);
} }
}
/** /**
* Clear all entries in the MDC. * Clear all entries in the MDC.
*/ */
@Override @Override
public void clear() { public void clear() {
lastOperation.set(WRITE_OPERATION); readWriteThreadLocalMap.set(null);
copyOnInheritThreadLocal.remove(); nullifyReadOnlyThreadLocalMap();
} }
/** /**
* Get the context identified by the <code>key</code> parameter. * <p>Get the current thread's MDC as a map. This method is intended to be used
* <p/> * internally.</p>
*/ *
@Override * The returned map is unmodifiable (since version 1.3.2/1.4.2).
public String get(String key) {
final Map<String, String> map = copyOnInheritThreadLocal.get();
if ((map != null) && (key != null)) {
return map.get(key);
} else {
return null;
}
}
/**
* Get the current thread's MDC as a map. This method is intended to be used
* internally.
*/ */
@SuppressWarnings("unchecked")
public Map<String, String> getPropertyMap() { public Map<String, String> getPropertyMap() {
lastOperation.set(MAP_COPY_OPERATION); Map<String, String> readOnlyMap = readOnlyThreadLocalMap.get();
return copyOnInheritThreadLocal.get(); if (readOnlyMap == null) {
Map<String, String> current = readWriteThreadLocalMap.get();
if (current != null) {
final Map<String, String> tempMap = new HashMap<>(current);
readOnlyMap = Collections.unmodifiableMap(tempMap);
readOnlyThreadLocalMap.set(readOnlyMap);
}
}
return readOnlyMap;
}
/**
* Return a copy of the current thread's context map. Returned value may be
* null.
*/
public Map getCopyOfContextMap() {
Map<String, String> readOnlyMap = getPropertyMap();
if (readOnlyMap == null) {
return null;
} else {
return new HashMap<>(readOnlyMap);
}
} }
/** /**
@@ -152,37 +129,43 @@ public class TtlMDCAdapter implements MDCAdapter {
* null. * null.
*/ */
public Set<String> getKeys() { public Set<String> getKeys() {
Map<String, String> map = getPropertyMap(); Map<String, String> readOnlyMap = getPropertyMap();
if (map != null) { if (readOnlyMap != null) {
return map.keySet(); return readOnlyMap.keySet();
} else { } else {
return null; return null;
} }
} }
/** @SuppressWarnings("unchecked")
* Return a copy of the current thread's context map. Returned value may be public void setContextMap(Map contextMap) {
* null. if (contextMap != null) {
*/ readWriteThreadLocalMap.set(new HashMap<String, String>(contextMap));
@Override
public Map<String, String> getCopyOfContextMap() {
Map<String, String> hashMap = copyOnInheritThreadLocal.get();
if (hashMap == null) {
return null;
} else { } else {
return new HashMap<>(hashMap); readWriteThreadLocalMap.set(null);
} }
nullifyReadOnlyThreadLocalMap();
}
@Override
public void pushByKey(String key, String value) {
threadLocalMapOfDeques.pushByKey(key, value);
} }
@Override @Override
public void setContextMap(Map<String, String> contextMap) { public String popByKey(String key) {
lastOperation.set(WRITE_OPERATION); return threadLocalMapOfDeques.popByKey(key);
}
Map<String, String> newMap = Collections.synchronizedMap(new HashMap<>()); @Override
newMap.putAll(contextMap); public Deque<String> getCopyOfDequeByKey(String key) {
return threadLocalMapOfDeques.getCopyOfDequeByKey(key);
}
// the newMap replaces the old one for serialisation's sake @Override
copyOnInheritThreadLocal.set(newMap); public void clearDequeByKey(String key) {
threadLocalMapOfDeques.clearDequeByKey(key);
} }
} }
@@ -23,7 +23,6 @@
<!-- 控制台日志 --> <!-- 控制台日志 -->
<appender name="StdoutAppender" class="ch.qos.logback.core.ConsoleAppender"> <appender name="StdoutAppender" class="ch.qos.logback.core.ConsoleAppender">
<withJansi>true</withJansi>
<encoder> <encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern> <pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>UTF-8</charset> <charset>UTF-8</charset>
@@ -3,6 +3,7 @@ package com.central.oss.properties;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/** /**
* @author zlt * @author zlt
@@ -14,6 +15,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
@Setter @Setter
@Getter @Getter
@ConfigurationProperties(prefix = FileServerProperties.PREFIX) @ConfigurationProperties(prefix = FileServerProperties.PREFIX)
@Component
public class FileServerProperties { public class FileServerProperties {
public static final String PREFIX = "zlt.file-server"; public static final String PREFIX = "zlt.file-server";
public static final String TYPE_FDFS = "fastdfs"; public static final String TYPE_FDFS = "fastdfs";
@@ -1,13 +1,15 @@
package com.central.common.redis; package com.central.common.redis;
import com.central.common.redis.properties.CacheManagerProperties; import com.central.common.redis.properties.CacheManagerProperties;
import org.springframework.beans.factory.annotation.Autowired; import jakarta.annotation.Resource;
import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties; import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager; import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.cache.RedisCacheManager;
@@ -28,10 +30,12 @@ import java.util.Map;
* Blog: https://zlt2000.gitee.io * Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000 * Github: https://github.com/zlt2000
*/ */
@Configuration
@ComponentScan
@EnableConfigurationProperties({RedisProperties.class, CacheManagerProperties.class}) @EnableConfigurationProperties({RedisProperties.class, CacheManagerProperties.class})
@EnableCaching @EnableCaching
public class RedisAutoConfigure { public class RedisAutoConfigure {
@Autowired @Resource
private CacheManagerProperties cacheManagerProperties; private CacheManagerProperties cacheManagerProperties;
@Bean @Bean
@@ -9,6 +9,7 @@ import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@@ -25,6 +26,7 @@ import java.util.concurrent.TimeUnit;
*/ */
@ConditionalOnClass(RedissonClient.class) @ConditionalOnClass(RedissonClient.class)
@ConditionalOnProperty(prefix = "zlt.lock", name = "lockerType", havingValue = "REDIS", matchIfMissing = true) @ConditionalOnProperty(prefix = "zlt.lock", name = "lockerType", havingValue = "REDIS", matchIfMissing = true)
@Component
public class RedissonDistributedLock implements DistributedLock { public class RedissonDistributedLock implements DistributedLock {
@Autowired @Autowired
private RedissonClient redisson; private RedissonClient redisson;
@@ -3,6 +3,7 @@ package com.central.common.redis.properties;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List; import java.util.List;
@@ -13,6 +14,7 @@ import java.util.List;
@Setter @Setter
@Getter @Getter
@ConfigurationProperties(prefix = "zlt.cache-manager") @ConfigurationProperties(prefix = "zlt.cache-manager")
@Component
public class CacheManagerProperties { public class CacheManagerProperties {
private List<CacheConfig> configs; private List<CacheConfig> configs;
@@ -10,6 +10,7 @@ import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.*; import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationUtils; import org.springframework.data.redis.serializer.SerializationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import java.util.*; import java.util.*;
@@ -25,6 +26,7 @@ import java.util.concurrent.TimeUnit;
* Github: https://github.com/zlt2000 * Github: https://github.com/zlt2000
*/ */
@Slf4j @Slf4j
@Component
public class RedisRepository { public class RedisRepository {
/** /**
* Spring Redis Template * Spring Redis Template
@@ -1,4 +1,2 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.central.common.redis.RedisAutoConfigure,\ com.central.common.redis.RedisAutoConfigure
com.central.common.redis.lock.RedissonDistributedLock,\
com.central.common.redis.template.RedisRepository
@@ -12,7 +12,7 @@ import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.reactive.function.server.ServerResponse;
import javax.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
/** /**
* Sentinel配置类 * Sentinel配置类
@@ -58,7 +58,7 @@ public class SwaggerAutoConfiguration implements BeanFactoryAware {
return new SwaggerProperties(); return new SwaggerProperties();
} }
@Bean /*@Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ConditionalOnProperty(name = "zlt.swagger.enabled", matchIfMissing = true) @ConditionalOnProperty(name = "zlt.swagger.enabled", matchIfMissing = true)
public List<Docket> createRestApi(SwaggerProperties swaggerProperties) { public List<Docket> createRestApi(SwaggerProperties swaggerProperties) {
@@ -131,7 +131,7 @@ public class SwaggerAutoConfiguration implements BeanFactoryAware {
docketList.add(docket); docketList.add(docket);
} }
return docketList; return docketList;
} }*/
/** /**
* 创建 Docket对象 * 创建 Docket对象
@@ -139,7 +139,7 @@ public class SwaggerAutoConfiguration implements BeanFactoryAware {
* @param swaggerProperties swagger配置 * @param swaggerProperties swagger配置
* @return Docket * @return Docket
*/ */
private Docket createDocket(final SwaggerProperties swaggerProperties) { /*private Docket createDocket(final SwaggerProperties swaggerProperties) {
ApiInfo apiInfo = new ApiInfoBuilder() ApiInfo apiInfo = new ApiInfoBuilder()
.title(swaggerProperties.getTitle()) .title(swaggerProperties.getTitle())
.description(swaggerProperties.getDescription()) .description(swaggerProperties.getDescription())
@@ -184,7 +184,7 @@ public class SwaggerAutoConfiguration implements BeanFactoryAware {
.build() .build()
.securitySchemes(securitySchemes()) .securitySchemes(securitySchemes())
.securityContexts(securityContexts()); .securityContexts(securityContexts());
} }*/
@Override @Override
public void setBeanFactory(BeanFactory beanFactory) { public void setBeanFactory(BeanFactory beanFactory) {
@@ -4,6 +4,7 @@ import lombok.Data;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@@ -18,6 +19,7 @@ import java.util.Map;
*/ */
@Data @Data
@ConfigurationProperties("zlt.swagger") @ConfigurationProperties("zlt.swagger")
@Component
public class SwaggerProperties { public class SwaggerProperties {
/**是否开启swagger**/ /**是否开启swagger**/
private Boolean enabled; private Boolean enabled;
@@ -3,6 +3,7 @@ package com.central.common.zookeeper.properties;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/** /**
* zookeeper配置 * zookeeper配置
@@ -17,6 +18,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
@Setter @Setter
@Getter @Getter
@ConfigurationProperties(prefix = "zlt.zookeeper") @ConfigurationProperties(prefix = "zlt.zookeeper")
@Component
public class ZookeeperProperty { public class ZookeeperProperty {
/** /**
* zk连接集群,多个用逗号隔开 * zk连接集群,多个用逗号隔开
@@ -5,9 +5,9 @@ zlt.datasource.username=root
zlt.datasource.password=1q2w3e4r zlt.datasource.password=1q2w3e4r
##### redis配置 ##### redis配置
spring.redis.host=192.168.28.130 spring.data.redis.host=192.168.28.130
spring.redis.port=6379 spring.data.redis.port=6379
spring.redis.timeout=5000 spring.data.redis.timeout=5000
##### elasticsearch配置 ##### elasticsearch配置
zlt.elasticsearch.uris=192.168.28.130:9200 zlt.elasticsearch.uris=192.168.28.130:9200
@@ -1,13 +1,13 @@
########################## 统一变量配置 ########################## ########################## 统一变量配置 ##########################
##### 数据库配置 ##### 数据库配置
zlt.datasource.ip=192.168.28.131 zlt.datasource.ip=192.168.28.130
zlt.datasource.username=root zlt.datasource.username=root
zlt.datasource.password=1q2w3e4r zlt.datasource.password=1q2w3e4r
##### redis配置 ##### redis配置
spring.redis.sentinel.master=mymaster spring.data.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=172.17.0.1 spring.data.redis.sentinel.nodes=172.17.0.1
spring.redis.password= spring.data.redis.password=
##### elasticsearch配置 ##### elasticsearch配置
zlt.elasticsearch.uris=192.168.28.130:9200 zlt.elasticsearch.uris=192.168.28.130:9200
@@ -1,13 +1,13 @@
########################## 统一变量配置 ########################## ########################## 统一变量配置 ##########################
##### 数据库配置 ##### 数据库配置
zlt.datasource.ip=192.168.28.131 zlt.datasource.ip=192.168.28.130
zlt.datasource.username=root zlt.datasource.username=root
zlt.datasource.password=1q2w3e4r zlt.datasource.password=1q2w3e4r
##### redis配置 ##### redis配置
spring.redis.host=192.168.28.130 spring.data.redis.host=192.168.28.130
spring.redis.port=6379 spring.data.redis.port=6379
spring.redis.timeout=5000 spring.data.redis.timeout=5000
##### elasticsearch配置 ##### elasticsearch配置
zlt.elasticsearch.uris=192.168.28.130:9200 zlt.elasticsearch.uris=192.168.28.130:9200
@@ -1,4 +1,6 @@
########################## application级别通用配置 ########################## ########################## application级别通用配置 ##########################
spring.main.allow-circular-references=true
##### loadbalancer配置 ##### loadbalancer配置
## 切换实例的重试 ## 切换实例的重试
spring.cloud.loadbalancer.retry.enabled=false spring.cloud.loadbalancer.retry.enabled=false
@@ -77,13 +79,13 @@ mybatis-plus.configuration.cache-enabled=false
##### redis配置 ##### redis配置
# 连接池最大连接数(使用负值表示没有限制) # 连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=8 spring.data.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) # 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.lettuce.pool.max-wait=-1 spring.data.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 # 连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=8 spring.data.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 # 连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=0 spring.data.redis.lettuce.pool.min-idle=0
##### logging配置 ##### logging配置
logging.level.com.alibaba.nacos.client.naming=warn logging.level.com.alibaba.nacos.client.naming=warn
+1
View File
@@ -24,6 +24,7 @@
<dependency> <dependency>
<groupId>com.alibaba.cloud</groupId> <groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-dubbo</artifactId> <artifactId>spring-cloud-starter-dubbo</artifactId>
<version>2021.1</version>
</dependency> </dependency>
<dependency> <dependency>
@@ -1,24 +0,0 @@
package com.rocketmq.demo.config;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.Input;
import com.rocketmq.demo.config.RocketMqConfig.MySink;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.messaging.SubscribableChannel;
/**
* @author zlt
*/
@EnableBinding({MySink.class})
public class RocketMqConfig {
public interface MySink {
@Input(Sink.INPUT)
SubscribableChannel input();
@Input("input2")
SubscribableChannel input2();
@Input("input3")
SubscribableChannel input3();
}
}
@@ -2,38 +2,38 @@ package com.rocketmq.demo.service;
import com.rocketmq.demo.model.Order; import com.rocketmq.demo.model.Order;
import org.springframework.cloud.stream.annotation.StreamListener; import org.springframework.context.annotation.Bean;
import org.springframework.cloud.stream.messaging.Sink; import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message; import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service; import java.util.function.Consumer;
/** /**
* @author zlt * @author zlt
*/ */
@Service @Configuration
public class ReceiveService { public class ReceiveService {
/** /**
* 字符串消息 * 字符串消息
*/ */
@StreamListener(Sink.INPUT) @Bean
public void receiveInput(String receiveMsg) { public Consumer<String> receiveInput() {
System.out.println("input receive: " + receiveMsg); return receiveMsg -> System.out.println("input receive: " + receiveMsg);
} }
/** /**
* 对象消息 * 对象消息
*/ */
@StreamListener("input2") @Bean
public void receiveInput2(@Payload Order order) { public Consumer<Order> receiveInput2() {
System.out.println("input2 receive: " + order); return order -> System.out.println("input2 receive: " + order);
} }
/** /**
* 通过spring.messaging对象来接收消息 * 通过spring.messaging对象来接收消息
*/ */
@StreamListener("input3") @Bean
public void receiveInput3(Message msg) { public Consumer<Message<String>> receiveInput3() {
System.out.println("input3 receive: " + msg); return msg -> System.out.println("input3 receive: " + msg);
} }
} }
@@ -6,34 +6,35 @@ spring:
name: rocketmq-produce name: rocketmq-produce
cloud: cloud:
stream: stream:
rocketmq: function:
binder: definition: receiveInput;receiveInput2;receiveInput3
# RocketMQ 服务器地址
name-server: 192.168.28.130:9876
bindings: bindings:
input2: receiveInput-in-0:
consumer:
#增加tag过滤
tags: tagObj
bindings:
input:
destination: test-topic destination: test-topic
content-type: text/plain content-type: text/plain
group: consume-group1 group: consume-group1
consumer: consumer:
#并发消费线程数 #并发消费线程数
concurrency: 20 concurrency: 20
input2: receiveInput2-in-0:
destination: test-topic destination: test-topic
content-type: application/json content-type: application/json
group: consume-group2 group: consume-group2
consumer: consumer:
#并发消费线程数 #并发消费线程数
concurrency: 20 concurrency: 20
input3: receiveInput3-in-0:
destination: test-topic destination: test-topic
content-type: text/plain content-type: text/plain
group: consume-group3 group: consume-group3
consumer: consumer:
#并发消费线程数 #并发消费线程数
concurrency: 20 concurrency: 20
rocketmq:
binder:
# RocketMQ 服务器地址
name-server: 192.168.28.130:9876
logging:
level:
org.springframework.context.support: debug
@@ -1,20 +0,0 @@
package com.rocketmq.demo.config;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.Output;
import com.rocketmq.demo.config.RocketMqConfig.MySource;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.MessageChannel;
/**
* 配置消息生产者
*
* @author zlt
*/
@EnableBinding({MySource.class})
public class RocketMqConfig {
public interface MySource {
@Output(Source.OUTPUT)
MessageChannel output();
}
}
@@ -1,37 +1,40 @@
package com.rocketmq.demo.service; package com.rocketmq.demo.service;
import org.apache.rocketmq.common.message.MessageConst; import org.apache.rocketmq.common.message.MessageConst;
import com.rocketmq.demo.config.RocketMqConfig.MySource; import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message; import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder; import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.MimeTypeUtils; import org.springframework.util.MimeTypeUtils;
import javax.annotation.Resource;
/** /**
* @author zlt * @author zlt
*/ */
@Service @Service
public class SenderService { public class SenderService {
@Autowired private final static String TEST_OUT = "test-out-0";
private MySource source;
@Resource
private StreamBridge streamBridge;
/** /**
* 发送字符消息 * 发送字符消息
*/ */
public void send(String msg) { public void send(String msg) {
source.output().send(MessageBuilder.withPayload(msg).build()); streamBridge.send(TEST_OUT, MessageBuilder.withPayload(msg).build());
} }
/** /**
* 发送带tag的对象消息 * 发送带tag的对象消息
*/ */
public <T> void sendWithTags(T msg, String tag) { public <T> void sendWithTags(T msg, String tag) {
Message message = MessageBuilder.withPayload(msg) Message<T> message = MessageBuilder.withPayload(msg)
.setHeader(MessageConst.PROPERTY_TAGS, tag) .setHeader(MessageConst.PROPERTY_TAGS, tag)
.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON) .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON)
.build(); .build();
source.output().send(message); streamBridge.send(TEST_OUT, message);
} }
} }
@@ -6,27 +6,16 @@ spring:
name: rocketmq-produce name: rocketmq-produce
cloud: cloud:
stream: stream:
bindings:
test-out-0:
destination: test-topic
content-type: application/json
group: produce-group
rocketmq: rocketmq:
binder: binder:
# RocketMQ 服务地址 # RocketMQ 服务地址
name-server: 192.168.28.130:9876 name-server: 192.168.28.130:9876
bindings:
output:
producer:
group: produce-group
output2:
producer:
group: test-group2
bindings:
output:
destination: test-topic
content-type: application/json
logging: logging:
level: level:
org: org.springframework.context.support: debug
springframework:
cloud:
stream:
binder:
rocketmq: DEBUG
@@ -1,23 +0,0 @@
package com.rocketmq.demo.config;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.SubscribableChannel;
import com.rocketmq.demo.config.RocketMqConfig.MySink;
/**
* @author zlt
*/
@EnableBinding({ Source.class, MySink.class })
public class RocketMqConfig {
public interface MySink {
@Input(Sink.INPUT)
SubscribableChannel input();
@Input("inputDlq")
SubscribableChannel inputDlq();
}
}
@@ -3,8 +3,7 @@ package com.rocketmq.demo.controller;
import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.RandomUtil;
import com.central.common.utils.IdGenerator; import com.central.common.utils.IdGenerator;
import com.rocketmq.demo.model.Order; import com.rocketmq.demo.model.Order;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message; import org.springframework.messaging.Message;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@@ -15,11 +14,11 @@ import org.springframework.web.bind.annotation.RestController;
*/ */
@RestController @RestController
public class OrderController { public class OrderController {
private final Source source; private final static String ORDER_OUT = "order-out-0";
private final StreamBridge streamBridge;
@Autowired public OrderController(StreamBridge streamBridge) {
public OrderController(Source source) { this.streamBridge = streamBridge;
this.source = source;
} }
/** /**
@@ -31,12 +30,12 @@ public class OrderController {
order.setOrderId(IdGenerator.getId()); order.setOrderId(IdGenerator.getId());
order.setOrderNo(RandomUtil.randomString(4)); order.setOrderNo(RandomUtil.randomString(4));
Message message = MessageBuilder Message<Order> message = MessageBuilder
.withPayload(order) .withPayload(order)
.setHeader("orderId", order.getOrderId()) .setHeader("orderId", order.getOrderId())
.build(); .build();
//发送半消息 //发送半消息
source.output().send(message); streamBridge.send(ORDER_OUT, message);
return "下单成功"; return "下单成功";
} }
@@ -49,13 +48,13 @@ public class OrderController {
order.setOrderId(IdGenerator.getId()); order.setOrderId(IdGenerator.getId());
order.setOrderNo(RandomUtil.randomString(4)); order.setOrderNo(RandomUtil.randomString(4));
Message message = MessageBuilder Message<Order> message = MessageBuilder
.withPayload(order) .withPayload(order)
.setHeader("orderId", order.getOrderId()) .setHeader("orderId", order.getOrderId())
.setHeader("produceError", "1") .setHeader("produceError", "1")
.build(); .build();
//发送半消息 //发送半消息
source.output().send(message); streamBridge.send(ORDER_OUT, message);
return "发送消息失败"; return "发送消息失败";
} }
@@ -68,13 +67,13 @@ public class OrderController {
order.setOrderId(IdGenerator.getId()); order.setOrderId(IdGenerator.getId());
order.setOrderNo(RandomUtil.randomString(4)); order.setOrderNo(RandomUtil.randomString(4));
Message message = MessageBuilder Message<Order> message = MessageBuilder
.withPayload(order) .withPayload(order)
.setHeader("orderId", order.getOrderId()) .setHeader("orderId", order.getOrderId())
.setHeader("consumeError", "1") .setHeader("consumeError", "1")
.build(); .build();
//发送半消息 //发送半消息
source.output().send(message); streamBridge.send(ORDER_OUT, message);
return "消费消息失败"; return "消费消息失败";
} }
} }
@@ -3,31 +3,32 @@ package com.rocketmq.demo.listener;
import com.central.common.utils.JsonUtil; import com.central.common.utils.JsonUtil;
import com.rocketmq.demo.model.Order; import com.rocketmq.demo.model.Order;
import com.rocketmq.demo.service.IOrderService; import com.rocketmq.demo.service.IOrderService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener; import jakarta.annotation.Resource;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener; import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState; import org.apache.rocketmq.client.producer.TransactionListener;
import org.springframework.beans.factory.annotation.Autowired; import org.apache.rocketmq.common.message.Message;
import org.springframework.messaging.Message; import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;
/** /**
* @author zlt * @author zlt
*/ */
@RocketMQTransactionListener(txProducerGroup = "order-tx-produce-group", corePoolSize = 5, maximumPoolSize = 10) @Component("myTransactionListener")
public class OrderTransactionListenerImpl implements RocketMQLocalTransactionListener { public class OrderTransactionListenerImpl implements TransactionListener {
@Autowired @Resource
private IOrderService orderService; private IOrderService orderService;
/** /**
* 提交本地事务 * 提交本地事务
*/ */
@Override @Override
public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) { public LocalTransactionState executeLocalTransaction(Message message, Object arg) {
//插入订单数据 //插入订单数据
String orderJson = new String(((byte[])message.getPayload())); String orderJson = new String((message.getBody()));
Order order = JsonUtil.toObject(orderJson, Order.class); Order order = JsonUtil.toObject(orderJson, Order.class);
orderService.save(order); orderService.save(order);
String produceError = (String)message.getHeaders().get("produceError"); String produceError = message.getProperty("produceError");
if ("1".equals(produceError)) { if ("1".equals(produceError)) {
System.err.println("============Exception:订单进程挂了,事务消息没提交"); System.err.println("============Exception:订单进程挂了,事务消息没提交");
//模拟插入订单后服务器挂了,没有commit事务消息 //模拟插入订单后服务器挂了,没有commit事务消息
@@ -35,7 +36,7 @@ public class OrderTransactionListenerImpl implements RocketMQLocalTransactionLis
} }
//提交事务消息 //提交事务消息
return RocketMQLocalTransactionState.COMMIT; return LocalTransactionState.COMMIT_MESSAGE;
} }
/** /**
@@ -46,13 +47,13 @@ public class OrderTransactionListenerImpl implements RocketMQLocalTransactionLis
* 否:回滚事务消息 * 否:回滚事务消息
*/ */
@Override @Override
public RocketMQLocalTransactionState checkLocalTransaction(Message message) { public LocalTransactionState checkLocalTransaction(MessageExt message) {
String orderId = (String)message.getHeaders().get("orderId"); String orderId = message.getProperty("orderId");
System.out.println("============事务回查-orderId:" + orderId); System.out.println("============事务回查-orderId:" + orderId);
//判断之前的事务是否已经提交:订单记录是否已经保存 //判断之前的事务是否已经提交:订单记录是否已经保存
int count = 1; int count = 1;
//select count(1) from t_order where order_id = ${orderId} //select count(1) from t_order where order_id = ${orderId}
System.out.println("============事务回查-订单已生成-提交事务消息"); System.out.println("============事务回查-订单已生成-提交事务消息");
return count > 0 ? RocketMQLocalTransactionState.COMMIT : RocketMQLocalTransactionState.ROLLBACK; return count > 0 ? LocalTransactionState.COMMIT_MESSAGE : LocalTransactionState.ROLLBACK_MESSAGE;
} }
} }
@@ -1,19 +1,22 @@
package com.rocketmq.demo.service.impl; package com.rocketmq.demo.service.impl;
import org.springframework.cloud.stream.annotation.StreamListener; import com.rocketmq.demo.model.Order;
import org.springframework.cloud.stream.messaging.Sink; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message; import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;
import java.util.function.Consumer;
/** /**
* 积分服务的消费者,接收到下单成功后增加积分 * 积分服务的消费者,接收到下单成功后增加积分
* *
* @author zlt * @author zlt
*/ */
@Service @Configuration
public class IntegralReceiveService { public class IntegralReceiveService {
@StreamListener(Sink.INPUT) @Bean
public void receive(Message message) { public Consumer<Message<Order>> receive() {
return message -> {
//模拟消费异常 //模拟消费异常
String consumeError = (String)message.getHeaders().get("consumeError"); String consumeError = (String)message.getHeaders().get("consumeError");
if ("1".equals(consumeError)) { if ("1".equals(consumeError)) {
@@ -23,14 +26,17 @@ public class IntegralReceiveService {
} }
System.out.println("============收到订单信息,增加积分:" + message); System.out.println("============收到订单信息,增加积分:" + message);
};
} }
/** /**
* 消费死信队列 * 消费死信队列
*/ */
@StreamListener("inputDlq") @Bean
public void receiveDlq(Message message) { public Consumer<Message<Order>> receiveDlq() {
return message -> {
String orderId = (String)message.getHeaders().get("orderId"); String orderId = (String)message.getHeaders().get("orderId");
System.err.println("============消费死信队列消息,记录日志并预警:" + orderId); System.err.println("============消费死信队列消息,记录日志并预警:" + orderId);
};
} }
} }
@@ -6,27 +6,16 @@ spring:
name: rocketmq-tx name: rocketmq-tx
cloud: cloud:
stream: stream:
rocketmq: function:
binder: definition: receive;receiveDlq
# RocketMQ 服务器地址
name-server: 192.168.28.130:9876
bindings:
output:
producer:
group: order-tx-produce-group
#开启事务消息
transactional: true
input:
consumer:
#重试失败直接进入死信队列
delayLevelWhenNextConsume: -1
bindings: bindings:
# 生产者 # 生产者
output: order-out-0:
destination: TransactionTopic destination: TransactionTopic
content-type: application/json content-type: application/json
group: order-tx-produce-group
# 消费者 # 消费者
input: receive-in-0:
destination: TransactionTopic destination: TransactionTopic
content-type: application/json content-type: application/json
group: order-tx-consume-group group: order-tx-consume-group
@@ -35,18 +24,27 @@ spring:
concurrency: 20 concurrency: 20
#重试1次 #重试1次
maxAttempts: 2 maxAttempts: 2
inputDlq: receiveDlq-in-0:
destination: '%DLQ%${spring.cloud.stream.bindings.input.group}' destination: '%DLQ%${spring.cloud.stream.bindings.receive-in-0.group}'
content-type: application/json content-type: application/json
group: order-dlq-group group: order-dlq-group
consumer: consumer:
concurrency: 20 concurrency: 20
rocketmq:
binder:
# RocketMQ 服务器地址
name-server: 192.168.28.130:9876
bindings:
order-out-0:
producer:
#开启事务消息
transactionListener: myTransactionListener
producerType: Trans
receive-in-0:
consumer:
#重试失败直接进入死信队列
delayLevelWhenNextConsume: -1
logging: logging:
level: level:
org: org.springframework.context.support: debug
springframework:
cloud:
stream:
binder:
rocketmq: DEBUG
@@ -23,7 +23,7 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import javax.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.security.interfaces.RSAPublicKey; import java.security.interfaces.RSAPublicKey;
import java.util.*; import java.util.*;
@@ -3,9 +3,10 @@ package com.sso.demo.config;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import javax.annotation.Resource; import javax.annotation.Resource;
@@ -21,16 +22,16 @@ import javax.annotation.Resource;
*/ */
@EnableOAuth2Sso @EnableOAuth2Sso
@Configuration @Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter { public class SecurityConfig {
@Value("${security.oauth2.sso.login-path:}") @Value("${security.oauth2.sso.login-path:}")
private String loginPath; private String loginPath;
@Resource @Resource
private LogoutSuccessHandler ssoLogoutSuccessHandler; private LogoutSuccessHandler ssoLogoutSuccessHandler;
@Override @Bean
public void configure(HttpSecurity http) throws Exception { public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated() http.authorizeHttpRequests().anyRequest().authenticated()
.and() .and()
.csrf().disable() .csrf().disable()
.logout() .logout()
@@ -38,5 +39,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
if (StrUtil.isNotEmpty(loginPath)) { if (StrUtil.isNotEmpty(loginPath)) {
http.formLogin().loginProcessingUrl(loginPath); http.formLogin().loginProcessingUrl(loginPath);
} }
return http.build();
} }
} }
@@ -9,8 +9,8 @@ import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
/** /**
@@ -16,7 +16,7 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import javax.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.util.*; import java.util.*;
@@ -1,12 +1,12 @@
package org.zlt.controller; package org.zlt.controller;
import com.central.oauth2.common.config.WcAuthConfigurator; import com.central.oauth2.common.config.WcAuthConfigurator;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException; import java.io.IOException;
/** /**
+20 -18
View File
@@ -10,6 +10,7 @@
<description>spring cloud gateway网关</description> <description>spring cloud gateway网关</description>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>com.zlt</groupId> <groupId>com.zlt</groupId>
<artifactId>zlt-config</artifactId> <artifactId>zlt-config</artifactId>
@@ -18,6 +19,7 @@
<groupId>com.zlt</groupId> <groupId>com.zlt</groupId>
<artifactId>zlt-log-spring-boot-starter</artifactId> <artifactId>zlt-log-spring-boot-starter</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.zlt</groupId> <groupId>com.zlt</groupId>
<artifactId>zlt-loadbalancer-spring-boot-starter</artifactId> <artifactId>zlt-loadbalancer-spring-boot-starter</artifactId>
@@ -26,26 +28,10 @@
<groupId>com.zlt</groupId> <groupId>com.zlt</groupId>
<artifactId>zlt-sentinel-spring-boot-starter</artifactId> <artifactId>zlt-sentinel-spring-boot-starter</artifactId>
</dependency> </dependency>
<!--<dependency> <dependency>
<groupId>com.alibaba.cloud</groupId> <groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId> <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>-->
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-auth-client-spring-boot-starter</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-redis-spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId> <artifactId>spring-cloud-starter-gateway</artifactId>
@@ -58,6 +44,21 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId> <artifactId>spring-boot-starter-webflux</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-redis-spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-auth-client-spring-boot-starter</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId> <artifactId>spring-cloud-starter-openfeign</artifactId>
@@ -74,7 +75,8 @@
<!-- swagger --> <!-- swagger -->
<dependency> <dependency>
<groupId>com.github.xiaoymin</groupId> <groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId> <artifactId>knife4j-gateway-spring-boot-starter</artifactId>
<version>4.2.0</version>
</dependency> </dependency>
<dependency> <dependency>
@@ -2,15 +2,15 @@ package com.central.gateway.config;
import com.central.gateway.auth.*; import com.central.gateway.auth.*;
import com.central.oauth2.common.properties.SecurityProperties; import com.central.oauth2.common.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.ReactiveAuthenticationManager; 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.SecurityWebFiltersOrder;
import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.server.resource.web.server.ServerBearerTokenAuthenticationConverter; import org.springframework.security.oauth2.server.resource.web.server.authentication.ServerBearerTokenAuthenticationConverter;
import org.springframework.security.web.server.SecurityWebFilterChain; import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.authentication.AuthenticationWebFilter; import org.springframework.security.web.server.authentication.AuthenticationWebFilter;
import org.springframework.security.web.server.authentication.ServerAuthenticationEntryPointFailureHandler; import org.springframework.security.web.server.authentication.ServerAuthenticationEntryPointFailureHandler;
@@ -25,18 +25,11 @@ import org.springframework.security.web.server.authentication.ServerAuthenticati
* Github: https://github.com/zlt2000 * Github: https://github.com/zlt2000
*/ */
@Configuration @Configuration
@EnableWebFluxSecurity
public class ResourceServerConfiguration { public class ResourceServerConfiguration {
@Autowired
private SecurityProperties securityProperties;
@Autowired
private TokenStore tokenStore;
@Autowired
private PermissionAuthManager permissionAuthManager;
@Bean @Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http
, SecurityProperties securityProperties, TokenStore tokenStore, PermissionAuthManager permissionAuthManager) {
//认证处理器 //认证处理器
ReactiveAuthenticationManager customAuthenticationManager = new CustomAuthenticationManager(tokenStore); ReactiveAuthenticationManager customAuthenticationManager = new CustomAuthenticationManager(tokenStore);
JsonAuthenticationEntryPoint entryPoint = new JsonAuthenticationEntryPoint(); JsonAuthenticationEntryPoint entryPoint = new JsonAuthenticationEntryPoint();
@@ -1,7 +1,7 @@
package com.central.gateway.error; package com.central.gateway.error;
import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.autoconfigure.web.ServerProperties;
@@ -12,16 +12,11 @@ import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler; import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer; import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.config.WebFluxConfigurer; import org.springframework.web.reactive.config.WebFluxConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver; import org.springframework.web.reactive.result.view.ViewResolver;
import java.util.Collections;
import java.util.List;
/** /**
* 自定义异常处理 * 自定义异常处理
* *
@@ -31,45 +26,28 @@ import java.util.List;
* Blog: https://zlt2000.gitee.io * Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000 * Github: https://github.com/zlt2000
*/ */
@Configuration @AutoConfiguration(before = WebFluxAutoConfiguration.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@ConditionalOnClass(WebFluxConfigurer.class) @ConditionalOnClass(WebFluxConfigurer.class)
@AutoConfigureBefore(WebFluxAutoConfiguration.class)
@EnableConfigurationProperties({ ServerProperties.class, WebProperties.class }) @EnableConfigurationProperties({ ServerProperties.class, WebProperties.class })
public class CustomErrorWebFluxAutoConfiguration { public class CustomErrorWebFluxAutoConfiguration {
private final ServerProperties serverProperties; private final ServerProperties serverProperties;
private final ApplicationContext applicationContext; public CustomErrorWebFluxAutoConfiguration(ServerProperties serverProperties) {
private final WebProperties webProperties;
private final List<ViewResolver> viewResolvers;
private final ServerCodecConfigurer serverCodecConfigurer;
public CustomErrorWebFluxAutoConfiguration(ServerProperties serverProperties,
WebProperties webProperties,
ObjectProvider<List<ViewResolver>> viewResolversProvider,
ServerCodecConfigurer serverCodecConfigurer,
ApplicationContext applicationContext) {
this.serverProperties = serverProperties; this.serverProperties = serverProperties;
this.applicationContext = applicationContext;
this.webProperties = webProperties;
this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
this.serverCodecConfigurer = serverCodecConfigurer;
} }
@Bean @Bean
@Order(Ordered.HIGHEST_PRECEDENCE) @Order(-1)
public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) { public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes,
JsonErrorWebExceptionHandler exceptionHandler = new JsonErrorWebExceptionHandler( WebProperties webProperties, ObjectProvider<ViewResolver> viewResolvers,
errorAttributes, ServerCodecConfigurer serverCodecConfigurer, ApplicationContext applicationContext) {
this.webProperties.getResources(), JsonErrorWebExceptionHandler exceptionHandler = new JsonErrorWebExceptionHandler(errorAttributes,
this.serverProperties.getError(), webProperties.getResources(), this.serverProperties.getError(), applicationContext);
this.applicationContext); exceptionHandler.setViewResolvers(viewResolvers.orderedStream().toList());
exceptionHandler.setViewResolvers(this.viewResolvers); exceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters()); exceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());
return exceptionHandler; return exceptionHandler;
} }
} }
@@ -80,7 +80,7 @@ public class JsonErrorWebExceptionHandler extends DefaultErrorWebExceptionHandle
*/ */
private Map<String, Object> responseError(ServerRequest request, Throwable error) { private Map<String, Object> responseError(ServerRequest request, Throwable error) {
String errorMessage = buildMessage(request, error); String errorMessage = buildMessage(request, error);
int httpStatus = getHttpStatus(error); int httpStatus = 200;//getHttpStatus(error);
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
map.put("resp_code", 1); map.put("resp_code", 1);
map.put("resp_msg", errorMessage); map.put("resp_msg", errorMessage);
@@ -1,13 +1,12 @@
package com.central.gateway.feign; package com.central.gateway.feign;
import com.central.common.model.SysMenu; import com.central.common.model.SysMenu;
import org.springframework.beans.factory.annotation.Autowired; import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List; import java.util.List;
import java.util.concurrent.Future; import java.util.concurrent.Future;
@@ -12,7 +12,7 @@ import java.util.List;
/** /**
* @author zlt * @author zlt
*/ */
@FeignClient(name = ServiceNameConstants.USER_SERVICE, fallbackFactory = MenuServiceFallbackFactory.class, decode404 = true) @FeignClient(name = ServiceNameConstants.USER_SERVICE, fallbackFactory = MenuServiceFallbackFactory.class, dismiss404 = true)
public interface MenuService { public interface MenuService {
/** /**
* 角色菜单列表 * 角色菜单列表
@@ -1,62 +0,0 @@
package com.central.gateway.swagger;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import java.util.HashSet;
import java.util.Set;
/**
* swagger聚合配置
*
* @author zlt
* @date 2019/10/5
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
@Getter
@ConfigurationProperties("zlt.swagger-agg")
@RefreshScope
public class SwaggerAggProperties {
/**
* Swagger返回JSON文档的接口路径(全局配置)
*/
private String apiDocsPath = "/v2/api-docs";
/**
* Swagger文档版本(全局配置)
*/
private String swaggerVersion = "2.0";
/**
* 自动生成文档的路由名称,设置了generateRoutes之后,ignoreRoutes不生效
*/
private Set<String> generateRoutes = new HashSet<>();
/**
* 不自动生成文档的路由名称,设置了generateRoutes之后,本配置不生效
*/
private Set<String> ignoreRoutes = new HashSet<>();
/**
* 是否显示该路由
*/
public boolean isShow(String route) {
int generateRoutesSize = generateRoutes.size();
int ignoreRoutesSize = ignoreRoutes.size();
if(generateRoutesSize > 0 && !generateRoutes.contains(route)) {
return false;
}
if(ignoreRoutesSize > 0 && ignoreRoutes.contains(route)) {
return false;
}
return true;
}
}
@@ -1,57 +0,0 @@
package com.central.gateway.swagger;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Optional;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import springfox.documentation.swagger.web.SecurityConfiguration;
import springfox.documentation.swagger.web.SecurityConfigurationBuilder;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger.web.UiConfigurationBuilder;
/**
* @author zlt
* @date 2019/10/5
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@RestController
@RequestMapping("/swagger-resources" )
public class SwaggerHandler {
private final SwaggerResourcesProvider swaggerResources;
@Autowired(required = false)
private SecurityConfiguration securityConfiguration;
@Autowired(required = false)
private UiConfiguration uiConfiguration;
@Autowired
public SwaggerHandler(SwaggerResourcesProvider swaggerResources) {
this.swaggerResources = swaggerResources;
}
@GetMapping("/configuration/security" )
public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration() {
return Mono.just(new ResponseEntity<>(
Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK));
}
@GetMapping("/configuration/ui" )
public Mono<ResponseEntity<UiConfiguration>> uiConfiguration() {
return Mono.just(new ResponseEntity<>(
Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));
}
@GetMapping
public Mono<ResponseEntity> swaggerResources() {
return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
}
}
@@ -1,73 +0,0 @@
package com.central.gateway.swagger;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* 跨域配置
*
* @author zlt
* @date 2019/10/5
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Component
@EnableConfigurationProperties(SwaggerAggProperties.class)
@Primary
public class SwaggerProvider implements SwaggerResourcesProvider {
private final RouteLocator routeLocator;
private final GatewayProperties gatewayProperties;
@Resource
private SwaggerAggProperties swaggerAggProperties;
public SwaggerProvider(RouteLocator routeLocator, GatewayProperties gatewayProperties) {
this.routeLocator = routeLocator;
this.gatewayProperties = gatewayProperties;
}
@Override
public List<SwaggerResource> get() {
List<SwaggerResource> resources = new ArrayList<>();
Set<String> routes = new HashSet<>();
//取出Spring Cloud Gateway中的route
routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
//结合application.yml中的路由配置,只获取有效的route节点
gatewayProperties.getRoutes().stream().filter(
routeDefinition -> (
routes.contains(routeDefinition.getId()) && swaggerAggProperties.isShow(routeDefinition.getId())
)
).forEach(routeDefinition -> routeDefinition.getPredicates().stream()
.filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
.forEach(predicateDefinition -> resources.add(
swaggerResource(
routeDefinition.getId(),
predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("/**", swaggerAggProperties.getApiDocsPath())
)
)
)
);
return resources;
}
private SwaggerResource swaggerResource(String name, String location) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(location);
swaggerResource.setSwaggerVersion(swaggerAggProperties.getSwaggerVersion());
return swaggerResource;
}
}
@@ -4,3 +4,5 @@ server:
spring: spring:
application: application:
name: sc-gateway name: sc-gateway
main:
web-application-type: reactive
@@ -1,9 +1,10 @@
package com.central.gateway.monitor.config; package com.central.gateway.monitor.config;
import de.codecentric.boot.admin.server.config.AdminServerProperties; import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
/** /**
@@ -11,22 +12,22 @@ import org.springframework.security.web.authentication.SavedRequestAwareAuthenti
* @date 2019/1/8 * @date 2019/1/8
*/ */
@Configuration @Configuration
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter { public class SecuritySecureConfig {
private final String adminContextPath; private final String adminContextPath;
public SecuritySecureConfig(AdminServerProperties adminServerProperties) { public SecuritySecureConfig(AdminServerProperties adminServerProperties) {
this.adminContextPath = adminServerProperties.getContextPath(); this.adminContextPath = adminServerProperties.getContextPath();
} }
@Override @Bean
protected void configure(HttpSecurity http) throws Exception { public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler(); SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo"); successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(adminContextPath + "/"); successHandler.setDefaultTargetUrl(adminContextPath + "/");
http.authorizeRequests() http.authorizeHttpRequests()
.antMatchers(adminContextPath + "/assets/**").permitAll() .requestMatchers(adminContextPath + "/assets/**").permitAll()
.antMatchers(adminContextPath + "/login").permitAll() .requestMatchers(adminContextPath + "/login").permitAll()
.anyRequest().authenticated() .anyRequest().authenticated()
.and() .and()
.formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and() .formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and()
@@ -38,5 +39,6 @@ public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
.disable() .disable()
.and() .and()
.csrf().disable(); .csrf().disable();
return http.build();
} }
} }
+16 -3
View File
@@ -21,10 +21,10 @@
<groupId>com.zlt</groupId> <groupId>com.zlt</groupId>
<artifactId>zlt-common-spring-boot-starter</artifactId> <artifactId>zlt-common-spring-boot-starter</artifactId>
</dependency> </dependency>
<dependency> <!--<dependency>
<groupId>com.zlt</groupId> <groupId>com.zlt</groupId>
<artifactId>zlt-auth-client-spring-boot-starter</artifactId> <artifactId>zlt-auth-client-spring-boot-starter</artifactId>
</dependency> </dependency>-->
<dependency> <dependency>
<groupId>com.zlt</groupId> <groupId>com.zlt</groupId>
<artifactId>zlt-db-spring-boot-starter</artifactId> <artifactId>zlt-db-spring-boot-starter</artifactId>
@@ -33,9 +33,14 @@
<groupId>com.zlt</groupId> <groupId>com.zlt</groupId>
<artifactId>zlt-loadbalancer-spring-boot-starter</artifactId> <artifactId>zlt-loadbalancer-spring-boot-starter</artifactId>
</dependency> </dependency>
<dependency> <!--<dependency>
<groupId>com.zlt</groupId> <groupId>com.zlt</groupId>
<artifactId>zlt-swagger2-spring-boot-starter</artifactId> <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>
<dependency> <dependency>
<groupId>com.zlt</groupId> <groupId>com.zlt</groupId>
@@ -102,6 +107,14 @@
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
@@ -1,6 +1,7 @@
package com.central; package com.central;
import com.central.common.lb.annotation.EnableFeignInterceptor; import com.central.common.lb.annotation.EnableFeignInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@@ -10,6 +11,7 @@ import org.springframework.cloud.openfeign.EnableFeignClients;
* @author zlt * @author zlt
*/ */
@EnableFeignClients @EnableFeignClients
@MapperScan(basePackages = "com.central.oauth.mapper")
@EnableFeignInterceptor @EnableFeignInterceptor
@EnableDiscoveryClient @EnableDiscoveryClient
//@EnableRedisHttpSession //@EnableRedisHttpSession
@@ -1,178 +0,0 @@
package com.central.oauth.config;
import cn.hutool.core.util.StrUtil;
import com.central.common.constant.SecurityConstants;
import com.central.common.model.SysUser;
import com.central.oauth.model.Client;
import com.central.oauth.service.IClientService;
import com.central.oauth.service.impl.RedisClientDetailsService;
import com.central.oauth.service.impl.UserDetailServiceFactory;
import com.central.oauth.utils.OidcIdTokenBuilder;
import com.central.oauth2.common.constants.IdTokenClaimNames;
import com.central.oauth2.common.properties.TokenStoreProperties;
import com.central.oauth2.common.util.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* OAuth2 授权服务器配置
*
* @author zlt
* @date 2018/10/24
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Configuration
@EnableAuthorizationServer
@AutoConfigureAfter(AuthorizationServerEndpointsConfigurer.class)
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
/**
* 注入authenticationManager 来支持 password grant type
*/
@Autowired
private AuthenticationManager authenticationManager;
@Resource
private UserDetailServiceFactory userDetailsServiceFactory;
@Autowired
private TokenStore tokenStore;
@Autowired
private WebResponseExceptionTranslator webResponseExceptionTranslator;
@Autowired
private RedisClientDetailsService clientDetailsService;
@Autowired
private RandomValueAuthorizationCodeServices authorizationCodeServices;
@Autowired
private TokenGranter tokenGranter;
/**
* 配置身份认证器,配置认证方式,TokenStore,TokenGranter,OAuth2RequestFactory
* @param endpoints
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.tokenStore(tokenStore)
.authenticationManager(authenticationManager)
//.userDetailsService(userDetailsServiceFactory.getService(SecurityConstants.DEF_ACCOUNT_TYPE))
.authorizationCodeServices(authorizationCodeServices)
.exceptionTranslator(webResponseExceptionTranslator)
.tokenGranter(tokenGranter);
}
/**
* 配置应用名称 应用id
* 配置OAuth2的客户端相关信息
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetailsService);
clientDetailsService.loadAllClientToCache();
}
/**
* 对应于配置AuthorizationServer安全认证的相关信息,创建ClientCredentialsTokenEndpointFilter核心过滤器
* @param security
*/
@Override
public void configure(AuthorizationServerSecurityConfigurer security) {
security
.tokenKeyAccess("isAuthenticated()")
.checkTokenAccess("permitAll()")
//让/oauth/token支持client_id以及client_secret作登录认证
.allowFormAuthenticationForClients();
}
@Bean
@Order(1)
public TokenEnhancer tokenEnhancer(@Autowired(required = false) KeyProperties keyProperties
, IClientService clientService
, TokenStoreProperties tokenStoreProperties) {
return (accessToken, authentication) -> {
Set<String> responseTypes = authentication.getOAuth2Request().getResponseTypes();
Map<String, Object> additionalInfo = new HashMap<>(3);
String accountType = AuthUtils.getAccountType(authentication.getUserAuthentication());
if (StrUtil.isNotEmpty(accountType)) {
additionalInfo.put(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, accountType);
}
if (responseTypes.contains(SecurityConstants.ID_TOKEN)
|| "authJwt".equals(tokenStoreProperties.getType())) {
Object principal = authentication.getPrincipal();
//增加id参数
if (principal instanceof SysUser) {
SysUser user = (SysUser)principal;
if (responseTypes.contains(SecurityConstants.ID_TOKEN)) {
//生成id_token
setIdToken(additionalInfo, authentication, keyProperties, clientService, user);
}
if ("authJwt".equals(tokenStoreProperties.getType())) {
additionalInfo.put("id", user.getId());
}
}
}
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
};
}
/**
* 生成id_token
* @param additionalInfo 存储token附加信息对象
* @param authentication 授权对象
* @param keyProperties 密钥
* @param clientService 应用service
*/
private void setIdToken(Map<String, Object> additionalInfo, OAuth2Authentication authentication
, KeyProperties keyProperties, IClientService clientService, SysUser user) {
String clientId = authentication.getOAuth2Request().getClientId();
Client client = clientService.loadClientByClientId(clientId);
if (client.getSupportIdToken()) {
String nonce = authentication.getOAuth2Request().getRequestParameters().get(IdTokenClaimNames.NONCE);
long now = System.currentTimeMillis();
long expiresAt = System.currentTimeMillis() + client.getIdTokenValiditySeconds() * 1000;
String idToken = OidcIdTokenBuilder.builder(keyProperties)
.issuer(SecurityConstants.ISS)
.issuedAt(now)
.expiresAt(expiresAt)
.subject(String.valueOf(user.getId()))
.name(user.getNickname())
.loginName(user.getUsername())
.picture(user.getHeadImgUrl())
.audience(clientId)
.nonce(nonce)
.build();
additionalInfo.put(SecurityConstants.ID_TOKEN, idToken);
}
}
}
@@ -1,167 +0,0 @@
package com.central.oauth.config;
import com.central.common.constant.SecurityConstants;
import com.central.common.properties.TenantProperties;
import com.central.oauth.filter.LoginProcessSetTenantFilter;
import com.central.oauth.handler.OauthLogoutSuccessHandler;
import com.central.oauth.password.PasswordAuthenticationProvider;
import com.central.oauth.service.impl.UserDetailServiceFactory;
import com.central.oauth.tenant.TenantAuthenticationSecurityConfig;
import com.central.oauth.tenant.TenantUsernamePasswordAuthenticationFilter;
import com.central.oauth.mobile.MobileAuthenticationSecurityConfig;
import com.central.oauth.openid.OpenIdAuthenticationSecurityConfig;
import com.central.common.config.DefaultPasswordConfig;
import com.central.oauth2.common.token.CustomWebAuthenticationDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
* spring security配置
* 在WebSecurityConfigurerAdapter不拦截oauth要开放的资源
*
* @author zlt
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Configuration
@Import(DefaultPasswordConfig.class)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationSuccessHandler authenticationSuccessHandler;
@Autowired(required = false)
private AuthenticationEntryPoint authenticationEntryPoint;
@Resource
private UserDetailServiceFactory userDetailsServiceFactory;
@Autowired
private PasswordEncoder passwordEncoder;
@Resource
private LogoutHandler logoutHandler;
@Resource
private LogoutSuccessHandler logoutSuccessHandler;
@Autowired
private OpenIdAuthenticationSecurityConfig openIdAuthenticationSecurityConfig;
@Autowired
private MobileAuthenticationSecurityConfig mobileAuthenticationSecurityConfig;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private TenantAuthenticationSecurityConfig tenantAuthenticationSecurityConfig;
@Autowired
private TenantProperties tenantProperties;
@Autowired
private AuthenticationDetailsSource<HttpServletRequest, CustomWebAuthenticationDetails> authenticationDetailsSource;
/**
* 这一步的配置是必不可少的,否则SpringBoot会自动配置一个AuthenticationManager,覆盖掉内存中的用户
* @return 认证管理对象
*/
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public TenantUsernamePasswordAuthenticationFilter tenantAuthenticationFilter(AuthenticationManager authenticationManager) {
TenantUsernamePasswordAuthenticationFilter filter = new TenantUsernamePasswordAuthenticationFilter();
filter.setAuthenticationManager(authenticationManager);
filter.setFilterProcessesUrl(SecurityConstants.OAUTH_LOGIN_PRO_URL);
filter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
filter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(SecurityConstants.LOGIN_FAILURE_PAGE));
filter.setAuthenticationDetailsSource(authenticationDetailsSource);
return filter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
//授权服务器关闭basic认证
.permitAll()
.and()
.logout()
.logoutUrl(SecurityConstants.LOGOUT_URL)
.logoutSuccessHandler(logoutSuccessHandler)
.addLogoutHandler(logoutHandler)
.clearAuthentication(true)
.and()
.apply(openIdAuthenticationSecurityConfig)
.and()
.apply(mobileAuthenticationSecurityConfig)
.and()
.addFilterBefore(new LoginProcessSetTenantFilter(), UsernamePasswordAuthenticationFilter.class)
.csrf().disable()
// 解决不允许显示在iframe的问题
.headers().frameOptions().disable().cacheControl();
if (tenantProperties.getEnable()) {
//解决不同租户单点登录时角色没变化
http.formLogin()
.loginPage(SecurityConstants.LOGIN_PAGE)
.and()
.addFilterAt(tenantAuthenticationFilter(authenticationManager), UsernamePasswordAuthenticationFilter.class)
.apply(tenantAuthenticationSecurityConfig);
} else {
http.formLogin()
.loginPage(SecurityConstants.LOGIN_PAGE)
.loginProcessingUrl(SecurityConstants.OAUTH_LOGIN_PRO_URL)
.successHandler(authenticationSuccessHandler)
.authenticationDetailsSource(authenticationDetailsSource);
}
// 基于密码 等模式可以无session,不支持授权码模式
if (authenticationEntryPoint != null) {
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
} else {
// 授权码模式单独处理,需要session的支持,此模式可以支持所有oauth2的认证
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
}
}
/**
* 全局用户信息
*/
@Override
public void configure(AuthenticationManagerBuilder auth) {
PasswordAuthenticationProvider provider = new PasswordAuthenticationProvider();
provider.setPasswordEncoder(passwordEncoder);
provider.setUserDetailsServiceFactory(userDetailsServiceFactory);
auth.authenticationProvider(provider);
}
/*public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}*/
}
@@ -1,86 +0,0 @@
package com.central.oauth.config;
import com.central.oauth.exception.ValidateCodeException;
import com.central.oauth.handler.OauthLogoutHandler;
import com.central.oauth.handler.OauthLogoutSuccessHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.*;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 认证错误处理
*
* @author zlt
*/
@Slf4j
@Configuration
public class SecurityHandlerConfig {
@Bean
public LogoutHandler logoutHandler() {
return new OauthLogoutHandler();
}
@Bean
public LogoutSuccessHandler logoutSuccessHandler() {
return new OauthLogoutSuccessHandler();
}
@Bean
public WebResponseExceptionTranslator webResponseExceptionTranslator() {
return new DefaultWebResponseExceptionTranslator() {
private static final String BAD_MSG = "坏的凭证";
private static final String BAD_MSG_EN = "Bad credentials";
@Override
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
OAuth2Exception oAuth2Exception;
if (e.getMessage() != null
&& (BAD_MSG.equals(e.getMessage()) || BAD_MSG_EN.equals(e.getMessage()))) {
oAuth2Exception = new InvalidGrantException("用户名或密码错误", e);
} else if (e instanceof InternalAuthenticationServiceException
|| e instanceof ValidateCodeException) {
oAuth2Exception = new InvalidGrantException(e.getMessage(), e);
} else if (e instanceof OAuth2Exception) {
oAuth2Exception = (OAuth2Exception)e;
} else {
oAuth2Exception = new UnsupportedResponseTypeException("服务内部错误", e);
}
ResponseEntity<OAuth2Exception> response = super.translate(oAuth2Exception);
ResponseEntity.status(oAuth2Exception.getHttpErrorCode());
response.getBody().addAdditionalInformation("resp_code", oAuth2Exception.getHttpErrorCode() + "");
response.getBody().addAdditionalInformation("resp_msg", oAuth2Exception.getMessage());
return response;
}
};
}
/**
* 登陆成功
*/
@Bean
public AuthenticationSuccessHandler loginSuccessHandler() {
return new SavedRequestAwareAuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
super.onAuthenticationSuccess(request, response, authentication);
}
};
}
}
@@ -1,179 +0,0 @@
package com.central.oauth.config;
import com.central.oauth.granter.MobilePwdGranter;
import com.central.oauth.granter.OpenIdGranter;
import com.central.oauth.granter.PwdImgCodeGranter;
import com.central.oauth.service.IValidateCodeService;
import com.central.oauth.service.impl.CustomTokenServices;
import com.central.oauth.service.impl.UserDetailServiceFactory;
import com.central.oauth.service.impl.UserDetailsByNameServiceFactoryWrapper;
import com.central.oauth2.common.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenGranter;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeTokenGranter;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.implicit.ImplicitTokenGranter;
import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;
import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.*;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* token授权模式配置类
*
* @author zlt
* @date 2020/7/11
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Configuration
public class TokenGranterConfig {
@Autowired
private ClientDetailsService clientDetailsService;
@Resource
private UserDetailServiceFactory userDetailsServiceFactory;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private TokenStore tokenStore;
@Autowired(required = false)
private List<TokenEnhancer> tokenEnhancer;
@Autowired
private IValidateCodeService validateCodeService;
@Autowired
private RandomValueAuthorizationCodeServices authorizationCodeServices;
private boolean reuseRefreshToken = true;
private AuthorizationServerTokenServices tokenServices;
private TokenGranter tokenGranter;
@Resource
private SecurityProperties securityProperties;
/**
* 授权模式
*/
@Bean
@ConditionalOnMissingBean
public TokenGranter tokenGranter(DefaultTokenServices tokenServices) {
if (tokenGranter == null) {
tokenGranter = new TokenGranter() {
private CompositeTokenGranter delegate;
@Override
public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) {
if (delegate == null) {
delegate = new CompositeTokenGranter(getAllTokenGranters(tokenServices));
}
return delegate.grant(grantType, tokenRequest);
}
};
}
return tokenGranter;
}
/**
* 所有授权模式:默认的5种模式 + 自定义的模式
*/
protected List<TokenGranter> getAllTokenGranters(DefaultTokenServices tokenServices) {
AuthorizationCodeServices authorizationCodeServices = authorizationCodeServices();
OAuth2RequestFactory requestFactory = requestFactory();
//获取默认的授权模式
List<TokenGranter> tokenGranters = getDefaultTokenGranters(tokenServices, authorizationCodeServices, requestFactory);
if (authenticationManager != null) {
// 添加密码加图形验证码模式
tokenGranters.add(new PwdImgCodeGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory, validateCodeService));
// 添加openId模式
tokenGranters.add(new OpenIdGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));
// 添加手机号加密码授权模式
tokenGranters.add(new MobilePwdGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));
}
return tokenGranters;
}
/**
* 默认的授权模式
*/
private List<TokenGranter> getDefaultTokenGranters(AuthorizationServerTokenServices tokenServices
, AuthorizationCodeServices authorizationCodeServices, OAuth2RequestFactory requestFactory) {
List<TokenGranter> tokenGranters = new ArrayList<>();
// 添加授权码模式
tokenGranters.add(new AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, clientDetailsService, requestFactory));
// 添加刷新令牌的模式
tokenGranters.add(new RefreshTokenGranter(tokenServices, clientDetailsService, requestFactory));
// 添加隐士授权模式
tokenGranters.add(new ImplicitTokenGranter(tokenServices, clientDetailsService, requestFactory));
// 添加客户端模式
tokenGranters.add(new ClientCredentialsTokenGranter(tokenServices, clientDetailsService, requestFactory));
if (authenticationManager != null) {
// 添加密码模式
tokenGranters.add(new ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));
}
return tokenGranters;
}
private AuthorizationCodeServices authorizationCodeServices() {
if (authorizationCodeServices == null) {
authorizationCodeServices = new InMemoryAuthorizationCodeServices();
}
return authorizationCodeServices;
}
private OAuth2RequestFactory requestFactory() {
return new DefaultOAuth2RequestFactory(clientDetailsService);
}
@Bean
@ConditionalOnMissingBean
protected DefaultTokenServices createDefaultTokenServices() {
DefaultTokenServices tokenServices = new CustomTokenServices(securityProperties.getAuth());
tokenServices.setTokenStore(tokenStore);
tokenServices.setSupportRefreshToken(true);
tokenServices.setReuseRefreshToken(reuseRefreshToken);
tokenServices.setClientDetailsService(clientDetailsService);
tokenServices.setTokenEnhancer(tokenEnhancer());
addUserDetailsService(tokenServices);
return tokenServices;
}
private TokenEnhancer tokenEnhancer() {
if (tokenEnhancer != null) {
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(tokenEnhancer);
return tokenEnhancerChain;
}
return null;
}
private void addUserDetailsService(DefaultTokenServices tokenServices) {
if (this.userDetailsServiceFactory != null) {
PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceFactoryWrapper<>(this.userDetailsServiceFactory));
tokenServices.setAuthenticationManager(new ProviderManager(Collections.singletonList(provider)));
}
}
}
@@ -1,12 +1,14 @@
package com.central.oauth.config; package com.central.oauth.config;
import com.central.common.config.DefaultWebMvcConfig; /*import com.central.common.config.DefaultWebMvcConfig;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;*/
/** /**
* @author zlt * @author zlt
* @date 2019/8/5 * @date 2019/8/5
*/ */
/*
@Configuration @Configuration
public class WebMvcConfig extends DefaultWebMvcConfig { public class WebMvcConfig extends DefaultWebMvcConfig {
} }
*/
@@ -6,8 +6,8 @@ import com.central.oauth.dto.ClientDto;
import com.central.oauth.model.Client; import com.central.oauth.model.Client;
import com.central.oauth.service.IClientService; import com.central.oauth.service.IClientService;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import io.swagger.annotations.Api; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.annotations.ApiOperation; import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@@ -22,7 +22,7 @@ import java.util.Map;
* Blog: https://zlt2000.gitee.io * Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000 * Github: https://github.com/zlt2000
*/ */
@Api(tags = "应用") @Tag(name = "应用")
@RestController @RestController
@RequestMapping("/clients") @RequestMapping("/clients")
public class ClientController { public class ClientController {
@@ -30,32 +30,32 @@ public class ClientController {
private IClientService clientService; private IClientService clientService;
@GetMapping("/list") @GetMapping("/list")
@ApiOperation(value = "应用列表") @Operation(summary = "应用列表")
public PageResult<Client> list(@RequestParam Map<String, Object> params) { public PageResult<Client> list(@RequestParam Map<String, Object> params) {
return clientService.listClient(params, true); return clientService.listClient(params, true);
} }
@GetMapping("/{id}") @GetMapping("/{id}")
@ApiOperation(value = "根据id获取应用") @Operation(summary = "根据id获取应用")
public Client get(@PathVariable Long id) { public Client get(@PathVariable Long id) {
return clientService.getById(id); return clientService.getById(id);
} }
@GetMapping("/all") @GetMapping("/all")
@ApiOperation(value = "所有应用") @Operation(summary = "所有应用")
public Result<List<Client>> allClient() { public Result<List<Client>> allClient() {
PageResult<Client> page = clientService.listClient(Maps.newHashMap(), false); PageResult<Client> page = clientService.listClient(Maps.newHashMap(), false);
return Result.succeed(page.getData()); return Result.succeed(page.getData());
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
@ApiOperation(value = "删除应用") @Operation(summary = "删除应用")
public void delete(@PathVariable Long id) { public void delete(@PathVariable Long id) {
clientService.delClient(id); clientService.delClient(id);
} }
@PostMapping("/saveOrUpdate") @PostMapping("/saveOrUpdate")
@ApiOperation(value = "保存或者修改应用") @Operation(summary = "保存或者修改应用")
public Result saveOrUpdate(@RequestBody ClientDto clientDto) throws Exception { public Result saveOrUpdate(@RequestBody ClientDto clientDto) throws Exception {
return clientService.saveClient(clientDto); return clientService.saveClient(clientDto);
} }
@@ -1,73 +0,0 @@
package com.central.oauth.controller;
import com.central.common.constant.SecurityConstants;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.oauth.model.TokenVo;
import com.central.oauth.service.ITokensService;
import com.central.oauth2.common.util.AuthUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.stream.Collectors;
/**
* token管理接口
*
* @author zlt
*/
@Api(tags = "Token管理")
@Slf4j
@RestController
@RequestMapping("/tokens")
public class TokensController {
@Resource
private ITokensService tokensService;
@Resource
private ClientDetailsService clientDetailsService;
@Resource
private PasswordEncoder passwordEncoder;
@GetMapping("")
@ApiOperation(value = "token列表")
public PageResult<TokenVo> list(@RequestParam Map<String, Object> params, String tenantId) {
return tokensService.listTokens(params, tenantId);
}
@GetMapping("/key")
@ApiOperation(value = "获取jwt密钥")
public Result<String> key(HttpServletRequest request) {
try {
String[] clientArr = AuthUtils.extractClient(request);
ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientArr[0]);
if (clientDetails == null || !passwordEncoder.matches(clientArr[1], clientDetails.getClientSecret())) {
throw new BadCredentialsException("应用ID或密码错误");
}
} catch (AuthenticationException ae) {
return Result.failed(ae.getMessage());
}
org.springframework.core.io.Resource res = new ClassPathResource(SecurityConstants.RSA_PUBLIC_KEY);
try (BufferedReader br = new BufferedReader(new InputStreamReader(res.getInputStream()))) {
return Result.succeed(br.lines().collect(Collectors.joining("\n")));
} catch (IOException ioe) {
log.error("key error", ioe);
return Result.failed(ioe.getMessage());
}
}
}
@@ -14,6 +14,7 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/** /**
* 验证码提供 * 验证码提供
@@ -31,7 +32,7 @@ public class ValidateCodeController {
* @throws Exception * @throws Exception
*/ */
@GetMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{deviceId}") @GetMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{deviceId}")
public void createCode(@PathVariable String deviceId, HttpServletResponse response) throws Exception { public void createCode(@PathVariable String deviceId, HttpServletResponse response) throws IOException {
Assert.notNull(deviceId, "机器码不能为空"); Assert.notNull(deviceId, "机器码不能为空");
// 设置请求头为输出图片类型 // 设置请求头为输出图片类型
CaptchaUtil.setHeader(response); CaptchaUtil.setHeader(response);
@@ -54,7 +55,7 @@ public class ValidateCodeController {
*/ */
@ResponseBody @ResponseBody
@GetMapping(SecurityConstants.MOBILE_VALIDATE_CODE_URL_PREFIX + "/{mobile}") @GetMapping(SecurityConstants.MOBILE_VALIDATE_CODE_URL_PREFIX + "/{mobile}")
public Result createCode(@PathVariable String mobile) { public Result<String> createCode(@PathVariable String mobile) {
Assert.notNull(mobile, "手机号不能为空"); Assert.notNull(mobile, "手机号不能为空");
return validateCodeService.sendSmsCode(mobile); return validateCodeService.sendSmsCode(mobile);
} }
@@ -1,66 +0,0 @@
package com.central.oauth.filter;
import cn.hutool.core.util.ArrayUtil;
import com.central.common.constant.SecurityConstants;
import com.central.common.context.TenantContextHolder;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.savedrequest.DefaultSavedRequest;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 设置租户id过滤器
*
* @author zlt
* @date 2020/3/29
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class LoginProcessSetTenantFilter extends OncePerRequestFilter {
private static final String SAVED_REQUEST = "SPRING_SECURITY_SAVED_REQUEST";
private RequestMatcher requiresAuthenticationRequestMatcher;
public LoginProcessSetTenantFilter() {
requiresAuthenticationRequestMatcher = new AntPathRequestMatcher(SecurityConstants.OAUTH_LOGIN_PRO_URL, HttpMethod.POST.name());
}
/**
* 返回true代表不执行过滤器,false代表执行
*/
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
if (requiresAuthentication(request)) {
return false;
}
return true;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
try {
DefaultSavedRequest savedRequest = (DefaultSavedRequest)request.getSession().getAttribute(SAVED_REQUEST);
if (savedRequest != null) {
String[] clientIds = savedRequest.getParameterValues("client_id");
if (ArrayUtil.isNotEmpty(clientIds)) {
//保存租户id
TenantContextHolder.setTenant(clientIds[0]);
}
}
chain.doFilter(request, response);
} finally {
TenantContextHolder.clear();
}
}
private boolean requiresAuthentication(HttpServletRequest request) {
return requiresAuthenticationRequestMatcher.matches(request);
}
}
@@ -1,93 +0,0 @@
package com.central.oauth.filter;
import com.central.common.constant.SecurityConstants;
import com.central.common.context.TenantContextHolder;
import com.central.common.model.Result;
import com.central.oauth.handler.decryptParamHandler.IDecryptParamHandler;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.security.Principal;
import java.util.Map;
/**
* oauth-token拦截器
* 1. 赋值租户
* 2. 统一返回token格式
*
* @author zlt
* @date 2020/3/29
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@Component
@Aspect
public class OauthTokenAspect {
@Resource
private IDecryptParamHandler decryptParamHandler;
@Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
public Object handleControllerMethod(ProceedingJoinPoint joinPoint) throws Throwable {
try {
Object[] args = joinPoint.getArgs();
Principal principal = (Principal) args[0];
if (!(principal instanceof Authentication)) {
throw new OAuth2Exception(
"There is no client authentication. Try adding an appropriate authentication filter.");
}
String clientId = getClientId(principal);
Map<String, String> parameters = (Map<String, String>) args[1];
//解密参数
decryptParamHandler.decryptParams(parameters);
String grantType = parameters.get(OAuth2Utils.GRANT_TYPE);
if (!parameters.containsKey(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME)) {
parameters.put(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, SecurityConstants.DEF_ACCOUNT_TYPE);
}
//保存租户id
TenantContextHolder.setTenant(clientId);
Object proceed = joinPoint.proceed(args);
if (SecurityConstants.AUTHORIZATION_CODE.equals(grantType)) {
/*
如果使用 @EnableOAuth2Sso 注解不能修改返回格式,否则授权码模式可以统一改
因为本项目的 sso-demo/ss-sso 里面使用了 @EnableOAuth2Sso 注解,所以这里就不修改授权码模式的token返回值了
*/
return proceed;
} else {
ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>) proceed;
OAuth2AccessToken body = responseEntity.getBody();
return ResponseEntity
.status(HttpStatus.OK)
.body(Result.succeed(body));
}
} finally {
TenantContextHolder.clear();
}
}
private String getClientId(Principal principal) {
Authentication client = (Authentication) principal;
if (!client.isAuthenticated()) {
throw new OAuth2Exception("The client is not authenticated.");
}
String clientId = client.getName();
if (client instanceof OAuth2Authentication) {
clientId = ((OAuth2Authentication) client).getOAuth2Request().getClientId();
}
return clientId;
}
}
@@ -1,53 +0,0 @@
package com.central.oauth.granter;
import com.central.oauth2.common.token.MobileAuthenticationToken;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* openId授权模式
*
* @author zlt
* @date 2020/7/11
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class MobilePwdGranter extends AbstractTokenGranter {
private static final String GRANT_TYPE = "mobile_password";
private final AuthenticationManager authenticationManager;
public MobilePwdGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices
, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
this.authenticationManager = authenticationManager;
}
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
String mobile = parameters.get("mobile");
String password = parameters.get("password");
// Protect from downstream leaks of password
parameters.remove("password");
Authentication userAuth = new MobileAuthenticationToken(mobile, password);
((AbstractAuthenticationToken) userAuth).setDetails(parameters);
userAuth = authenticationManager.authenticate(userAuth);
if (userAuth == null || !userAuth.isAuthenticated()) {
throw new InvalidGrantException("Could not authenticate mobile: " + mobile);
}
OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
return new OAuth2Authentication(storedOAuth2Request, userAuth);
}
}
@@ -1,49 +0,0 @@
package com.central.oauth.granter;
import com.central.oauth2.common.token.OpenIdAuthenticationToken;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* openId授权模式
*
* @author zlt
* @date 2020/7/11
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class OpenIdGranter extends AbstractTokenGranter {
private static final String GRANT_TYPE = "openId";
private final AuthenticationManager authenticationManager;
public OpenIdGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices
, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
this.authenticationManager = authenticationManager;
}
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
String openId = parameters.get("openId");
Authentication userAuth = new OpenIdAuthenticationToken(openId);
((AbstractAuthenticationToken) userAuth).setDetails(parameters);
userAuth = authenticationManager.authenticate(userAuth);
if (userAuth == null || !userAuth.isAuthenticated()) {
throw new InvalidGrantException("Could not authenticate openId: " + openId);
}
OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
return new OAuth2Authentication(storedOAuth2Request, userAuth);
}
}

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