Browse Source

项目初始化

master
qiujinyang 2 years ago
parent
commit
918a876961
100 changed files with 4305 additions and 0 deletions
  1. +159
    -0
      doc/tuoheng_cloud.sql
  2. +5
    -0
      doc/接口文档.txt
  3. +111
    -0
      pom.xml
  4. +157
    -0
      tuoheng-auth/pom.xml
  5. +22
    -0
      tuoheng-auth/src/main/java/com/tuoheng/auth/THAuthApplication.java
  6. +127
    -0
      tuoheng-auth/src/main/java/com/tuoheng/auth/config/AuthorizationServerConfig.java
  7. +58
    -0
      tuoheng-auth/src/main/java/com/tuoheng/auth/config/SecurityConfig.java
  8. +20
    -0
      tuoheng-auth/src/main/java/com/tuoheng/auth/controller/UserController.java
  9. +33
    -0
      tuoheng-auth/src/main/java/com/tuoheng/auth/exception/OAuth2WebResponseExceptionTranslator.java
  10. +91
    -0
      tuoheng-auth/src/main/java/com/tuoheng/auth/service/OAuthUserDetailsService.java
  11. +20
    -0
      tuoheng-auth/src/main/resources/application-dev.yml
  12. +20
    -0
      tuoheng-auth/src/main/resources/application-local.yml
  13. +20
    -0
      tuoheng-auth/src/main/resources/application-prod.yml
  14. +20
    -0
      tuoheng-auth/src/main/resources/application-test.yml
  15. +16
    -0
      tuoheng-auth/src/main/resources/application.yml
  16. +20
    -0
      tuoheng-auth/target/classes/WEB-INF/classes/application-local.yml
  17. +20
    -0
      tuoheng-auth/target/classes/application-dev.yml
  18. +20
    -0
      tuoheng-auth/target/classes/application-local.yml
  19. +20
    -0
      tuoheng-auth/target/classes/application-prod.yml
  20. +20
    -0
      tuoheng-auth/target/classes/application-test.yml
  21. +16
    -0
      tuoheng-auth/target/classes/application.yml
  22. BIN
      tuoheng-auth/target/classes/com/tuoheng/auth/THAuthApplication.class
  23. BIN
      tuoheng-auth/target/classes/com/tuoheng/auth/config/AuthorizationServerConfig$1.class
  24. BIN
      tuoheng-auth/target/classes/com/tuoheng/auth/config/AuthorizationServerConfig.class
  25. BIN
      tuoheng-auth/target/classes/com/tuoheng/auth/config/SecurityConfig.class
  26. BIN
      tuoheng-auth/target/classes/com/tuoheng/auth/controller/UserController.class
  27. BIN
      tuoheng-auth/target/classes/com/tuoheng/auth/exception/OAuth2WebResponseExceptionTranslator.class
  28. BIN
      tuoheng-auth/target/classes/com/tuoheng/auth/service/OAuthUserDetailsService.class
  29. +207
    -0
      tuoheng-auth/tuoheng-auth.iml
  30. +19
    -0
      tuoheng-common/pom.xml
  31. +69
    -0
      tuoheng-common/tuoheng-common-core/pom.xml
  32. +6
    -0
      tuoheng-common/tuoheng-common-core/src/main/java/com/tuoheng/common/core/DemoController.java
  33. +8
    -0
      tuoheng-common/tuoheng-common-core/src/main/java/com/tuoheng/common/core/common/BaseController.java
  34. +58
    -0
      tuoheng-common/tuoheng-common-core/src/main/java/com/tuoheng/common/core/common/BaseEntity.java
  35. +19
    -0
      tuoheng-common/tuoheng-common-core/src/main/java/com/tuoheng/common/core/common/BaseQuery.java
  36. +209
    -0
      tuoheng-common/tuoheng-common-core/src/main/java/com/tuoheng/common/core/common/BaseServiceImpl.java
  37. +109
    -0
      tuoheng-common/tuoheng-common-core/src/main/java/com/tuoheng/common/core/common/IBaseService.java
  38. +136
    -0
      tuoheng-common/tuoheng-common-core/src/main/java/com/tuoheng/common/core/utils/DateUtils.java
  39. +99
    -0
      tuoheng-common/tuoheng-common-core/src/main/java/com/tuoheng/common/core/utils/JsonResult.java
  40. +367
    -0
      tuoheng-common/tuoheng-common-core/src/main/java/com/tuoheng/common/core/utils/StringUtils.java
  41. BIN
      tuoheng-common/tuoheng-common-core/target/classes/com/tuoheng/common/core/DemoController.class
  42. BIN
      tuoheng-common/tuoheng-common-core/target/classes/com/tuoheng/common/core/common/BaseController.class
  43. BIN
      tuoheng-common/tuoheng-common-core/target/classes/com/tuoheng/common/core/common/BaseEntity.class
  44. BIN
      tuoheng-common/tuoheng-common-core/target/classes/com/tuoheng/common/core/common/BaseQuery.class
  45. BIN
      tuoheng-common/tuoheng-common-core/target/classes/com/tuoheng/common/core/common/BaseServiceImpl.class
  46. BIN
      tuoheng-common/tuoheng-common-core/target/classes/com/tuoheng/common/core/common/IBaseService.class
  47. BIN
      tuoheng-common/tuoheng-common-core/target/classes/com/tuoheng/common/core/utils/DateUtils.class
  48. BIN
      tuoheng-common/tuoheng-common-core/target/classes/com/tuoheng/common/core/utils/JsonResult.class
  49. BIN
      tuoheng-common/tuoheng-common-core/target/classes/com/tuoheng/common/core/utils/StringUtils.class
  50. +113
    -0
      tuoheng-common/tuoheng-common-core/tuoheng-common-core.iml
  51. +53
    -0
      tuoheng-common/tuoheng-common-security/pom.xml
  52. +25
    -0
      tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/annotation/EnableCustomConfig.java
  53. +21
    -0
      tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/annotation/EnableTHFeignClients.java
  54. +19
    -0
      tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/config/OAuth2FeignConfig.java
  55. +88
    -0
      tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/config/ResourceServerConfig.java
  56. +33
    -0
      tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/constant/SecurityConstant.java
  57. +27
    -0
      tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/entity/SecurityUser.java
  58. +26
    -0
      tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/interceptor/OAuth2FeignRequestInterceptor.java
  59. +62
    -0
      tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/security/CustomUserAuthenticationConverter.java
  60. +34
    -0
      tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/security/OAuthAccessDeniedHandler.java
  61. +40
    -0
      tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/security/OAuthAuthExceptionEntryPoint.java
  62. +23
    -0
      tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/security/SecurityImportBeanDefinitionRegistrar.java
  63. +99
    -0
      tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/utils/JsonResult.java
  64. +78
    -0
      tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/utils/SecurityUtils.java
  65. BIN
      tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/annotation/EnableCustomConfig.class
  66. BIN
      tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/annotation/EnableTHFeignClients.class
  67. BIN
      tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/config/OAuth2FeignConfig.class
  68. BIN
      tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/config/ResourceServerConfig.class
  69. BIN
      tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/constant/SecurityConstant.class
  70. BIN
      tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/entity/SecurityUser.class
  71. BIN
      tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/interceptor/OAuth2FeignRequestInterceptor.class
  72. BIN
      tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/security/CustomUserAuthenticationConverter.class
  73. BIN
      tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/security/OAuthAccessDeniedHandler.class
  74. BIN
      tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/security/OAuthAuthExceptionEntryPoint.class
  75. BIN
      tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/security/SecurityImportBeanDefinitionRegistrar.class
  76. BIN
      tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/utils/JsonResult.class
  77. BIN
      tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/utils/SecurityUtils.class
  78. +159
    -0
      tuoheng-common/tuoheng-common-security/tuoheng-common-security.iml
  79. +58
    -0
      tuoheng-common/tuoheng-common.iml
  80. +87
    -0
      tuoheng-eureka/pom.xml
  81. +16
    -0
      tuoheng-eureka/src/main/java/com/tuoheng/eureka/THEurekaApplication.java
  82. +26
    -0
      tuoheng-eureka/src/main/resources/application.yml
  83. +26
    -0
      tuoheng-eureka/target/classes/WEB-INF/classes/application.yml
  84. +26
    -0
      tuoheng-eureka/target/classes/application.yml
  85. BIN
      tuoheng-eureka/target/classes/com/tuoheng/eureka/THEurekaApplication.class
  86. +147
    -0
      tuoheng-eureka/tuoheng-eureka.iml
  87. +151
    -0
      tuoheng-gateway/pom.xml
  88. +18
    -0
      tuoheng-gateway/src/main/java/com/tuoheng/gateway/THGatewayApplication.java
  89. +36
    -0
      tuoheng-gateway/src/main/java/com/tuoheng/gateway/config/GatewayCorsConfig.java
  90. +34
    -0
      tuoheng-gateway/src/main/java/com/tuoheng/gateway/config/GatewayExceptionConfig.java
  91. +107
    -0
      tuoheng-gateway/src/main/java/com/tuoheng/gateway/config/GatewayFilterConfig.java
  92. +10
    -0
      tuoheng-gateway/src/main/java/com/tuoheng/gateway/constant/RSAConstant.java
  93. +22
    -0
      tuoheng-gateway/src/main/java/com/tuoheng/gateway/controller/FallBackController.java
  94. +55
    -0
      tuoheng-gateway/src/main/java/com/tuoheng/gateway/controller/TestController.java
  95. +29
    -0
      tuoheng-gateway/src/main/java/com/tuoheng/gateway/exception/AbstractExceptionHandler.java
  96. +94
    -0
      tuoheng-gateway/src/main/java/com/tuoheng/gateway/exception/GatewayExceptionHandler.java
  97. +14
    -0
      tuoheng-gateway/src/main/java/com/tuoheng/gateway/exception/RSAException.java
  98. +60
    -0
      tuoheng-gateway/src/main/java/com/tuoheng/gateway/utils/FilterUtils.java
  99. +88
    -0
      tuoheng-gateway/src/main/java/com/tuoheng/gateway/utils/RSAUtils.java
  100. +0
    -0
      tuoheng-gateway/src/main/resources/application-dev.yml

+ 159
- 0
doc/tuoheng_cloud.sql
File diff suppressed because it is too large
View File


+ 5
- 0
doc/接口文档.txt View File

@@ -0,0 +1,5 @@
1、登录接口:
http://localhost:9011/api/auth/oauth/token?client_id=web&client_secret=123456&grant_type=password&scope=server&username=admin&password=123456&captcha=520&key

2、刷新接口:
http://localhost:9011/api/auth/oauth/token?grant_type=refresh_token&refresh_token=0a8b27fa-0f48-4a04-8112-bdb0ca529b7b

+ 111
- 0
pom.xml View File

@@ -0,0 +1,111 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<modules>
<module>tuoheng-eureka</module>
<module>tuoheng-gateway</module>
<module>tuoheng-auth</module>
<module>tuoheng-common</module>
<module>tuoheng-service</module>
<module>tuoheng-service-api</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.tuoheng</groupId>
<artifactId>tuoheng</artifactId>
<version>1.0.0</version>
<name>tuoheng</name>
<description>tuoheng</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>2021.0.3</spring-cloud.version>
<tuoheng.version>1.0.0</tuoheng.version>
<fastjson.version>1.2.76</fastjson.version>
<poi.version>3.17</poi.version>
<commons.io.version>2.5</commons.io.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- 核心模块依赖 -->
<dependency>
<groupId>com.tuoheng</groupId>
<artifactId>tuoheng-common-core</artifactId>
<version>${tuoheng.version}</version>
</dependency>
<!-- 安全认证依赖 -->
<dependency>
<groupId>com.tuoheng</groupId>
<artifactId>tuoheng-common-security</artifactId>
<version>${tuoheng.version}</version>
</dependency>
<!-- 系统服务API接口层模块依赖 -->
<dependency>
<groupId>com.tuoheng</groupId>
<artifactId>tuoheng-system-api</artifactId>
<version>${tuoheng.version}</version>
</dependency>
<!-- Excel工具 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<!-- JSON 解析器和生成器 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!-- IO常用工具类 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
</dependency>
</dependencies>
</dependencyManagement>

<!-- <build>-->
<!-- <plugins>-->
<!-- <plugin>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-maven-plugin</artifactId>-->
<!-- </plugin>-->
<!-- </plugins>-->
<!-- </build>-->

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>

</project>

+ 157
- 0
tuoheng-auth/pom.xml View File

@@ -0,0 +1,157 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>tuoheng</artifactId>
<groupId>com.tuoheng</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>tuoheng-auth</artifactId>

<!-- 依赖管理 -->
<dependencies>
<!-- 安全认证依赖 -->
<dependency>
<groupId>com.tuoheng</groupId>
<artifactId>tuoheng-common-security</artifactId>
</dependency>
<!-- 系统API接口模块依赖 -->
<dependency>
<groupId>com.tuoheng</groupId>
<artifactId>tuoheng-system-api</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

<!-- MySql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 引入阿里数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<!-- &lt;!&ndash; SpringCloud Netflix Hystrix &ndash;&gt;-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>

<profiles>
<!-- 本地开发环境 -->
<profile>
<id>local</id>
<properties>
<package.environment>local</package.environment>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<!-- 开发环境 -->
<profile>
<id>dev</id>
<properties>
<package.environment>dev</package.environment>
</properties>
</profile>
<!-- 测试环境 -->
<profile>
<id>test</id>
<properties>
<package.environment>test</package.environment>
</properties>
</profile>
<!-- 生产环境 -->
<profile>
<id>prod</id>
<properties>
<package.environment>prod</package.environment>
</properties>
</profile>
</profiles>

<build>
<finalName>tuoheng-auth</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>

<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.*</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>

<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<targetPath>WEB-INF/classes</targetPath>
<includes>
<include>application-${package.environment}.yml</include>
</includes>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.1.11.RELEASE</version>
<configuration>
<finalName>${project.build.finalName}</finalName>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>

</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

</project>

+ 22
- 0
tuoheng-auth/src/main/java/com/tuoheng/auth/THAuthApplication.java View File

@@ -0,0 +1,22 @@
package com.tuoheng.auth;

import com.tuoheng.common.security.annotation.EnableCustomConfig;
import com.tuoheng.common.security.annotation.EnableTHFeignClients;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
@EnableTHFeignClients
@EnableCustomConfig
//@MapperScan("com.tuoheng.**.**.mapper")
public class THAuthApplication {

public static void main(String[] args) {
SpringApplication.run(THAuthApplication.class, args);
System.out.println("(♥◠‿◠)ノ゙ 微服务【认证服务】启动成功 ლ(´ڡ`ლ)゙");
}

}

+ 127
- 0
tuoheng-auth/src/main/java/com/tuoheng/auth/config/AuthorizationServerConfig.java View File

@@ -0,0 +1,127 @@
package com.tuoheng.auth.config;

import com.tuoheng.auth.exception.OAuth2WebResponseExceptionTranslator;
import com.tuoheng.common.security.constant.SecurityConstant;
import com.tuoheng.common.security.entity.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
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.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import javax.sql.DataSource;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
* 授权配置信息类
* 声明TokenStore实现和ClientDetails的实现
*/
@Configuration
// 开启认证授权中心
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private TokenEnhancer tokenEnhancer;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private DataSource dataSource;

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// super.configure(clients);
clients.withClientDetails(clientDetails());
}

@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
// super.configure(security);
security.tokenKeyAccess("permitAll()");
security.checkTokenAccess("isAuthenticated()");
// 允许表单认证,允许客户端使用client_id和client_secret获取token
security.allowFormAuthenticationForClients();
}

/**
* 配置授权(authorization)以及令牌(token)的访问端点和令牌服务(token services)
*
* @param endpoints
* @throws Exception
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// super.configure(endpoints);
// 指定认证管理器
endpoints.authenticationManager(authenticationManager);
// 请求方式
endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
// 指定token存储位置
endpoints.tokenStore(tokenStore());
// 自定义生成令牌
endpoints.tokenEnhancer(tokenEnhancer);
// 用户账号密码认证
endpoints.userDetailsService(userDetailsService);
/**
* refresh_token有两种使用方式:重复使用(true)、非重复使用(false),默认为true
* 1.重复使用:access_token过期刷新时, refresh_token过期时间未改变,仍以初次生成的时间为准
* 2.非重复使用:access_token过期刷新时, refresh_token过期时间延续,在refresh_token有效期内刷新而无需失效再次登录
*/
endpoints.reuseRefreshTokens(false);
// 自定义异常处理
endpoints.exceptionTranslator(new OAuth2WebResponseExceptionTranslator());
}

@Bean
public ClientDetailsService clientDetails() {
return new JdbcClientDetailsService(dataSource);
}

@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}

/**
* 自定义令牌
*
* @return
*/
@Bean
public TokenEnhancer tokenEnhancer() {
return new TokenEnhancer() {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
if (accessToken instanceof DefaultOAuth2AccessToken) {
DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken;
token.setExpiration(new Date(System.currentTimeMillis() + 86400 * 7 * 1000L));
SecurityUser user = (SecurityUser) authentication.getUserAuthentication().getPrincipal();
Map<String, Object> additionalInformation = new LinkedHashMap<String, Object>();
additionalInformation.put(SecurityConstant.DETAILS_USERNAME, authentication.getName());
additionalInformation.put(SecurityConstant.DETAILS_USER_ID, user.getUserId());
token.setAdditionalInformation(additionalInformation);
}
return accessToken;
}
};
}
}

+ 58
- 0
tuoheng-auth/src/main/java/com/tuoheng/auth/config/SecurityConfig.java View File

@@ -0,0 +1,58 @@
package com.tuoheng.auth.config;

import org.springframework.beans.factory.annotation.Autowired;
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.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
* 安全服务配置类
*/
@Configuration
@Order(2)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
// super.configure(http);
http.authorizeRequests()
.antMatchers("/oauth/**", "/user/**")
.permitAll()
// 其他所有的请求都需要登录认证
.anyRequest().authenticated()
.and().csrf().disable();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// super.configure(auth);
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}

+ 20
- 0
tuoheng-auth/src/main/java/com/tuoheng/auth/controller/UserController.java View File

@@ -0,0 +1,20 @@
package com.tuoheng.auth.controller;


import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
* <p>
* 后台用户管理表 前端控制器
* </p>
*
* @author 拓恒
* @since 2022-06-21
*/
@RestController
@RequestMapping("/user")
public class UserController {

}

+ 33
- 0
tuoheng-auth/src/main/java/com/tuoheng/auth/exception/OAuth2WebResponseExceptionTranslator.java View File

@@ -0,0 +1,33 @@
package com.tuoheng.auth.exception;

import com.tuoheng.common.core.utils.JsonResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

public class OAuth2WebResponseExceptionTranslator extends DefaultWebResponseExceptionTranslator implements WebResponseExceptionTranslator<OAuth2Exception> {

@Override
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
// return super.translate(e);
ResponseEntity<OAuth2Exception> responseEntity = null;
try {
responseEntity = super.translate(e);
} catch (Exception e1) {
e1.printStackTrace();
}
JsonResult jsonResult = new JsonResult();
OAuth2Exception body = responseEntity.getBody();
if (e instanceof InvalidGrantException) {
return new ResponseEntity(jsonResult.error(402, "用户名或密码不正确"), HttpStatus.OK);
} else if (e instanceof InvalidTokenException) {
return new ResponseEntity(jsonResult.error(401, "token已失效"), HttpStatus.OK);
} else {
return new ResponseEntity(jsonResult.error(401, body.getLocalizedMessage()), HttpStatus.OK);
}
}
}

+ 91
- 0
tuoheng-auth/src/main/java/com/tuoheng/auth/service/OAuthUserDetailsService.java View File

@@ -0,0 +1,91 @@
package com.tuoheng.auth.service;

import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.security.entity.SecurityUser;
import com.tuoheng.common.core.utils.StringUtils;
import com.tuoheng.system.api.entity.User;
import com.tuoheng.system.api.feign.UserClient;
import com.tuoheng.system.api.vo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

@Service
public class OAuthUserDetailsService implements UserDetailsService {

@Autowired
private UserClient userClient;

/**
* 获取用户信息
*
* @param username 用户名
* @return
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
JsonResult<UserInfo> result = userClient.getInfoByName(username);
// 检查用户
checkUser(result, username);
// 获取用户信息
UserDetails userDetails = getUserDetails(result);
return userDetails;
}

/**
* 检查用户信息
*
* @param result 数据源
* @param username 用户名
*/
private void checkUser(JsonResult result, String username) {
// 用户信息验证
if (StringUtils.isNull(result) || StringUtils.isNull(result.getData())) {
// log.info("登录用户:{} 不存在.", username);
throw new UsernameNotFoundException("登录用户:" + username + " 不存在");
}
}

/**
* 获取用户详情信息
*
* @param result 结果
* @return
*/
private UserDetails getUserDetails(JsonResult<UserInfo> result) {
UserInfo info = result.getData();
Set<String> dbAuthsSet = new HashSet<String>();
if (StringUtils.isNotEmpty(info.getRoles())) {
// 获取角色
dbAuthsSet.addAll(info.getRoles());
dbAuthsSet.addAll(info.getPermissions());
}

Collection<? extends GrantedAuthority> authorities = AuthorityUtils
.createAuthorityList(dbAuthsSet.toArray(new String[0]));
User user = info.getUser();

// // 下面是写死,暂时不和数据库交互
// if(!(("admin").equals(username))){
// throw new UsernameNotFoundException("the user is not found");
// }else{
// String role = "ADMIN_ROLE";
// List<SimpleGrantedAuthority> authorities = new ArrayList<>();
// authorities.add(new SimpleGrantedAuthority(role));
// String password = passwordEncoder.encode("123456");
// return new User(username,password,authorities);
// }

return new SecurityUser(user.getId(), user.getUsername(), user.getPassword(), true, true, true, true,
authorities);
}
}

+ 20
- 0
tuoheng-auth/src/main/resources/application-dev.yml View File

@@ -0,0 +1,20 @@
spring:
redis:
host: localhost
port: 6379
password:
database: 0
# 配置数据源
datasource:
# 使用阿里的Druid连接池
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
# 填写你数据库的url、登录名、密码和数据库名
url: jdbc:mysql://127.0.0.1:3306/tuoheng_cloud?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8&useSSL=true&tinyInt1isBit=false
username: root
password:

# 安全认证的配置
security:
basic:
enabled: true

+ 20
- 0
tuoheng-auth/src/main/resources/application-local.yml View File

@@ -0,0 +1,20 @@
spring:
redis:
host: localhost
port: 6379
password:
database: 0
# 配置数据源
datasource:
# 使用阿里的Druid连接池
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
# 填写你数据库的url、登录名、密码和数据库名
url: jdbc:mysql://127.0.0.1:3306/tuoheng_cloud?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8&useSSL=true&tinyInt1isBit=false
username: root
password:

# 安全认证的配置
security:
basic:
enabled: true

+ 20
- 0
tuoheng-auth/src/main/resources/application-prod.yml View File

@@ -0,0 +1,20 @@
spring:
redis:
host: localhost
port: 6379
password:
database: 0
# 配置数据源
datasource:
# 使用阿里的Druid连接池
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
# 填写你数据库的url、登录名、密码和数据库名
url: jdbc:mysql://127.0.0.1:3306/tuoheng_cloud?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8&useSSL=true&tinyInt1isBit=false
username: root
password:

# 安全认证的配置
security:
basic:
enabled: true

+ 20
- 0
tuoheng-auth/src/main/resources/application-test.yml View File

@@ -0,0 +1,20 @@
spring:
redis:
host: localhost
port: 6379
password:
database: 0
# 配置数据源
datasource:
# 使用阿里的Druid连接池
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
# 填写你数据库的url、登录名、密码和数据库名
url: jdbc:mysql://127.0.0.1:3306/tuoheng_cloud?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8&useSSL=true&tinyInt1isBit=false
username: root
password:

# 安全认证的配置
security:
basic:
enabled: true

+ 16
- 0
tuoheng-auth/src/main/resources/application.yml View File

@@ -0,0 +1,16 @@
server:
port: 9012

spring:
profiles:
active: @package.environment@
application:
name: tuoheng-auth
main:
allow-bean-definition-overriding: true
allow-circular-references: true

eureka:
client:
serviceUrl:
defaultZone: http://localhost:9010/eureka/

+ 20
- 0
tuoheng-auth/target/classes/WEB-INF/classes/application-local.yml View File

@@ -0,0 +1,20 @@
spring:
redis:
host: localhost
port: 6379
password:
database: 0
# 配置数据源
datasource:
# 使用阿里的Druid连接池
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
# 填写你数据库的url、登录名、密码和数据库名
url: jdbc:mysql://127.0.0.1:3306/tuoheng_cloud?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8&useSSL=true&tinyInt1isBit=false
username: root
password:

# 安全认证的配置
security:
basic:
enabled: true

+ 20
- 0
tuoheng-auth/target/classes/application-dev.yml View File

@@ -0,0 +1,20 @@
spring:
redis:
host: localhost
port: 6379
password:
database: 0
# 配置数据源
datasource:
# 使用阿里的Druid连接池
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
# 填写你数据库的url、登录名、密码和数据库名
url: jdbc:mysql://127.0.0.1:3306/tuoheng_cloud?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8&useSSL=true&tinyInt1isBit=false
username: root
password:

# 安全认证的配置
security:
basic:
enabled: true

+ 20
- 0
tuoheng-auth/target/classes/application-local.yml View File

@@ -0,0 +1,20 @@
spring:
redis:
host: localhost
port: 6379
password:
database: 0
# 配置数据源
datasource:
# 使用阿里的Druid连接池
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
# 填写你数据库的url、登录名、密码和数据库名
url: jdbc:mysql://127.0.0.1:3306/tuoheng_cloud?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8&useSSL=true&tinyInt1isBit=false
username: root
password:

# 安全认证的配置
security:
basic:
enabled: true

+ 20
- 0
tuoheng-auth/target/classes/application-prod.yml View File

@@ -0,0 +1,20 @@
spring:
redis:
host: localhost
port: 6379
password:
database: 0
# 配置数据源
datasource:
# 使用阿里的Druid连接池
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
# 填写你数据库的url、登录名、密码和数据库名
url: jdbc:mysql://127.0.0.1:3306/tuoheng_cloud?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8&useSSL=true&tinyInt1isBit=false
username: root
password:

# 安全认证的配置
security:
basic:
enabled: true

+ 20
- 0
tuoheng-auth/target/classes/application-test.yml View File

@@ -0,0 +1,20 @@
spring:
redis:
host: localhost
port: 6379
password:
database: 0
# 配置数据源
datasource:
# 使用阿里的Druid连接池
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
# 填写你数据库的url、登录名、密码和数据库名
url: jdbc:mysql://127.0.0.1:3306/tuoheng_cloud?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8&useSSL=true&tinyInt1isBit=false
username: root
password:

# 安全认证的配置
security:
basic:
enabled: true

+ 16
- 0
tuoheng-auth/target/classes/application.yml View File

@@ -0,0 +1,16 @@
server:
port: 9012

spring:
profiles:
active: local
application:
name: tuoheng-auth
main:
allow-bean-definition-overriding: true
allow-circular-references: true

eureka:
client:
serviceUrl:
defaultZone: http://localhost:9010/eureka/

BIN
tuoheng-auth/target/classes/com/tuoheng/auth/THAuthApplication.class View File


BIN
tuoheng-auth/target/classes/com/tuoheng/auth/config/AuthorizationServerConfig$1.class View File


BIN
tuoheng-auth/target/classes/com/tuoheng/auth/config/AuthorizationServerConfig.class View File


BIN
tuoheng-auth/target/classes/com/tuoheng/auth/config/SecurityConfig.class View File


BIN
tuoheng-auth/target/classes/com/tuoheng/auth/controller/UserController.class View File


BIN
tuoheng-auth/target/classes/com/tuoheng/auth/exception/OAuth2WebResponseExceptionTranslator.class View File


BIN
tuoheng-auth/target/classes/com/tuoheng/auth/service/OAuthUserDetailsService.class View File


+ 207
- 0
tuoheng-auth/tuoheng-auth.iml View File

@@ -0,0 +1,207 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="web" name="Web">
<configuration>
<webroots />
</configuration>
</facet>
<facet type="Spring" name="Spring">
<configuration />
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="tuoheng-common-security" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-starter-oauth2:2.2.5.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.1.2.RELEASE" level="project" />
<orderEntry type="library" name="Maven: com.sun.xml.bind:jaxb-core:2.3.0.1" level="project" />
<orderEntry type="library" name="Maven: com.sun.xml.bind:jaxb-impl:2.3.0.1" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security.oauth:spring-security-oauth2:2.3.4.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security:spring-security-core:5.7.1" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security:spring-security-config:5.7.1" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security:spring-security-web:5.7.1" level="project" />
<orderEntry type="library" name="Maven: org.codehaus.jackson:jackson-mapper-asl:1.9.13" level="project" />
<orderEntry type="library" name="Maven: org.codehaus.jackson:jackson-core-asl:1.9.13" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security:spring-security-jwt:1.0.9.RELEASE" level="project" />
<orderEntry type="library" name="Maven: javax.activation:javax.activation-api:1.2.0" level="project" />
<orderEntry type="library" name="Maven: javax.xml.bind:jaxb-api:2.3.1" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jaxb:jaxb-runtime:2.3.6" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jaxb:txw2:2.3.6" level="project" />
<orderEntry type="library" name="Maven: com.sun.istack:istack-commons-runtime:3.0.12" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: com.sun.activation:jakarta.activation:1.2.2" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-starter-security:2.1.4.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-security:2.1.4.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-security:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-data-redis:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-redis:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-keyvalue:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-commons:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-tx:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-oxm:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-aop:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-context-support:5.3.20" level="project" />
<orderEntry type="library" name="Maven: io.lettuce:lettuce-core:6.1.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-common:4.1.77.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-handler:4.1.77.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-resolver:4.1.77.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-buffer:4.1.77.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-codec:4.1.77.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-transport:4.1.77.Final" level="project" />
<orderEntry type="library" name="Maven: io.projectreactor:reactor-core:3.4.18" level="project" />
<orderEntry type="library" name="Maven: org.reactivestreams:reactive-streams:1.0.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-starter-openfeign:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-openfeign-core:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-aop:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.aspectj:aspectjweaver:1.9.7" level="project" />
<orderEntry type="library" name="Maven: io.github.openfeign.form:feign-form-spring:3.8.0" level="project" />
<orderEntry type="library" name="Maven: io.github.openfeign.form:feign-form:3.8.0" level="project" />
<orderEntry type="library" name="Maven: commons-fileupload:commons-fileupload:1.4" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-web:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-beans:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-commons:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security:spring-security-crypto:5.7.1" level="project" />
<orderEntry type="library" name="Maven: io.github.openfeign:feign-core:11.8" level="project" />
<orderEntry type="library" name="Maven: io.github.openfeign:feign-slf4j:11.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-web:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-json:2.7.0" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.13.3" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.module:jackson-module-parameter-names:2.13.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-tomcat:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-core:9.0.63" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-el:9.0.63" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-websocket:9.0.63" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-webmvc:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-context:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-expression:5.3.20" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-boot-starter:3.2.0" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus:3.2.0" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-extension:3.2.0" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-core:3.2.0" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-annotation:3.2.0" level="project" />
<orderEntry type="library" name="Maven: com.github.jsqlparser:jsqlparser:2.1" level="project" />
<orderEntry type="library" name="Maven: org.mybatis:mybatis:3.5.2" level="project" />
<orderEntry type="library" name="Maven: org.mybatis:mybatis-spring:2.0.2" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-jdbc:2.7.0" level="project" />
<orderEntry type="library" name="Maven: com.zaxxer:HikariCP:4.0.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-jdbc:5.3.20" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:fastjson:1.2.76" level="project" />
<orderEntry type="module" module-name="tuoheng-system-api" />
<orderEntry type="module" module-name="tuoheng-common-core" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-lang3:3.12.0" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-pool2:2.11.1" level="project" />
<orderEntry type="library" name="Maven: commons-io:commons-io:2.5" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:easyexcel:1.1.2-beat1" level="project" />
<orderEntry type="library" name="Maven: org.apache.poi:poi:3.17" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-collections4:4.4" level="project" />
<orderEntry type="library" name="Maven: org.apache.poi:poi-ooxml:3.17" level="project" />
<orderEntry type="library" name="Maven: org.apache.poi:poi-ooxml-schemas:3.17" level="project" />
<orderEntry type="library" name="Maven: org.apache.xmlbeans:xmlbeans:2.6.0" level="project" />
<orderEntry type="library" name="Maven: stax:stax-api:1.0.1" level="project" />
<orderEntry type="library" name="Maven: com.github.virtuald:curvesapi:1.04" level="project" />
<orderEntry type="library" name="Maven: cglib:cglib:3.1" level="project" />
<orderEntry type="library" name="Maven: org.ow2.asm:asm:4.2" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.13.3" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.13.3" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.13.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-starter-netflix-eureka-client:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-starter:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-context:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security:spring-security-rsa:1.0.10.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.bouncycastle:bcpkix-jdk15on:1.68" level="project" />
<orderEntry type="library" name="Maven: org.bouncycastle:bcprov-jdk15on:1.68" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-netflix-eureka-client:3.1.3" level="project" />
<orderEntry type="library" name="Maven: com.netflix.eureka:eureka-client:1.10.17" level="project" />
<orderEntry type="library" name="Maven: com.netflix.netflix-commons:netflix-eventbus:0.3.0" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: com.netflix.netflix-commons:netflix-infix:0.3.0" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: commons-jxpath:commons-jxpath:1.3" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: joda-time:joda-time:2.3" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.antlr:antlr-runtime:3.4" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.antlr:stringtemplate:3.2.1" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: antlr:antlr:2.7.7" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: com.google.code.gson:gson:2.9.0" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.apache.commons:commons-math:2.2" level="project" />
<orderEntry type="library" name="Maven: com.thoughtworks.xstream:xstream:1.4.18" level="project" />
<orderEntry type="library" name="Maven: io.github.x-stream:mxparser:1.2.2" level="project" />
<orderEntry type="library" name="Maven: xmlpull:xmlpull:1.1.3.1" level="project" />
<orderEntry type="library" name="Maven: javax.ws.rs:jsr311-api:1.1.1" level="project" />
<orderEntry type="library" name="Maven: com.netflix.servo:servo-core:0.12.21" level="project" />
<orderEntry type="library" name="Maven: com.google.guava:guava:19.0" level="project" />
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpclient:4.5.13" level="project" />
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpcore:4.4.15" level="project" />
<orderEntry type="library" name="Maven: commons-codec:commons-codec:1.15" level="project" />
<orderEntry type="library" name="Maven: commons-configuration:commons-configuration:1.10" level="project" />
<orderEntry type="library" name="Maven: commons-lang:commons-lang:2.6" level="project" />
<orderEntry type="library" name="Maven: com.google.inject:guice:4.1.0" level="project" />
<orderEntry type="library" name="Maven: javax.inject:javax.inject:1" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.codehaus.jettison:jettison:1.4.0" level="project" />
<orderEntry type="library" name="Maven: com.netflix.eureka:eureka-core:1.10.17" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.woodstox:woodstox-core:6.2.1" level="project" />
<orderEntry type="library" name="Maven: org.codehaus.woodstox:stax2-api:4.2.1" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-starter-loadbalancer:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-loadbalancer:3.1.3" level="project" />
<orderEntry type="library" name="Maven: io.projectreactor.addons:reactor-extra:3.4.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-cache:2.7.0" level="project" />
<orderEntry type="library" name="Maven: com.stoyanr:evictor:1.0.0" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: mysql:mysql-connector-java:8.0.29" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:druid-spring-boot-starter:1.1.10" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:druid:1.1.10" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.36" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-autoconfigure:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-actuator:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-logging:2.7.0" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-classic:1.2.11" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-core:1.2.11" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-to-slf4j:2.17.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-api:2.17.2" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:1.7.36" level="project" />
<orderEntry type="library" name="Maven: jakarta.annotation:jakarta.annotation-api:1.3.5" level="project" />
<orderEntry type="library" name="Maven: org.yaml:snakeyaml:1.30" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-actuator-autoconfigure:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-actuator:2.7.0" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.13.3" level="project" />
<orderEntry type="library" name="Maven: io.micrometer:micrometer-core:1.9.0" level="project" />
<orderEntry type="library" name="Maven: org.hdrhistogram:HdrHistogram:2.1.12" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.latencyutils:LatencyUtils:2.0.3" level="project" />
<orderEntry type="library" name="Maven: org.projectlombok:lombok:1.18.24" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-starter-test:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test-autoconfigure:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.jayway.jsonpath:json-path:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:json-smart:2.4.8" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:accessors-smart:2.4.8" level="project" />
<orderEntry type="library" name="Maven: jakarta.xml.bind:jakarta.xml.bind-api:2.3.3" level="project" />
<orderEntry type="library" name="Maven: jakarta.activation:jakarta.activation-api:1.2.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.assertj:assertj-core:3.22.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest:2.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-api:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.opentest4j:opentest4j:1.2.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.platform:junit-platform-commons:1.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apiguardian:apiguardian-api:1.1.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-params:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-engine:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.platform:junit-platform-engine:1.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-core:4.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy:1.12.10" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy-agent:1.12.10" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.objenesis:objenesis:3.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-junit-jupiter:4.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.skyscreamer:jsonassert:1.5.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.vaadin.external.google:android-json:0.0.20131108.vaadin1" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-core:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-jcl:5.3.20" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-test:5.3.20" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.xmlunit:xmlunit-core:2.9.0" level="project" />
</component>
</module>

+ 19
- 0
tuoheng-common/pom.xml View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>tuoheng</artifactId>
<groupId>com.tuoheng</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>tuoheng-common</artifactId>
<packaging>pom</packaging>
<modules>
<module>tuoheng-common-core</module>
<module>tuoheng-common-security</module>
</modules>

</project>

+ 69
- 0
tuoheng-common/tuoheng-common-core/pom.xml View File

@@ -0,0 +1,69 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>tuoheng-common</artifactId>
<groupId>com.tuoheng</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>tuoheng-common-core</artifactId>
<groupId>com.tuoheng</groupId>

<!-- 依赖库管理 -->
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<!--mybatis-plus 起始依赖 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<!-- 引入阿里数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!-- JSON工具类 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<!-- Apache Commons Pool2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<!-- Excel依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>1.1.2-beat1</version>
</dependency>
</dependencies>

</project>

+ 6
- 0
tuoheng-common/tuoheng-common-core/src/main/java/com/tuoheng/common/core/DemoController.java View File

@@ -0,0 +1,6 @@
package com.tuoheng.common.core;

public class DemoController {


}

+ 8
- 0
tuoheng-common/tuoheng-common-core/src/main/java/com/tuoheng/common/core/common/BaseController.java View File

@@ -0,0 +1,8 @@
package com.tuoheng.common.core.common;

/**
* 基类控制器
*/
public class BaseController {

}

+ 58
- 0
tuoheng-common/tuoheng-common-core/src/main/java/com/tuoheng/common/core/common/BaseEntity.java View File

@@ -0,0 +1,58 @@
package com.tuoheng.common.core.common;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import java.io.Serializable;
import java.util.Date;

/**
* 基类实体对象
*
* @author 牧羊人
* @date 2019/11/28
*/
@Data
public class BaseEntity implements Serializable {

private static final long serialVersionUID = 1L;

/**
* 主键ID
*/
@TableId(value = "id", type = IdType.UUID)
private String id;

/**
* 添加人
*/
private Integer createUser;

/**
* 创建时间
*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;

/**
* 更新人
*/
private Integer updateUser;

/**
* 更新时间
*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;

/**
* 有效标识
*/
private Integer mark;

}

+ 19
- 0
tuoheng-common/tuoheng-common-core/src/main/java/com/tuoheng/common/core/common/BaseQuery.java View File

@@ -0,0 +1,19 @@
package com.tuoheng.common.core.common;

import lombok.Data;

/**
* 查询对象基类
*/
@Data
public class BaseQuery {
/**
* 页码(默认1)
*/
private Integer page = 1;

/**
* 每页数(默认:20)
*/
private Integer limit = 20;
}

+ 209
- 0
tuoheng-common/tuoheng-common-core/src/main/java/com/tuoheng/common/core/common/BaseServiceImpl.java View File

@@ -0,0 +1,209 @@
package com.tuoheng.common.core.common;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;

import java.io.Serializable;
import java.util.List;

public class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseEntity> extends ServiceImpl<M, T> implements IBaseService<T> {

/**
* 根据查询条件获取数据列表
*
* @param page 分页
* @param query 查询条件
* @return
*/
@Override
public JsonResult getList(Page<T> page, BaseQuery query) {
return null;
}

/**
* 获取数据列表
*
* @param query 查询条件
* @return
*/
@Override
public JsonResult getList(BaseQuery query) {
return null;
}

/**
* 根据实体ID获取实体信息
*
* @param id 记录ID
* @return
*/
@Override
public JsonResult info(Integer id) {
if (id == null && id <= 0) {
return JsonResult.error("记录ID不能为空");
}
Object result = this.getInfo(id);
return JsonResult.success(result, "操作成功");
}

/**
* 根据ID获取记录信息
*
* @param id 记录ID
* @return
*/
@Override
public Object getInfo(Serializable id) {
T entity = this.getById(id);
return entity;
}

/**
* 传入实体对象添加记录
*
* @param entity 实体对象
* @return
*/
@Override
public JsonResult add(T entity) {
// entity.setCreateUser(SecurityUtils.getUserId());
entity.setCreateTime(DateUtils.now());
entity.setMark(1);
boolean result = this.save(entity);
if (!result) {
return JsonResult.error();
}
return JsonResult.success();
}

/**
* 传入实体对象更新记录
*
* @param entity 实体对象
* @return
*/
@Override
public JsonResult update(T entity) {
// entity.setUpdateUser(SecurityUtils.getUserId());
entity.setUpdateTime(DateUtils.now());
boolean result = this.updateById(entity);
if (!result) {
return JsonResult.error();
}
return JsonResult.success();
}

/**
* 根据实体对象添加、编辑记录
*
* @param entity 实体对象
* @return
*/
@Override
public JsonResult edit(T entity) {
if (entity == null) {
return JsonResult.error("实体对象不存在");
}
if (entity.getId() != null && StringUtils.isNotEmpty(entity.getId())) {
// 修改记录
return this.update(entity);
} else {
// 新增记录
return this.add(entity);
}
}

/**
* 删除记录
*
* @param entity 实体对象
* @return
*/
@Override
public JsonResult delete(T entity) {
// entity.setUpdateUser(SecurityUtils.getUserId());
entity.setUpdateTime(DateUtils.now());
entity.setMark(0);
boolean result = this.updateById(entity);
if (!result) {
return JsonResult.error();
}
return JsonResult.success("删除成功");
}

/**
* 根据ID删除记录
*
* @param id 记录ID
* @return
*/
@Override
public JsonResult deleteById(Integer id) {
if (id == null || id == 0) {
return JsonResult.error("记录ID不能为空");
}
// 设置Mark=0
UpdateWrapper updateWrapper = new UpdateWrapper();
updateWrapper.set("mark", 0);
updateWrapper.eq("id", id);
boolean result = update(updateWrapper);
if (!result) {
return JsonResult.error();
}
return JsonResult.success("删除成功");
}

/**
* 根据ID删除记录
*
* @param ids 记录ID
* @return
*/
@Override
public JsonResult deleteByIds(Integer[] ids) {
if (StringUtils.isNull(ids)) {
return JsonResult.error("记录ID不能为空");
}
// 设置Mark=0
Integer totalNum = 0;
for (Integer id : ids) {
UpdateWrapper updateWrapper = new UpdateWrapper();
updateWrapper.set("mark", 0);
updateWrapper.eq("id", id);
boolean result = update(updateWrapper);
if (result) {
totalNum++;
}
}
if (totalNum != ids.length) {
return JsonResult.error();
}
return JsonResult.success("删除成功");
}

/**
* 设置状态
*
* @param entity 实体对象
* @return
*/
@Override
public JsonResult setStatus(T entity) {
return this.update(entity);
}

/**
* 导出Excel
*
* @return
*/
@Override
public List<T> exportExcel() {
return null;
}
}

+ 109
- 0
tuoheng-common/tuoheng-common-core/src/main/java/com/tuoheng/common/core/common/IBaseService.java View File

@@ -0,0 +1,109 @@
package com.tuoheng.common.core.common;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.tuoheng.common.core.utils.JsonResult;

import java.io.Serializable;
import java.util.List;


public interface IBaseService<T> extends IService<T> {

/**
* 根据查询条件获取数据列表
*
* @param page 分页
* @param query 查询条件
* @return
*/
JsonResult getList(Page<T> page, BaseQuery query);

/**
* 获取数据列表
*
* @param query 查询条件
* @return
*/
JsonResult getList(BaseQuery query);

/**
* 根据ID获取记录信息
*
* @param id 记录ID
* @return
*/
JsonResult info(Integer id);

/**
* 根据ID获取记录信息
*
* @param id 记录ID
* @return
*/
Object getInfo(Serializable id);

/**
* 根据实体对象添加记录
*
* @param entity 实体对象
* @return
*/
JsonResult add(T entity);

/**
* 根据实体对象更新记录
*
* @param entity 实体对象
* @return
*/
JsonResult update(T entity);

/**
* 根据实体对象添加、编辑记录
*
* @param entity 实体对象
* @return
*/
JsonResult edit(T entity);

/**
* 删除记录
*
* @param entity 实体对象
* @return
*/
JsonResult delete(T entity);

/**
* 根据ID删除记录
*
* @param id 记录ID
* @return
*/
JsonResult deleteById(Integer id);

/**
* 根据ID删除记录
*
* @param ids 记录ID
* @return
*/
JsonResult deleteByIds(Integer[] ids);

/**
* 设置状态
*
* @param entity 实体对象
* @return
*/
JsonResult setStatus(T entity);

/**
* 导出Excel
*
* @return
*/
List<T> exportExcel();

}

+ 136
- 0
tuoheng-common/tuoheng-common-core/src/main/java/com/tuoheng/common/core/utils/DateUtils.java View File

@@ -0,0 +1,136 @@
package com.tuoheng.common.core.utils;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
* 时间工具类
*/
public final class DateUtils extends org.apache.commons.lang3.time.DateUtils {

public static String YYYY = "yyyy";

public static String YYYY_MM = "yyyy-MM";

public static String YYYY_MM_DD = "yyyy-MM-dd";

public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

private static String[] parsePatterns = {
"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};


/**
* 获取当前时间
*
* @return
*/
public static Date now() {
return new Date();
}

/**
* 获取当前日期, 默认格式为yyyy-MM-dd
*
* @return String
*/
public static String getDate() {
return dateTimeNow(YYYY_MM_DD);
}

public static final String getTime() {
return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
}

public static final String dateTimeNow() {
return dateTimeNow(YYYYMMDDHHMMSS);
}

public static final String dateTimeNow(final String format) {
return parseDateToStr(format, new Date());
}

public static final String dateTime(final Date date) {
return parseDateToStr(YYYY_MM_DD, date);
}

public static final String parseDateToStr(final String format, final Date date) {
return new SimpleDateFormat(format).format(date);
}

public static final Date dateTime(final String format, final String ts) {
try {
return new SimpleDateFormat(format).parse(ts);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}

/**
* 日期路径 即年/月/日 如2018/08/08
*/
public static final String datePath() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyy/MM/dd");
}

/**
* 日期路径 即年/月/日 如20180808
*/
public static final String dateTime() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyyMMdd");
}

/**
* 日期型字符串转化为日期 格式
*/
public static Date parseDate(Object str) {
if (str == null) {
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}

/**
* 获取服务器启动时间
*/
public static Date getServerStartDate() {
long time = ManagementFactory.getRuntimeMXBean().getStartTime();
return new Date(time);
}

/**
* 计算两个时间差
*/
public static String getDatePoor(Date endDate, Date nowDate) {
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
// long ns = 1000;
// 获得两个时间的毫秒时间差异
long diff = endDate.getTime() - nowDate.getTime();
// 计算差多少天
long day = diff / nd;
// 计算差多少小时
long hour = diff % nd / nh;
// 计算差多少分钟
long min = diff % nd % nh / nm;
// 计算差多少秒//输出结果
// long sec = diff % nd % nh % nm / ns;
return day + "天" + hour + "小时" + min + "分钟";
}

}

+ 99
- 0
tuoheng-common/tuoheng-common-core/src/main/java/com/tuoheng/common/core/utils/JsonResult.java View File

@@ -0,0 +1,99 @@
package com.tuoheng.common.core.utils;

import java.io.Serializable;

/**
* JSON回应类
*
* @author 牧羊人
* @date 2019/11/28
*/
public class JsonResult<T> implements Serializable {

private static final long serialVersionUID = 1L;

/**
* 成功
*/
public static final int SUCCESS = 0;

/**
* 失败
*/
public static final int error = -1;

private int code;

private String msg;

private T data;

public static <T> JsonResult<T> success() {
return jsonResult(null, SUCCESS, "操作成功");
}

public static <T> JsonResult<T> success(String msg) {
return jsonResult(null, SUCCESS, msg);
}

public static <T> JsonResult<T> success(T data) {
return jsonResult(data, SUCCESS, "操作成功");
}

public static <T> JsonResult<T> success(T data, String msg) {
return jsonResult(data, SUCCESS, msg);
}

public static <T> JsonResult<T> error() {
return jsonResult(null, error, "操作失败");
}

public static <T> JsonResult<T> error(String msg) {
return jsonResult(null, error, msg);
}

public static <T> JsonResult<T> error(T data) {
return jsonResult(data, error, "操作失败");
}

public static <T> JsonResult<T> error(T data, String msg) {
return jsonResult(data, error, msg);
}

public static <T> JsonResult<T> error(int code, String msg) {
return jsonResult(null, code, msg);
}

private static <T> JsonResult<T> jsonResult(T data, int code, String msg) {
JsonResult<T> result = new JsonResult<>();
result.setCode(code);
result.setData(data);
result.setMsg(msg);
return result;
}

public int getCode() {
return code;
}

public void setCode(int code) {
this.code = code;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public T getData() {
return data;
}

public void setData(T data) {
this.data = data;
}

}

+ 367
- 0
tuoheng-common/tuoheng-common-core/src/main/java/com/tuoheng/common/core/utils/StringUtils.java View File

@@ -0,0 +1,367 @@
package com.tuoheng.common.core.utils;

import java.util.*;

/**
* 字符串工具类
*/
public class StringUtils extends org.apache.commons.lang3.StringUtils {

/**
* 空字符串
*/
private static final String NULLSTR = "";

/**
* 下划线
*/
private static final char SEPARATOR = '_';

/**
* 获取参数不为空值
*
* @param value defaultValue 要判断的value
* @return value 返回值
*/
public static <T> T nvl(T value, T defaultValue) {
return value != null ? value : defaultValue;
}

/**
* * 判断一个Collection是否为空, 包含List,Set,Queue
*
* @param coll 要判断的Collection
* @return true:为空 false:非空
*/
public static boolean isEmpty(Collection<?> coll) {
return isNull(coll) || coll.isEmpty();
}

/**
* * 判断一个Collection是否非空,包含List,Set,Queue
*
* @param coll 要判断的Collection
* @return true:非空 false:空
*/
public static boolean isNotEmpty(Collection<?> coll) {
return !isEmpty(coll);
}

/**
* * 判断一个对象数组是否为空
*
* @param objects 要判断的对象数组
* * @return true:为空 false:非空
*/
public static boolean isEmpty(Object[] objects) {
return isNull(objects) || (objects.length == 0);
}

/**
* * 判断一个对象数组是否非空
*
* @param objects 要判断的对象数组
* @return true:非空 false:空
*/
public static boolean isNotEmpty(Object[] objects) {
return !isEmpty(objects);
}

/**
* * 判断一个Map是否为空
*
* @param map 要判断的Map
* @return true:为空 false:非空
*/
public static boolean isEmpty(Map<?, ?> map) {
return isNull(map) || map.isEmpty();
}

/**
* * 判断一个Map是否为空
*
* @param map 要判断的Map
* @return true:非空 false:空
*/
public static boolean isNotEmpty(Map<?, ?> map) {
return !isEmpty(map);
}

/**
* * 判断一个字符串是否为空串
*
* @param str String
* @return true:为空 false:非空
*/
public static boolean isEmpty(String str) {
return isNull(str) || NULLSTR.equals(str.trim());
}

/**
* * 判断一个字符串是否为非空串
*
* @param str String
* @return true:非空串 false:空串
*/
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}

/**
* * 判断一个对象是否为空
*
* @param object Object
* @return true:为空 false:非空
*/
public static boolean isNull(Object object) {
return object == null;
}

/**
* * 判断一个对象是否非空
*
* @param object Object
* @return true:非空 false:空
*/
public static boolean isNotNull(Object object) {
return !isNull(object);
}

/**
* * 判断一个对象是否是数组类型(Java基本型别的数组)
*
* @param object 对象
* @return true:是数组 false:不是数组
*/
public static boolean isArray(Object object) {
return isNotNull(object) && object.getClass().isArray();
}

/**
* 去空格
*/
public static String trim(String str) {
return (str == null ? "" : str.trim());
}

/**
* 截取字符串
*
* @param str 字符串
* @param start 开始
* @return 结果
*/
public static String substring(final String str, int start) {
if (str == null) {
return NULLSTR;
}

if (start < 0) {
start = str.length() + start;
}

if (start < 0) {
start = 0;
}
if (start > str.length()) {
return NULLSTR;
}

return str.substring(start);
}

/**
* 截取字符串
*
* @param str 字符串
* @param start 开始
* @param end 结束
* @return 结果
*/
public static String substring(final String str, int start, int end) {
if (str == null) {
return NULLSTR;
}

if (end < 0) {
end = str.length() + end;
}
if (start < 0) {
start = str.length() + start;
}

if (end > str.length()) {
end = str.length();
}

if (start > end) {
return NULLSTR;
}

if (start < 0) {
start = 0;
}
if (end < 0) {
end = 0;
}

return str.substring(start, end);
}

/**
* 字符串转set
*
* @param str 字符串
* @param sep 分隔符
* @return set集合
*/
public static final Set<String> str2Set(String str, String sep) {
return new HashSet<String>(str2List(str, sep, true, false));
}

/**
* 字符串转list
*
* @param str 字符串
* @param sep 分隔符
* @param filterBlank 过滤纯空白
* @param trim 去掉首尾空白
* @return list集合
*/
public static final List<String> str2List(String str, String sep, boolean filterBlank, boolean trim) {
List<String> list = new ArrayList<String>();
if (StringUtils.isEmpty(str)) {
return list;
}

// 过滤空白字符串
if (filterBlank && StringUtils.isBlank(str)) {
return list;
}
String[] split = str.split(sep);
for (String string : split) {
if (filterBlank && StringUtils.isBlank(string)) {
continue;
}
if (trim) {
string = string.trim();
}
list.add(string);
}

return list;
}

/**
* 下划线转驼峰命名
*/
public static String toUnderScoreCase(String str) {
if (str == null) {
return null;
}
StringBuilder sb = new StringBuilder();
// 前置字符是否大写
boolean preCharIsUpperCase = true;
// 当前字符是否大写
boolean curreCharIsUpperCase = true;
// 下一字符是否大写
boolean nexteCharIsUpperCase = true;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (i > 0) {
preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
} else {
preCharIsUpperCase = false;
}

curreCharIsUpperCase = Character.isUpperCase(c);

if (i < (str.length() - 1)) {
nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
}

if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) {
sb.append(SEPARATOR);
} else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) {
sb.append(SEPARATOR);
}
sb.append(Character.toLowerCase(c));
}

return sb.toString();
}

/**
* 是否包含字符串
*
* @param str 验证字符串
* @param strs 字符串组
* @return 包含返回true
*/
public static boolean inStringIgnoreCase(String str, String... strs) {
if (str != null && strs != null) {
for (String s : strs) {
if (str.equalsIgnoreCase(trim(s))) {
return true;
}
}
}
return false;
}

/**
* 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld
*
* @param name 转换前的下划线大写方式命名的字符串
* @return 转换后的驼峰式命名的字符串
*/
public static String convertToCamelCase(String name) {
StringBuilder result = new StringBuilder();
// 快速检查
if (name == null || name.isEmpty()) {
// 没必要转换
return "";
} else if (!name.contains("_")) {
// 不含下划线,仅将首字母大写
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
// 用下划线将原始字符串分割
String[] camels = name.split("_");
for (String camel : camels) {
// 跳过原始字符串中开头、结尾的下换线或双重下划线
if (camel.isEmpty()) {
continue;
}
// 首字母大写
result.append(camel.substring(0, 1).toUpperCase());
result.append(camel.substring(1).toLowerCase());
}
return result.toString();
}

/**
* 驼峰式命名法 例如:user_name->userName
*/
public static String toCamelCase(String s) {
if (s == null) {
return null;
}
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);

if (c == SEPARATOR) {
upperCase = true;
} else if (upperCase) {
sb.append(Character.toUpperCase(c));
upperCase = false;
} else {
sb.append(c);
}
}
return sb.toString();
}

}

BIN
tuoheng-common/tuoheng-common-core/target/classes/com/tuoheng/common/core/DemoController.class View File


BIN
tuoheng-common/tuoheng-common-core/target/classes/com/tuoheng/common/core/common/BaseController.class View File


BIN
tuoheng-common/tuoheng-common-core/target/classes/com/tuoheng/common/core/common/BaseEntity.class View File


BIN
tuoheng-common/tuoheng-common-core/target/classes/com/tuoheng/common/core/common/BaseQuery.class View File


BIN
tuoheng-common/tuoheng-common-core/target/classes/com/tuoheng/common/core/common/BaseServiceImpl.class View File


BIN
tuoheng-common/tuoheng-common-core/target/classes/com/tuoheng/common/core/common/IBaseService.class View File


BIN
tuoheng-common/tuoheng-common-core/target/classes/com/tuoheng/common/core/utils/DateUtils.class View File


BIN
tuoheng-common/tuoheng-common-core/target/classes/com/tuoheng/common/core/utils/JsonResult.class View File


BIN
tuoheng-common/tuoheng-common-core/target/classes/com/tuoheng/common/core/utils/StringUtils.class View File


+ 113
- 0
tuoheng-common/tuoheng-common-core/tuoheng-common-core.iml View File

@@ -0,0 +1,113 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="Spring" name="Spring">
<configuration />
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-starter-openfeign:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-starter:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-context:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security:spring-security-rsa:1.0.10.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.bouncycastle:bcpkix-jdk15on:1.68" level="project" />
<orderEntry type="library" name="Maven: org.bouncycastle:bcprov-jdk15on:1.68" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-openfeign-core:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-aop:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-aop:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.aspectj:aspectjweaver:1.9.7" level="project" />
<orderEntry type="library" name="Maven: io.github.openfeign.form:feign-form-spring:3.8.0" level="project" />
<orderEntry type="library" name="Maven: io.github.openfeign.form:feign-form:3.8.0" level="project" />
<orderEntry type="library" name="Maven: commons-fileupload:commons-fileupload:1.4" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-web:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-beans:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-commons:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security:spring-security-crypto:5.7.1" level="project" />
<orderEntry type="library" name="Maven: io.github.openfeign:feign-core:11.8" level="project" />
<orderEntry type="library" name="Maven: io.github.openfeign:feign-slf4j:11.8" level="project" />
<orderEntry type="library" name="Maven: org.projectlombok:lombok:1.18.24" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:fastjson:1.2.76" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-boot-starter:3.2.0" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus:3.2.0" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-extension:3.2.0" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-core:3.2.0" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-annotation:3.2.0" level="project" />
<orderEntry type="library" name="Maven: com.github.jsqlparser:jsqlparser:2.1" level="project" />
<orderEntry type="library" name="Maven: org.mybatis:mybatis:3.5.2" level="project" />
<orderEntry type="library" name="Maven: org.mybatis:mybatis-spring:2.0.2" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-autoconfigure:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-context:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-expression:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-jdbc:2.7.0" level="project" />
<orderEntry type="library" name="Maven: com.zaxxer:HikariCP:4.0.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-jdbc:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-tx:5.3.20" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:druid-spring-boot-starter:1.1.10" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:druid:1.1.10" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.36" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.13.3" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.13.3" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.13.3" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-lang3:3.9" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-pool2:2.11.1" level="project" />
<orderEntry type="library" name="Maven: commons-io:commons-io:2.5" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:easyexcel:1.1.2-beat1" level="project" />
<orderEntry type="library" name="Maven: org.apache.poi:poi:3.17" level="project" />
<orderEntry type="library" name="Maven: commons-codec:commons-codec:1.15" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-collections4:4.4" level="project" />
<orderEntry type="library" name="Maven: org.apache.poi:poi-ooxml:3.17" level="project" />
<orderEntry type="library" name="Maven: org.apache.poi:poi-ooxml-schemas:3.17" level="project" />
<orderEntry type="library" name="Maven: org.apache.xmlbeans:xmlbeans:2.6.0" level="project" />
<orderEntry type="library" name="Maven: stax:stax-api:1.0.1" level="project" />
<orderEntry type="library" name="Maven: com.github.virtuald:curvesapi:1.04" level="project" />
<orderEntry type="library" name="Maven: cglib:cglib:3.1" level="project" />
<orderEntry type="library" name="Maven: org.ow2.asm:asm:4.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-starter-test:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-logging:2.7.0" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-classic:1.2.11" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-core:1.2.11" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-to-slf4j:2.17.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-api:2.17.2" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:1.7.36" level="project" />
<orderEntry type="library" name="Maven: jakarta.annotation:jakarta.annotation-api:1.3.5" level="project" />
<orderEntry type="library" name="Maven: org.yaml:snakeyaml:1.30" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test-autoconfigure:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.jayway.jsonpath:json-path:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:json-smart:2.4.8" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:accessors-smart:2.4.8" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: jakarta.xml.bind:jakarta.xml.bind-api:2.3.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: jakarta.activation:jakarta.activation-api:1.2.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.assertj:assertj-core:3.22.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest:2.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-api:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.opentest4j:opentest4j:1.2.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.platform:junit-platform-commons:1.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apiguardian:apiguardian-api:1.1.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-params:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-engine:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.platform:junit-platform-engine:1.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-core:4.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy:1.12.10" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy-agent:1.12.10" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.objenesis:objenesis:3.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-junit-jupiter:4.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.skyscreamer:jsonassert:1.5.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.vaadin.external.google:android-json:0.0.20131108.vaadin1" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-core:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-jcl:5.3.20" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-test:5.3.20" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.xmlunit:xmlunit-core:2.9.0" level="project" />
</component>
</module>

+ 53
- 0
tuoheng-common/tuoheng-common-security/pom.xml View File

@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>tuoheng-common</artifactId>
<groupId>com.tuoheng</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>tuoheng-common-security</artifactId>

<!-- 依赖库管理 -->
<dependencies>
<!-- Spring Security Oauth2 依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
<!-- 此处需要加版本号 -->
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
<!-- 此处需要加版本号 -->
<version>2.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis-plus 起始依赖 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
</dependencies>

</project>

+ 25
- 0
tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/annotation/EnableCustomConfig.java View File

@@ -0,0 +1,25 @@
package com.tuoheng.common.security.annotation;

import com.tuoheng.common.security.config.OAuth2FeignConfig;
import com.tuoheng.common.security.security.SecurityImportBeanDefinitionRegistrar;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.scheduling.annotation.EnableAsync;

import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
// 表示通过aop框架暴露该代理对象,AopContext能够访问
@EnableAspectJAutoProxy(exposeProxy = true)
// 指定要扫描的Mapper类的包的路径
@MapperScan("com.tuoheng.**.**.mapper")
// 开启线程异步执行
@EnableAsync
// 自动加载类
@Import({SecurityImportBeanDefinitionRegistrar.class, OAuth2FeignConfig.class})
public @interface EnableCustomConfig {
}

+ 21
- 0
tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/annotation/EnableTHFeignClients.java View File

@@ -0,0 +1,21 @@
package com.tuoheng.common.security.annotation;

import org.springframework.cloud.openfeign.EnableFeignClients;

import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@EnableFeignClients
public @interface EnableTHFeignClients {
String[] value() default {};

String[] basePackages() default {"com.tuoheng"};

Class<?>[] basePackageClasses() default {};

Class<?>[] defaultConfiguration() default {};

Class<?>[] clients() default {};
}

+ 19
- 0
tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/config/OAuth2FeignConfig.java View File

@@ -0,0 +1,19 @@
package com.tuoheng.common.security.config;

import com.tuoheng.common.security.interceptor.OAuth2FeignRequestInterceptor;
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
* 拦截器配置
*/
@Configuration
public class OAuth2FeignConfig {

@Bean
public RequestInterceptor requestInterceptor() {
return new OAuth2FeignRequestInterceptor();
}

}

+ 88
- 0
tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/config/ResourceServerConfig.java View File

@@ -0,0 +1,88 @@
package com.tuoheng.common.security.config;

import com.tuoheng.common.security.security.CustomUserAuthenticationConverter;
import com.tuoheng.common.security.security.OAuthAccessDeniedHandler;
import com.tuoheng.common.security.security.OAuthAuthExceptionEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.OAuth2ClientProperties;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

@Configuration
@EnableResourceServer
//@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(3)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

@Autowired
private ResourceServerProperties resourceServerProperties;

@Autowired
private OAuth2ClientProperties oAuth2ClientProperties;

/**
* 重写安全配置类
*
* @param http
* @throws Exception
*/
@Override
public void configure(HttpSecurity http) throws Exception {
// super.configure(http);
http.csrf().disable();
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http
.authorizeRequests();
// 设置不登录可以访问
registry.antMatchers("/user/**", "/common/**").permitAll();
// 其他请求认证后放行
registry.anyRequest().authenticated();
}

@Bean
@LoadBalanced
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
return restTemplate;
}

@Bean
@Primary
public ResourceServerTokenServices tokenServices() {
RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
UserAuthenticationConverter userTokenConverter = new CustomUserAuthenticationConverter();
accessTokenConverter.setUserTokenConverter(userTokenConverter);
remoteTokenServices.setCheckTokenEndpointUrl(resourceServerProperties.getTokenInfoUri());
remoteTokenServices.setClientId(oAuth2ClientProperties.getClientId());
remoteTokenServices.setClientSecret(oAuth2ClientProperties.getClientSecret());
remoteTokenServices.setRestTemplate(restTemplate());
remoteTokenServices.setAccessTokenConverter(accessTokenConverter);
return remoteTokenServices;
}

@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenServices(tokenServices())
// 处理未认证
.authenticationEntryPoint(new OAuthAuthExceptionEntryPoint())
// 处理未授权
.accessDeniedHandler(new OAuthAccessDeniedHandler());
}
}

+ 33
- 0
tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/constant/SecurityConstant.java View File

@@ -0,0 +1,33 @@
package com.tuoheng.common.security.constant;

/**
* 安全配置常量
*/
public class SecurityConstant {

/**
* 令牌类型
*/
public static final String BEARER_TOKEN_TYPE = "Bearer";

/**
* 授权token url
*/
public static final String AUTH_TOKEN = "/oauth/token";

/**
* 注销token url
*/
public static final String TOKEN_LOGOUT = "/token/logout";

/**
* 用户ID字段
*/
public static final String DETAILS_USER_ID = "id";

/**
* 用户名字段
*/
public static final String DETAILS_USERNAME = "username";

}

+ 27
- 0
tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/entity/SecurityUser.java View File

@@ -0,0 +1,27 @@
package com.tuoheng.common.security.entity;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;

import java.util.Collection;

public class SecurityUser extends User {

/**
* 登录用户ID
*/
private Integer userId;

public SecurityUser(Integer userId, String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
this.userId = userId;
}

public Integer getUserId() {
return this.userId;
}

public void setUserId(Integer userId) {
this.userId = userId;
}
}

+ 26
- 0
tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/interceptor/OAuth2FeignRequestInterceptor.java View File

@@ -0,0 +1,26 @@
package com.tuoheng.common.security.interceptor;

import com.tuoheng.common.security.constant.SecurityConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.stereotype.Component;

@Component
public class OAuth2FeignRequestInterceptor implements RequestInterceptor {

@Override
public void apply(RequestTemplate requestTemplate) {
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
if (authentication != null && authentication.getDetails() instanceof OAuth2AuthenticationDetails) {
OAuth2AuthenticationDetails dateils = (OAuth2AuthenticationDetails) authentication.getDetails();
requestTemplate.header(HttpHeaders.AUTHORIZATION,
String.format("%s %s", SecurityConstant.BEARER_TOKEN_TYPE, dateils.getTokenValue()));
}
}
}

+ 62
- 0
tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/security/CustomUserAuthenticationConverter.java View File

@@ -0,0 +1,62 @@
package com.tuoheng.common.security.security;

import com.tuoheng.common.security.constant.SecurityConstant;
import com.tuoheng.common.security.entity.SecurityUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

public class CustomUserAuthenticationConverter implements UserAuthenticationConverter {

private static final String N_A = "N/A";

@Override
public Map<String, ?> convertUserAuthentication(Authentication authentication) {
Map<String, Object> authMap = new LinkedHashMap<>();
authMap.put(USERNAME, authentication.getName());
if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
authMap.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
}
return authMap;
}

@Override
public Authentication extractAuthentication(Map<String, ?> map) {
if (map.containsKey(USERNAME)) {
Collection<? extends GrantedAuthority> authorities = getAuthorities(map);

// 自定义对象,这里可以根据实际需要进行设置
Integer userId = Integer.valueOf(map.get(SecurityConstant.DETAILS_USER_ID).toString());
String username = map.get(SecurityConstant.DETAILS_USERNAME).toString();
SecurityUser user = new SecurityUser(userId, username, N_A, true, true, true, true, authorities);

return new UsernamePasswordAuthenticationToken(user, N_A, authorities);
}
return null;
}

/**
* 获取权限资源信息
*
* @param map
* @return
*/
private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
Object authorities = map.get(AUTHORITIES);
if (authorities instanceof String) {
return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
}
if (authorities instanceof Collection) {
return AuthorityUtils.commaSeparatedStringToAuthorityList(
StringUtils.collectionToCommaDelimitedString((Collection<?>) authorities));
}
throw new IllegalArgumentException("Authorities must be either a String or a Collection");
}
}

+ 34
- 0
tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/security/OAuthAccessDeniedHandler.java View File

@@ -0,0 +1,34 @@
package com.tuoheng.common.security.security;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class OAuthAccessDeniedHandler implements AccessDeniedHandler {

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.setContentType("application/json;charset=UTF-8");
Map<String, Object> map = new HashMap<String, Object>();
map.put("code", 401);
map.put("msg", "权限不足");
map.put("data", accessDeniedException.getMessage());
map.put("success", false);
map.put("path", request.getServletPath());
map.put("timestamp", String.valueOf(new Date().getTime()));
ObjectMapper mapper = new ObjectMapper();
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write(mapper.writeValueAsString(map));
}
}

+ 40
- 0
tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/security/OAuthAuthExceptionEntryPoint.java View File

@@ -0,0 +1,40 @@
package com.tuoheng.common.security.security;

import com.alibaba.fastjson.JSONObject;
import com.tuoheng.common.security.utils.JsonResult;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class OAuthAuthExceptionEntryPoint implements AuthenticationEntryPoint {

@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.setStatus(HttpStatus.OK.value());
response.setHeader("Content-Type", "application/json;charset=UTF-8");
// httpServletResponse.setContentType("application/json; charset=utf-8");
// httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
Throwable cause = authException.getCause();
try {
if (cause instanceof InvalidTokenException) {
// 无效的token
JsonResult jsonResult = new JsonResult();
response.getWriter().write(JSONObject.toJSON(jsonResult.error(401, "请先登录")).toString());
} else {
// 访问此资源需要完全的身份验证
JsonResult jsonResult = new JsonResult();
response.getWriter().write(JSONObject.toJSON(jsonResult.error(401, "访问此资源需要完全的身份验证")).toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

+ 23
- 0
tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/security/SecurityImportBeanDefinitionRegistrar.java View File

@@ -0,0 +1,23 @@
package com.tuoheng.common.security.security;

import com.tuoheng.common.security.config.ResourceServerConfig;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

/**
* 注册自动加载类
*/
public class SecurityImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
// ImportBeanDefinitionRegistrar.super.registerBeanDefinitions(importingClassMetadata, registry);
Class<ResourceServerConfig> aClass = ResourceServerConfig.class;
String beanName = StringUtils.uncapitalize(aClass.getSimpleName());
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(ResourceServerConfig.class);
registry.registerBeanDefinition(beanName, beanDefinitionBuilder.getBeanDefinition());
}
}

+ 99
- 0
tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/utils/JsonResult.java View File

@@ -0,0 +1,99 @@
package com.tuoheng.common.security.utils;

import java.io.Serializable;

/**
* JSON回应类
*
* @author 牧羊人
* @date 2019/11/28
*/
public class JsonResult<T> implements Serializable {

private static final long serialVersionUID = 1L;

/**
* 成功
*/
public static final int SUCCESS = 0;

/**
* 失败
*/
public static final int error = -1;

private int code;

private String msg;

private T data;

public static <T> JsonResult<T> success() {
return jsonResult(null, SUCCESS, "操作成功");
}

public static <T> JsonResult<T> success(String msg) {
return jsonResult(null, SUCCESS, msg);
}

public static <T> JsonResult<T> success(T data) {
return jsonResult(data, SUCCESS, "操作成功");
}

public static <T> JsonResult<T> success(T data, String msg) {
return jsonResult(data, SUCCESS, msg);
}

public static <T> JsonResult<T> error() {
return jsonResult(null, error, "操作失败");
}

public static <T> JsonResult<T> error(String msg) {
return jsonResult(null, error, msg);
}

public static <T> JsonResult<T> error(T data) {
return jsonResult(data, error, "操作失败");
}

public static <T> JsonResult<T> error(T data, String msg) {
return jsonResult(data, error, msg);
}

public static <T> JsonResult<T> error(int code, String msg) {
return jsonResult(null, code, msg);
}

private static <T> JsonResult<T> jsonResult(T data, int code, String msg) {
JsonResult<T> result = new JsonResult<>();
result.setCode(code);
result.setData(data);
result.setMsg(msg);
return result;
}

public int getCode() {
return code;
}

public void setCode(int code) {
this.code = code;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public T getData() {
return data;
}

public void setData(T data) {
this.data = data;
}

}

+ 78
- 0
tuoheng-common/tuoheng-common-security/src/main/java/com/tuoheng/common/security/utils/SecurityUtils.java View File

@@ -0,0 +1,78 @@
package com.tuoheng.common.security.utils;

import com.tuoheng.common.security.entity.SecurityUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class SecurityUtils {

/**
* 获取用户ID
*
* @return
*/
public static Integer getUserId() {
return getSecurityUser().getUserId();
}

/**
* 获取用户认证信息
*
* @return
*/
public static SecurityUser getSecurityUser() {
Authentication authentication = getAuthentication();
if (authentication == null) {
return null;
}
return getLoginUser(authentication);
}

/**
* 获取认证信息
*
* @return
*/
public static Authentication getAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}

/**
* 获取用户登录信息
*
* @param authentication
* @return
*/
public static SecurityUser getLoginUser(Authentication authentication) {
Object principal = authentication.getPrincipal();
if (principal instanceof SecurityUser) {
return (SecurityUser) principal;
}
return null;
}

/**
* 生成加密密码
*
* @param password 密码
* @return 加密字符串
*/
public static String encryptPassword(String password) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.encode(password);
}

/**
* 比对密码是否一直
*
* @param password 原始密码
* @param encodedPassword 加密后的密码
* @return
*/
public static boolean matchesPassword(String password, String encodedPassword) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.matches(password, encodedPassword);
}

}

BIN
tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/annotation/EnableCustomConfig.class View File


BIN
tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/annotation/EnableTHFeignClients.class View File


BIN
tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/config/OAuth2FeignConfig.class View File


BIN
tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/config/ResourceServerConfig.class View File


BIN
tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/constant/SecurityConstant.class View File


BIN
tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/entity/SecurityUser.class View File


BIN
tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/interceptor/OAuth2FeignRequestInterceptor.class View File


BIN
tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/security/CustomUserAuthenticationConverter.class View File


BIN
tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/security/OAuthAccessDeniedHandler.class View File


BIN
tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/security/OAuthAuthExceptionEntryPoint.class View File


BIN
tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/security/SecurityImportBeanDefinitionRegistrar.class View File


BIN
tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/utils/JsonResult.class View File


BIN
tuoheng-common/tuoheng-common-security/target/classes/com/tuoheng/common/security/utils/SecurityUtils.class View File


+ 159
- 0
tuoheng-common/tuoheng-common-security/tuoheng-common-security.iml View File

@@ -0,0 +1,159 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="web" name="Web">
<configuration>
<webroots />
</configuration>
</facet>
<facet type="Spring" name="Spring">
<configuration>
<fileset id="fileset" name="Spring 应用程序上下文" removed="false">
<file>file://$MODULE_DIR$/src/main/java/com/tuoheng/common/security/config/ResourceServerConfig.java</file>
</fileset>
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-starter-oauth2:2.2.5.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.1.2.RELEASE" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.13.3" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.13.3" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.13.3" level="project" />
<orderEntry type="library" name="Maven: com.sun.xml.bind:jaxb-core:2.3.0.1" level="project" />
<orderEntry type="library" name="Maven: com.sun.xml.bind:jaxb-impl:2.3.0.1" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security.oauth:spring-security-oauth2:2.3.4.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security:spring-security-core:5.7.1" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security:spring-security-config:5.7.1" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security:spring-security-web:5.7.1" level="project" />
<orderEntry type="library" name="Maven: commons-codec:commons-codec:1.15" level="project" />
<orderEntry type="library" name="Maven: org.codehaus.jackson:jackson-mapper-asl:1.9.13" level="project" />
<orderEntry type="library" name="Maven: org.codehaus.jackson:jackson-core-asl:1.9.13" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security:spring-security-jwt:1.0.9.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.bouncycastle:bcpkix-jdk15on:1.56" level="project" />
<orderEntry type="library" name="Maven: org.bouncycastle:bcprov-jdk15on:1.56" level="project" />
<orderEntry type="library" name="Maven: javax.activation:javax.activation-api:1.2.0" level="project" />
<orderEntry type="library" name="Maven: javax.xml.bind:jaxb-api:2.3.1" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jaxb:jaxb-runtime:2.3.6" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jaxb:txw2:2.3.6" level="project" />
<orderEntry type="library" name="Maven: com.sun.istack:istack-commons-runtime:3.0.12" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: com.sun.activation:jakarta.activation:1.2.2" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-starter-security:2.1.4.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-starter:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-context:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security:spring-security-rsa:1.0.10.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-actuator:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-actuator-autoconfigure:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-actuator:2.7.0" level="project" />
<orderEntry type="library" name="Maven: io.micrometer:micrometer-core:1.9.0" level="project" />
<orderEntry type="library" name="Maven: org.hdrhistogram:HdrHistogram:2.1.12" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.latencyutils:LatencyUtils:2.0.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-security:2.1.4.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-security:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-data-redis:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-logging:2.7.0" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-classic:1.2.11" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-core:1.2.11" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-to-slf4j:2.17.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-api:2.17.2" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:1.7.36" level="project" />
<orderEntry type="library" name="Maven: jakarta.annotation:jakarta.annotation-api:1.3.5" level="project" />
<orderEntry type="library" name="Maven: org.yaml:snakeyaml:1.30" level="project" />
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-redis:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-keyvalue:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-commons:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-tx:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-oxm:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-aop:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-context-support:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.36" level="project" />
<orderEntry type="library" name="Maven: io.lettuce:lettuce-core:6.1.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-common:4.1.77.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-handler:4.1.77.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-resolver:4.1.77.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-buffer:4.1.77.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-codec:4.1.77.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-transport:4.1.77.Final" level="project" />
<orderEntry type="library" name="Maven: io.projectreactor:reactor-core:3.4.18" level="project" />
<orderEntry type="library" name="Maven: org.reactivestreams:reactive-streams:1.0.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-starter-openfeign:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-openfeign-core:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-aop:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.aspectj:aspectjweaver:1.9.7" level="project" />
<orderEntry type="library" name="Maven: io.github.openfeign.form:feign-form-spring:3.8.0" level="project" />
<orderEntry type="library" name="Maven: io.github.openfeign.form:feign-form:3.8.0" level="project" />
<orderEntry type="library" name="Maven: commons-fileupload:commons-fileupload:1.4" level="project" />
<orderEntry type="library" name="Maven: commons-io:commons-io:2.5" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-web:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-beans:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-commons:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security:spring-security-crypto:5.7.1" level="project" />
<orderEntry type="library" name="Maven: io.github.openfeign:feign-core:11.8" level="project" />
<orderEntry type="library" name="Maven: io.github.openfeign:feign-slf4j:11.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-web:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-json:2.7.0" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.13.3" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.13.3" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.module:jackson-module-parameter-names:2.13.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-tomcat:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-core:9.0.63" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-el:9.0.63" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-websocket:9.0.63" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-webmvc:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-context:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-expression:5.3.20" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-boot-starter:3.2.0" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus:3.2.0" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-extension:3.2.0" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-core:3.2.0" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-annotation:3.2.0" level="project" />
<orderEntry type="library" name="Maven: com.github.jsqlparser:jsqlparser:2.1" level="project" />
<orderEntry type="library" name="Maven: org.mybatis:mybatis:3.5.2" level="project" />
<orderEntry type="library" name="Maven: org.mybatis:mybatis-spring:2.0.2" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-autoconfigure:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-jdbc:2.7.0" level="project" />
<orderEntry type="library" name="Maven: com.zaxxer:HikariCP:4.0.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-jdbc:5.3.20" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:fastjson:1.2.76" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-starter-test:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test-autoconfigure:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.jayway.jsonpath:json-path:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:json-smart:2.4.8" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:accessors-smart:2.4.8" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.ow2.asm:asm:9.1" level="project" />
<orderEntry type="library" name="Maven: jakarta.xml.bind:jakarta.xml.bind-api:2.3.3" level="project" />
<orderEntry type="library" name="Maven: jakarta.activation:jakarta.activation-api:1.2.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.assertj:assertj-core:3.22.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest:2.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-api:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.opentest4j:opentest4j:1.2.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.platform:junit-platform-commons:1.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apiguardian:apiguardian-api:1.1.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-params:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-engine:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.platform:junit-platform-engine:1.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-core:4.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy:1.12.10" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy-agent:1.12.10" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.objenesis:objenesis:3.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-junit-jupiter:4.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.skyscreamer:jsonassert:1.5.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.vaadin.external.google:android-json:0.0.20131108.vaadin1" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-core:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-jcl:5.3.20" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-test:5.3.20" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.xmlunit:xmlunit-core:2.9.0" level="project" />
</component>
</module>

+ 58
- 0
tuoheng-common/tuoheng-common.iml View File

@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-starter-test:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-starter:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-context:5.3.20" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-aop:5.3.20" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-beans:5.3.20" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-expression:5.3.20" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-autoconfigure:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-starter-logging:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: ch.qos.logback:logback-classic:1.2.11" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: ch.qos.logback:logback-core:1.2.11" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.logging.log4j:log4j-to-slf4j:2.17.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.logging.log4j:log4j-api:2.17.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.slf4j:jul-to-slf4j:1.7.36" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: jakarta.annotation:jakarta.annotation-api:1.3.5" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.yaml:snakeyaml:1.30" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test-autoconfigure:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.jayway.jsonpath:json-path:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:json-smart:2.4.8" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:accessors-smart:2.4.8" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.ow2.asm:asm:9.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.slf4j:slf4j-api:1.7.36" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: jakarta.xml.bind:jakarta.xml.bind-api:2.3.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: jakarta.activation:jakarta.activation-api:1.2.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.assertj:assertj-core:3.22.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest:2.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-api:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.opentest4j:opentest4j:1.2.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.platform:junit-platform-commons:1.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apiguardian:apiguardian-api:1.1.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-params:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-engine:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.platform:junit-platform-engine:1.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-core:4.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy:1.12.10" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy-agent:1.12.10" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.objenesis:objenesis:3.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-junit-jupiter:4.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.skyscreamer:jsonassert:1.5.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.vaadin.external.google:android-json:0.0.20131108.vaadin1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-core:5.3.20" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-jcl:5.3.20" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-test:5.3.20" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.xmlunit:xmlunit-core:2.9.0" level="project" />
</component>
</module>

+ 87
- 0
tuoheng-eureka/pom.xml View File

@@ -0,0 +1,87 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>tuoheng</artifactId>
<groupId>com.tuoheng</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>tuoheng-eureka</artifactId>
<groupId>com.tuoheng</groupId>
<version>1.0.0</version>
<name>tuoheng-eureka</name>
<description>微服务注册中心</description>
<packaging>jar</packaging>

<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>

<build>
<finalName>tuoheng-eureka</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>

<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.*</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>

<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<targetPath>WEB-INF/classes</targetPath>
<includes>
<include>application.yml</include>
</includes>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.1.11.RELEASE</version>
<configuration>
<finalName>${project.build.finalName}</finalName>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

</project>

+ 16
- 0
tuoheng-eureka/src/main/java/com/tuoheng/eureka/THEurekaApplication.java View File

@@ -0,0 +1,16 @@
package com.tuoheng.eureka;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class THEurekaApplication {

public static void main(String[] args) {
SpringApplication.run(THEurekaApplication.class, args);
System.out.println("(♥◠‿◠)ノ゙ 微服务【注册中心】启动成功 ლ(´ڡ`ლ)゙");
}

}

+ 26
- 0
tuoheng-eureka/src/main/resources/application.yml View File

@@ -0,0 +1,26 @@
server:
port: 9010 # 服务端口

spring:
application:
name: eurka-server # 服务名称
security:
user:
name: root #定义账户
password: root #定义密码

eureka:
instance:
hostname: localhost # 设置主机名
client:
registerWithEureka: false # 是否向 Eureka 注册服务。该应用为服务注册中心,不需要自注册,设置为 false
fetchRegistry: false # 是否检索服务。该应用为服务注册中心,职责为注册和发现服务,无需检索服务,设置为 false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ # 注册中心url
server: #配置属性,但由于 Eureka 自我保护模式以及心跳周期长的原因,经常会遇到 Eureka Server 不剔除已关停的节点的问题
enable-self-preservation: false
eviction-interval-timer-in-ms: 5000

logging:
level:
root: info

+ 26
- 0
tuoheng-eureka/target/classes/WEB-INF/classes/application.yml View File

@@ -0,0 +1,26 @@
server:
port: 9010 # 服务端口

spring:
application:
name: eurka-server # 服务名称
security:
user:
name: root #定义账户
password: root #定义密码

eureka:
instance:
hostname: localhost # 设置主机名
client:
registerWithEureka: false # 是否向 Eureka 注册服务。该应用为服务注册中心,不需要自注册,设置为 false
fetchRegistry: false # 是否检索服务。该应用为服务注册中心,职责为注册和发现服务,无需检索服务,设置为 false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ # 注册中心url
server: #配置属性,但由于 Eureka 自我保护模式以及心跳周期长的原因,经常会遇到 Eureka Server 不剔除已关停的节点的问题
enable-self-preservation: false
eviction-interval-timer-in-ms: 5000

logging:
level:
root: info

+ 26
- 0
tuoheng-eureka/target/classes/application.yml View File

@@ -0,0 +1,26 @@
server:
port: 9010 # 服务端口

spring:
application:
name: eurka-server # 服务名称
security:
user:
name: root #定义账户
password: root #定义密码

eureka:
instance:
hostname: localhost # 设置主机名
client:
registerWithEureka: false # 是否向 Eureka 注册服务。该应用为服务注册中心,不需要自注册,设置为 false
fetchRegistry: false # 是否检索服务。该应用为服务注册中心,职责为注册和发现服务,无需检索服务,设置为 false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ # 注册中心url
server: #配置属性,但由于 Eureka 自我保护模式以及心跳周期长的原因,经常会遇到 Eureka Server 不剔除已关停的节点的问题
enable-self-preservation: false
eviction-interval-timer-in-ms: 5000

logging:
level:
root: info

BIN
tuoheng-eureka/target/classes/com/tuoheng/eureka/THEurekaApplication.class View File


+ 147
- 0
tuoheng-eureka/tuoheng-eureka.iml View File

@@ -0,0 +1,147 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="web" name="Web">
<configuration>
<webroots />
</configuration>
</facet>
<facet type="Spring" name="Spring">
<configuration />
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-starter-netflix-eureka-server:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-starter:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-context:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security:spring-security-crypto:5.7.1" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-commons:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.security:spring-security-rsa:1.0.10.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.bouncycastle:bcpkix-jdk15on:1.68" level="project" />
<orderEntry type="library" name="Maven: org.bouncycastle:bcprov-jdk15on:1.68" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-netflix-eureka-server:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-web:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-json:2.7.0" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.13.3" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.13.3" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.module:jackson-module-parameter-names:2.13.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-tomcat:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-core:9.0.63" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-el:9.0.63" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-websocket:9.0.63" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-web:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-beans:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-webmvc:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-aop:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-expression:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-actuator:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-actuator-autoconfigure:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-actuator:2.7.0" level="project" />
<orderEntry type="library" name="Maven: io.micrometer:micrometer-core:1.9.0" level="project" />
<orderEntry type="library" name="Maven: org.hdrhistogram:HdrHistogram:2.1.12" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.latencyutils:LatencyUtils:2.0.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-freemarker:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.freemarker:freemarker:2.3.31" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-context-support:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-netflix-eureka-client:3.1.3" level="project" />
<orderEntry type="library" name="Maven: com.netflix.eureka:eureka-client:1.10.17" level="project" />
<orderEntry type="library" name="Maven: com.netflix.netflix-commons:netflix-eventbus:0.3.0" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: com.netflix.netflix-commons:netflix-infix:0.3.0" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: commons-jxpath:commons-jxpath:1.3" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: joda-time:joda-time:2.3" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.antlr:antlr-runtime:3.4" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.antlr:stringtemplate:3.2.1" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: antlr:antlr:2.7.7" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: com.google.code.gson:gson:2.9.0" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.apache.commons:commons-math:2.2" level="project" />
<orderEntry type="library" name="Maven: com.thoughtworks.xstream:xstream:1.4.18" level="project" />
<orderEntry type="library" name="Maven: io.github.x-stream:mxparser:1.2.2" level="project" />
<orderEntry type="library" name="Maven: xmlpull:xmlpull:1.1.3.1" level="project" />
<orderEntry type="library" name="Maven: javax.ws.rs:jsr311-api:1.1.1" level="project" />
<orderEntry type="library" name="Maven: com.netflix.servo:servo-core:0.12.21" level="project" />
<orderEntry type="library" name="Maven: com.google.guava:guava:19.0" level="project" />
<orderEntry type="library" name="Maven: com.sun.jersey:jersey-core:1.19.1" level="project" />
<orderEntry type="library" name="Maven: com.sun.jersey.contribs:jersey-apache-client4:1.19.1" level="project" />
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpclient:4.5.13" level="project" />
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpcore:4.4.15" level="project" />
<orderEntry type="library" name="Maven: commons-codec:commons-codec:1.15" level="project" />
<orderEntry type="library" name="Maven: commons-configuration:commons-configuration:1.10" level="project" />
<orderEntry type="library" name="Maven: commons-lang:commons-lang:2.6" level="project" />
<orderEntry type="library" name="Maven: com.google.inject:guice:4.1.0" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.13.3" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.13.3" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.13.3" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.codehaus.jettison:jettison:1.4.0" level="project" />
<orderEntry type="library" name="Maven: com.sun.jersey:jersey-servlet:1.19.4" level="project" />
<orderEntry type="library" name="Maven: com.sun.jersey:jersey-server:1.19.4" level="project" />
<orderEntry type="library" name="Maven: com.sun.jersey:jersey-client:1.19.4" level="project" />
<orderEntry type="library" name="Maven: com.netflix.eureka:eureka-core:1.10.17" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.woodstox:woodstox-core:6.2.1" level="project" />
<orderEntry type="library" name="Maven: javax.inject:javax.inject:1" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.13.3" level="project" />
<orderEntry type="library" name="Maven: org.codehaus.woodstox:stax2-api:4.2.1" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-starter-loadbalancer:3.1.3" level="project" />
<orderEntry type="library" name="Maven: org.springframework.cloud:spring-cloud-loadbalancer:3.1.3" level="project" />
<orderEntry type="library" name="Maven: io.projectreactor:reactor-core:3.4.18" level="project" />
<orderEntry type="library" name="Maven: org.reactivestreams:reactive-streams:1.0.3" level="project" />
<orderEntry type="library" name="Maven: io.projectreactor.addons:reactor-extra:3.4.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-cache:2.7.0" level="project" />
<orderEntry type="library" name="Maven: com.stoyanr:evictor:1.0.0" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jaxb:jaxb-runtime:2.3.6" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jaxb:txw2:2.3.6" level="project" />
<orderEntry type="library" name="Maven: com.sun.istack:istack-commons-runtime:3.0.12" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: com.sun.activation:jakarta.activation:1.2.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-starter-test:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-context:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-autoconfigure:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-logging:2.7.0" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-classic:1.2.11" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-core:1.2.11" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-to-slf4j:2.17.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-api:2.17.2" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:1.7.36" level="project" />
<orderEntry type="library" name="Maven: jakarta.annotation:jakarta.annotation-api:1.3.5" level="project" />
<orderEntry type="library" name="Maven: org.yaml:snakeyaml:1.30" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test-autoconfigure:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.jayway.jsonpath:json-path:2.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:json-smart:2.4.8" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:accessors-smart:2.4.8" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.ow2.asm:asm:9.1" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.36" level="project" />
<orderEntry type="library" name="Maven: jakarta.xml.bind:jakarta.xml.bind-api:2.3.3" level="project" />
<orderEntry type="library" name="Maven: jakarta.activation:jakarta.activation-api:1.2.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.assertj:assertj-core:3.22.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest:2.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-api:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.opentest4j:opentest4j:1.2.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.platform:junit-platform-commons:1.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apiguardian:apiguardian-api:1.1.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-params:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-engine:5.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.platform:junit-platform-engine:1.8.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-core:4.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy:1.12.10" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy-agent:1.12.10" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.objenesis:objenesis:3.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-junit-jupiter:4.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.skyscreamer:jsonassert:1.5.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.vaadin.external.google:android-json:0.0.20131108.vaadin1" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-core:5.3.20" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-jcl:5.3.20" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-test:5.3.20" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.xmlunit:xmlunit-core:2.9.0" level="project" />
</component>
</module>

+ 151
- 0
tuoheng-gateway/pom.xml View File

@@ -0,0 +1,151 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>tuoheng</artifactId>
<groupId>com.tuoheng</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>tuoheng-gateway</artifactId>
<groupId>com.tuoheng</groupId>
<version>1.0.0</version>
<name>tuoheng-gateway</name>
<description>微服务网关</description>
<packaging>jar</packaging>

<dependencies>
<!-- 微服务Gateway网关依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<!-- <exclusions>-->
<!-- <exclusion>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-web</artifactId>-->
<!-- </exclusion>-->
<!-- </exclusions>-->
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>-->
<!-- <version>2.2.10.RELEASE</version>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
</dependencies>

<profiles>
<!-- 本地开发环境 -->
<profile>
<id>local</id>
<properties>
<package.environment>local</package.environment>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<!-- 开发环境 -->
<profile>
<id>dev</id>
<properties>
<package.environment>dev</package.environment>
</properties>
</profile>
<!-- 测试环境 -->
<profile>
<id>test</id>
<properties>
<package.environment>test</package.environment>
</properties>
</profile>
<!-- 生产环境 -->
<profile>
<id>prod</id>
<properties>
<package.environment>prod</package.environment>
</properties>
</profile>
</profiles>

<build>
<finalName>tuoheng_paas_gateway</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>

<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.*</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>

<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<targetPath>WEB-INF/classes</targetPath>
<includes>
<include>application-${package.environment}.yml</include>
</includes>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.1.11.RELEASE</version>
<configuration>
<finalName>${project.build.finalName}</finalName>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>

</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

</project>

+ 18
- 0
tuoheng-gateway/src/main/java/com/tuoheng/gateway/THGatewayApplication.java View File

@@ -0,0 +1,18 @@
package com.tuoheng.gateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@EnableDiscoveryClient
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
//@EnableHystrix
public class THGatewayApplication {

public static void main(String[] args) {
SpringApplication.run(THGatewayApplication.class, args);
System.out.println("(♥◠‿◠)ノ゙ 微服务【网关服务】启动成功 ლ(´ڡ`ლ)゙");
}

}

+ 36
- 0
tuoheng-gateway/src/main/java/com/tuoheng/gateway/config/GatewayCorsConfig.java View File

@@ -0,0 +1,36 @@
package com.tuoheng.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

/**
* 跨域配置
*/
@Configuration
public class GatewayCorsConfig {

/**
* 跨域处理
*
* @return
*/
@Bean
public CorsWebFilter corsFilter() {

// 跨域请求配置
CorsConfiguration configuration = new CorsConfiguration();
// 在生产环境上最好指定域名,以免产生跨域安全问题
configuration.addAllowedOrigin("*");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", configuration);

return new CorsWebFilter(source);
}
}

+ 34
- 0
tuoheng-gateway/src/main/java/com/tuoheng/gateway/config/GatewayExceptionConfig.java View File

@@ -0,0 +1,34 @@
package com.tuoheng.gateway.config;

import com.tuoheng.gateway.exception.GatewayExceptionHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import java.util.Collections;
import java.util.List;

/**
* 网关异常配置
*/
@Configuration
public class GatewayExceptionConfig {

@Primary
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public ErrorWebExceptionHandler errorWebExceptionHandler(ObjectProvider<List<ViewResolver>> viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer) {
GatewayExceptionHandler gatewayExceptionHandler = new GatewayExceptionHandler();
gatewayExceptionHandler.setViewResolvers(viewResolversProvider.getIfAvailable(Collections::emptyList));
gatewayExceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
gatewayExceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
return gatewayExceptionHandler;
}

}

+ 107
- 0
tuoheng-gateway/src/main/java/com/tuoheng/gateway/config/GatewayFilterConfig.java View File

@@ -0,0 +1,107 @@
package com.tuoheng.gateway.config;

import com.tuoheng.gateway.constant.RSAConstant;
import com.tuoheng.gateway.utils.FilterUtils;
import com.tuoheng.gateway.utils.RSAUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.factory.rewrite.CachedBodyOutputMessage;
import org.springframework.cloud.gateway.support.BodyInserterContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ReactiveHttpOutputMessage;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.reactive.function.BodyInserter;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerStrategies;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.lang.reflect.Field;
import java.net.URI;

/**
* 网关全局过滤器
*/
@Configuration
public class GatewayFilterConfig implements GlobalFilter, Ordered {

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 如果是登录不校验Token
String requestUrl = exchange.getRequest().getPath().value();
AntPathMatcher pathMatcher = new AntPathMatcher();
// 非登录请求统一需要认证
if (!pathMatcher.match("/api/auth/oauth/**", requestUrl)) {
String token = exchange.getRequest().getHeaders().getFirst("Authorization");
if (StringUtils.isBlank(token)) {
return FilterUtils.invalidToken(exchange);
}
}
// // 修改请求参数,并获取请求参数
// try {
// updateRequestParam(exchange);
// } catch (Exception e) {
// return FilterUtils.invalidUrl(exchange);
// }
// // 获取请求体,修改请求体
// ServerRequest serverRequest = ServerRequest.create(exchange, HandlerStrategies.withDefaults().messageReaders());
// Mono<String> modifiedBody = serverRequest.bodyToMono(String.class).flatMap(body -> {
// String encrypt = RSAUtils.decrypt(body, RSAConstant.PRIVATE_KEY);
// return Mono.just(encrypt);
// });
//
// // 创建BodyInserter修改请求体
// BodyInserter<Mono<String>, ReactiveHttpOutputMessage> bodyInserter = BodyInserters.fromPublisher(modifiedBody, String.class);
// HttpHeaders headers = new HttpHeaders();
// headers.putAll(exchange.getRequest().getHeaders());
// headers.remove(HttpHeaders.CONTENT_LENGTH);
// // 创建CachedBodyOutputMessage并且把请求param加入
// CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(exchange, headers);
// return bodyInserter.insert(outputMessage, new BodyInserterContext()).then(Mono.defer(() -> {
// ServerHttpRequestDecorator decorator = new ServerHttpRequestDecorator(exchange.getRequest()) {
// @Override
// public Flux<DataBuffer> getBody() {
// return outputMessage.getBody();
// }
// };
// return chain.filter(exchange.mutate().request(decorator).build());
// }));
// 放行
return chain.filter(exchange);
}

/**
* 修改前端传的参数
*/
private void updateRequestParam(ServerWebExchange exchange) throws NoSuchFieldException, IllegalAccessException {
ServerHttpRequest request = exchange.getRequest();
URI uri = request.getURI();
String query = uri.getQuery();
if (StringUtils.isNotBlank(query) && query.contains("param")) {
String[] split = query.split("=");
String param = RSAUtils.decrypt(split[1], RSAConstant.PRIVATE_KEY);
Field targetQuery = uri.getClass().getDeclaredField("query");
targetQuery.setAccessible(true);
targetQuery.set(uri, param);
}
}

/**
* 这是Ordered接口的中的方法
* 过滤器有一个优先级的问题,这个值越小,优先级越高
*
* @return
*/
@Override
public int getOrder() {
return 0;
}
}

+ 10
- 0
tuoheng-gateway/src/main/java/com/tuoheng/gateway/constant/RSAConstant.java View File

@@ -0,0 +1,10 @@
package com.tuoheng.gateway.constant;

/**
* RSA常量
*/
public class RSAConstant {

public static final String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIW1OUvrUiogZ359EtSEnQyOyoVcUmzAKiEnjmbnVa9vEM9E/eCWVbRYKGTvgPkkQ6kwNJajgLtF+gaUFE1buRDqpga6RhnmOBinOhPT6Cneif3p9BcTJAnKy/3GJM8h2ZJddVWPUcA4nDb1FvPEhUpRLPM9e8S1dFO0ILX7CQAlAgMBAAECgYBC4amtbiKFa/wY61tV7pfYRjzLhKi+OUlZmD3E/4Z+4KGZ7DrJ8qkgMtDR3HO5LAikQrare1HTW2d7juqw32ascu+uDObf4yrYNKin+ZDLUYvIDfLhThPxnZJwQ/trdtfxO3VM//XbwZacmwYbAsYW/3QPUXwwOPAgbC2oth8kqQJBANKLyXcdjZx4cwJVl7xNeC847su8y6bPpcBASsaQloCIPiNBIg1h76dpfEGIQBYWJWbBsxtHe/MhOmz7fNFDS2sCQQCiktYZR0dZNH4eNX329LoRuBiltpr9tf36rVOlKr1GSHkLYEHF2qtyXV2mdrY8ZWpvuo3qm1oSLaqmop2rN9avAkBHk85B+IIUF77BpGeZVJzvMOO9z8lMRHuNCE5jgvQnbinxwkrZUdovh+T+QlvHJnBApslFFOBGn51FP5oHamFRAkEAmwZmPsinkrrpoKjlqz6GyCrC5hKRDWoj/IyXfKKaxpCJTH3HeoIghvfdO8Vr1X/n1Q8SESt+4mLFngznSMQAZQJBAJx07bCFYbA2IocfFV5LTEYTIiUeKdue2NP2yWqZ/+tB5H7jNwQTJmX1mn0W/sZm4+nJM7SjfETpNZhH49+rV6U=";

}

+ 22
- 0
tuoheng-gateway/src/main/java/com/tuoheng/gateway/controller/FallBackController.java View File

@@ -0,0 +1,22 @@
package com.tuoheng.gateway.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* 网关熔断机制,添加fallback方法
*/
@RestController
public class FallBackController {

/**
* 网关熔断机制
*
* @return
*/
@RequestMapping("/fallback")
public String fallback() {
return "系统繁忙,请稍后再试!";
}

}

+ 55
- 0
tuoheng-gateway/src/main/java/com/tuoheng/gateway/controller/TestController.java View File

@@ -0,0 +1,55 @@
package com.tuoheng.gateway.controller;


import com.alibaba.fastjson.JSONObject;
import com.tuoheng.gateway.utils.RSAUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/rsa")
public class TestController {

/**
* 用测试生成的公钥,私钥赋值
*/
private static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCFtTlL61IqIGd+fRLUhJ0MjsqFXFJswCohJ45m51WvbxDPRP3gllW0WChk74D5JEOpMDSWo4C7RfoGlBRNW7kQ6qYGukYZ5jgYpzoT0+gp3on96fQXEyQJysv9xiTPIdmSXXVVj1HAOJw29RbzxIVKUSzzPXvEtXRTtCC1+wkAJQIDAQAB";

private static final String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIW1OUvrUiogZ359EtSEnQyOyoVcUmzAKiEnjmbnVa9vEM9E/eCWVbRYKGTvgPkkQ6kwNJajgLtF+gaUFE1buRDqpga6RhnmOBinOhPT6Cneif3p9BcTJAnKy/3GJM8h2ZJddVWPUcA4nDb1FvPEhUpRLPM9e8S1dFO0ILX7CQAlAgMBAAECgYBC4amtbiKFa/wY61tV7pfYRjzLhKi+OUlZmD3E/4Z+4KGZ7DrJ8qkgMtDR3HO5LAikQrare1HTW2d7juqw32ascu+uDObf4yrYNKin+ZDLUYvIDfLhThPxnZJwQ/trdtfxO3VM//XbwZacmwYbAsYW/3QPUXwwOPAgbC2oth8kqQJBANKLyXcdjZx4cwJVl7xNeC847su8y6bPpcBASsaQloCIPiNBIg1h76dpfEGIQBYWJWbBsxtHe/MhOmz7fNFDS2sCQQCiktYZR0dZNH4eNX329LoRuBiltpr9tf36rVOlKr1GSHkLYEHF2qtyXV2mdrY8ZWpvuo3qm1oSLaqmop2rN9avAkBHk85B+IIUF77BpGeZVJzvMOO9z8lMRHuNCE5jgvQnbinxwkrZUdovh+T+QlvHJnBApslFFOBGn51FP5oHamFRAkEAmwZmPsinkrrpoKjlqz6GyCrC5hKRDWoj/IyXfKKaxpCJTH3HeoIghvfdO8Vr1X/n1Q8SESt+4mLFngznSMQAZQJBAJx07bCFYbA2IocfFV5LTEYTIiUeKdue2NP2yWqZ/+tB5H7jNwQTJmX1mn0W/sZm4+nJM7SjfETpNZhH49+rV6U=";


/**
* 生成公钥私钥
*/
@GetMapping("/generateRsaKey")
public void generateRsaKey() {
Map<String, String> map = RSAUtils.generateRasKey();
System.out.println("随机生成的公钥为:" + map.get(RSAUtils.PUBLIC_KEY));
System.out.println("随机生成的私钥为:" + map.get(RSAUtils.PRIVATE_KEY));

}

/**
* 加密: Yeidauky/iN1/whevov2+ntzXJKAp2AHfESu5ixnDqH5iB7ww+TcfqJpDfkPHfb12Y0sVXw0gBHNJ4inkh7l2/SJBze3pKQU/mg3oyDokTia3JZIs+e80/iJcSfN+yA1JaqY+eJPYiBiOGAF2S6x0ynvJg/Wj0fwp2Tq3PDzRMo=
*/
@GetMapping("/testEncrypt")
public void testEncrypt() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "rosh");
jsonObject.put("password", "123456");
String str = jsonObject.toJSONString();
String encrypt = RSAUtils.encrypt(str, PUBLIC_KEY);
System.out.println(encrypt);
}

@GetMapping("/testDecrypt")
public void testDecrypt() {
String decrypt = RSAUtils.decrypt("Yeidauky/iN1/whevov2+ntzXJKAp2AHfESu5ixnDqH5iB7ww+TcfqJpDfkPHfb12Y0sVXw0gBHNJ4inkh7l2/SJBze3pKQU/mg3oyDokTia3JZIs+e80/iJcSfN+yA1JaqY+eJPYiBiOGAF2S6x0ynvJg/Wj0fwp2Tq3PDzRMo=",
PRIVATE_KEY);
System.out.println(decrypt);
}

}

+ 29
- 0
tuoheng-gateway/src/main/java/com/tuoheng/gateway/exception/AbstractExceptionHandler.java View File

@@ -0,0 +1,29 @@
package com.tuoheng.gateway.exception;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;

/**
* 抽象异常处理
*/
public abstract class AbstractExceptionHandler {

protected JSONObject buildErrorMap(Throwable ex) {
JSONObject json = new JSONObject();
if (ex instanceof RSAException || ex instanceof IllegalArgumentException) {
json.put("code", HttpStatus.BAD_REQUEST.value());
if (StringUtils.isNotBlank(ex.getMessage())) {
json.put("msg", ex.getMessage());
} else {
json.put("msg", "无效的请求");
}

} else {
json.put("code", HttpStatus.BAD_REQUEST.value());
json.put("msg", "未知错误联系管理员");
}
return json;
}

}

+ 94
- 0
tuoheng-gateway/src/main/java/com/tuoheng/gateway/exception/GatewayExceptionHandler.java View File

@@ -0,0 +1,94 @@
package com.tuoheng.gateway.exception;

import com.alibaba.fastjson.JSONObject;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.util.Assert;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.List;
import java.util.Map;

//@Slf4j
public class GatewayExceptionHandler extends AbstractExceptionHandler implements ErrorWebExceptionHandler {

private List<HttpMessageReader<?>> messageReaders = Collections.emptyList();


private List<HttpMessageWriter<?>> messageWriters = Collections.emptyList();


private List<ViewResolver> viewResolvers = Collections.emptyList();


private ThreadLocal<JSONObject> exceptionHandlerResult = new ThreadLocal<>();


public void setMessageReaders(List<HttpMessageReader<?>> messageReaders) {
Assert.notNull(messageReaders, "'messageReaders' must not be null");
this.messageReaders = messageReaders;
}


public void setViewResolvers(List<ViewResolver> viewResolvers) {
this.viewResolvers = viewResolvers;
}


public void setMessageWriters(List<HttpMessageWriter<?>> messageWriters) {
Assert.notNull(messageWriters, "'messageWriters' must not be null");
this.messageWriters = messageWriters;
}

@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
JSONObject errorInfo = super.buildErrorMap(ex);
if (exchange.getResponse().isCommitted()) {
return Mono.error(ex);
}
exceptionHandlerResult.set(errorInfo);
ServerRequest newRequest = ServerRequest.create(exchange, this.messageReaders);
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse).route(newRequest)
.switchIfEmpty(Mono.error(ex))
.flatMap(handler -> handler.handle(newRequest))
.flatMap(response -> write(exchange, response));
}

protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
Map<String, Object> result = exceptionHandlerResult.get();
return ServerResponse.status(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(result));
}


private Mono<? extends Void> write(ServerWebExchange exchange,
ServerResponse response) {
exchange.getResponse().getHeaders().setContentType(response.headers().getContentType());
return response.writeTo(exchange, new ResponseContext());
}

private class ResponseContext implements ServerResponse.Context {

@Override
public List<HttpMessageWriter<?>> messageWriters() {
return GatewayExceptionHandler.this.messageWriters;
}

@Override
public List<ViewResolver> viewResolvers() {
return GatewayExceptionHandler.this.viewResolvers;
}
}
}

+ 14
- 0
tuoheng-gateway/src/main/java/com/tuoheng/gateway/exception/RSAException.java View File

@@ -0,0 +1,14 @@
package com.tuoheng.gateway.exception;

import lombok.Getter;

@Getter
public class RSAException extends RuntimeException {

private final String message;

public RSAException(String message) {
this.message = message;
}

}

+ 60
- 0
tuoheng-gateway/src/main/java/com/tuoheng/gateway/utils/FilterUtils.java View File

@@ -0,0 +1,60 @@
package com.tuoheng.gateway.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
* 过滤工具类封装
*/
public class FilterUtils {

/**
* 无效的Token
*
* @param exchange
* @return
*/
public static Mono<Void> invalidToken(ServerWebExchange exchange) {
JSONObject json = new JSONObject();
json.put("code", HttpStatus.UNAUTHORIZED.value());
json.put("msg", "无效的token");
return buildReturnMono(json, exchange);
}

/**
* 无效的请求
*
* @param exchange
* @return
*/
public static Mono<Void> invalidUrl(ServerWebExchange exchange) {
JSONObject json = new JSONObject();
json.put("code", HttpStatus.BAD_REQUEST.value());
json.put("msg", "无效的请求");
return buildReturnMono(json, exchange);
}

/**
* 回应体构建
*
* @param json JSON对象
* @param exchange
* @return
*/
public static Mono<Void> buildReturnMono(JSONObject json, ServerWebExchange exchange) {
ServerHttpResponse response = exchange.getResponse();
byte[] bits = json.toJSONString().getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = response.bufferFactory().wrap(bits);
response.setStatusCode(HttpStatus.UNAUTHORIZED);
//指定编码,否则在浏览器中会中文乱码
response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
return response.writeWith(Mono.just(buffer));
}

}

+ 88
- 0
tuoheng-gateway/src/main/java/com/tuoheng/gateway/utils/RSAUtils.java View File

@@ -0,0 +1,88 @@
package com.tuoheng.gateway.utils;

import com.tuoheng.gateway.exception.RSAException;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

//@Slf4j
public class RSAUtils {

public static final String PUBLIC_KEY = "public_key";

public static final String PRIVATE_KEY = "private_key";


public static Map<String, String> generateRasKey() {
Map<String, String> rs = new HashMap<>();
try {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = null;
keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(1024, new SecureRandom());
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
// 得到私钥 公钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
// 得到私钥字符串
String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
// 将公钥和私钥保存到Map
rs.put(PUBLIC_KEY, publicKeyString);
rs.put(PRIVATE_KEY, privateKeyString);
} catch (Exception e) {
// log.error("RsaUtils invoke genKeyPair failed.", e);
throw new RSAException("RsaUtils invoke genKeyPair failed.");
}
return rs;
}


public static String encrypt(String str, String publicKey) {
try {
//base64编码的公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
return Base64.encodeBase64String(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
} catch (Exception e) {
// log.error("RsaUtils invoke encrypt failed.", e);
throw new RSAException("RsaUtils invoke encrypt failed.");
}
}


public static String decrypt(String str, String privateKey) {

try {
//64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8));
//base64编码的私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
return new String(cipher.doFinal(inputByte));
} catch (Exception e) {
// log.error("RsaUtils invoke decrypt failed.", e);
throw new RSAException("RsaUtils invoke decrypt failed.");
}

}

}

+ 0
- 0
tuoheng-gateway/src/main/resources/application-dev.yml View File


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

Loading…
Cancel
Save