From f9e1a07e7c60e53a96b6f016e088e9686301f03e Mon Sep 17 00:00:00 2001 From: wxz Date: Sun, 23 Aug 2020 00:06:45 +0800 Subject: [PATCH 1/5] =?UTF-8?q?=E5=8A=A8=E6=80=81=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E6=BA=90-=E6=94=AF=E6=8C=81=E5=8F=82=E6=95=B0=E6=96=B9?= =?UTF-8?q?=E5=BC=8F=E6=8C=87=E5=AE=9A=E6=95=B0=E6=8D=AE=E6=BA=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../epmet-commons-dynamic-datasource/pom.xml | 6 +++ .../datasource/aspect/DataSourceAspect.java | 48 +++++++------------ .../datasource/config/DynamicDataSource.java | 8 +++- .../datasource/enums/DataSourceEnum.java | 43 +++++++++++++++++ .../util/AbstractDataSourceNameFetcher.java | 13 +++++ .../HttpRequestDataSourceNameFetcher.java | 44 +++++++++++++++++ .../epmet/constant/DataSourceConstant.java | 1 + .../com/epmet/controller/DemoController.java | 17 +++++++ .../stats/impl/DimAgencyServiceImpl.java | 3 ++ .../src/main/resources/bootstrap.yml | 10 ++++ .../resources/mapper/stats/DimAgencyDao.xml | 1 + 11 files changed, 163 insertions(+), 31 deletions(-) create mode 100644 epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/enums/DataSourceEnum.java create mode 100644 epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/util/AbstractDataSourceNameFetcher.java create mode 100644 epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/util/HttpRequestDataSourceNameFetcher.java diff --git a/epmet-commons/epmet-commons-dynamic-datasource/pom.xml b/epmet-commons/epmet-commons-dynamic-datasource/pom.xml index 07f98a0b56..efb328a391 100644 --- a/epmet-commons/epmet-commons-dynamic-datasource/pom.xml +++ b/epmet-commons/epmet-commons-dynamic-datasource/pom.xml @@ -19,6 +19,12 @@ 2.0.0 provided + + + org.springframework.boot + spring-boot-starter-web + provided + diff --git a/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/aspect/DataSourceAspect.java b/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/aspect/DataSourceAspect.java index 45113847c6..080bda7565 100644 --- a/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/aspect/DataSourceAspect.java +++ b/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/aspect/DataSourceAspect.java @@ -9,8 +9,8 @@ package com.epmet.commons.dynamic.datasource.aspect; import com.epmet.commons.dynamic.datasource.annotation.DataSource; -import com.epmet.commons.dynamic.datasource.bean.DataSourceParam; import com.epmet.commons.dynamic.datasource.config.DynamicContextHolder; +import com.epmet.commons.dynamic.datasource.util.HttpRequestDataSourceNameFetcher; import org.apache.commons.lang3.StringUtils; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; @@ -19,12 +19,12 @@ import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import java.lang.reflect.Method; -import java.lang.reflect.Parameter; /** * 多数据源,切面处理类 @@ -38,6 +38,9 @@ import java.lang.reflect.Parameter; public class DataSourceAspect { protected Logger logger = LoggerFactory.getLogger(getClass()); + @Autowired + private HttpRequestDataSourceNameFetcher httpRequestDataSourceNameFetcher; + @Pointcut("@annotation(com.epmet.commons.dynamic.datasource.annotation.DataSource) " + "|| @within(com.epmet.commons.dynamic.datasource.annotation.DataSource)") public void dataSourcePointCut() { @@ -55,12 +58,14 @@ public class DataSourceAspect { if(targetDataSource != null || methodDataSource != null){ String value; if(methodDataSource != null){ - value = getDatasourceName(methodDataSource, signature.getMethod().getParameters(), point.getArgs()); + value = getDatasourceName(methodDataSource); }else { - value = getDatasourceName(targetDataSource, signature.getMethod().getParameters(), point.getArgs()); + value = getDatasourceName(targetDataSource); } - DynamicContextHolder.push(value); + if (StringUtils.isNotBlank(value)) { + DynamicContextHolder.push(value); + } logger.debug("set datasource is {}", value); } @@ -77,33 +82,16 @@ public class DataSourceAspect { * @param dataSource * @return */ - public String getDatasourceName(DataSource dataSource, Parameter[] methodParameters, Object[] methodArgValues) { + public String getDatasourceName(DataSource dataSource) { + String dataSourceName = null; if (dataSource.datasourceNameFromArg()) { - // 1.从参数中动态获取数据源名称 - String datasourceNameFromParam = getDatasourceNameFromArg(methodParameters, methodArgValues); - if (StringUtils.isNotBlank(datasourceNameFromParam)) { - // 如果有DatasourceParam类型的参数并且设置了datasourceName值,那么返回这个值,否则使用硬编码的 - return datasourceNameFromParam; - } + // 1.优先从http header中动态获取数据源名称 + dataSourceName = httpRequestDataSourceNameFetcher.fetchDataSourceName(); } - // 2.硬编码指定数据源名称 - return dataSource.value(); - } - - /** - * 从参数中取数据源名称 - * @param parameters - * @param argsObject - * @return - */ - public String getDatasourceNameFromArg(Parameter[] parameters, Object[] argsObject) { - for (int i = 0; i < parameters.length; i++) { - if (parameters[i].getType() == DataSourceParam.class) { - DataSourceParam param = (DataSourceParam) argsObject[i]; - return param.getDatasourceName(); - } + // 2.硬编码指定默认的数据源名称 + if (StringUtils.isBlank(dataSourceName)) { + dataSourceName = dataSource.value(); } - - return null; + return dataSourceName; } } diff --git a/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/config/DynamicDataSource.java b/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/config/DynamicDataSource.java index 3fae7e003d..0a9d9adf91 100644 --- a/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/config/DynamicDataSource.java +++ b/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/config/DynamicDataSource.java @@ -8,6 +8,8 @@ package com.epmet.commons.dynamic.datasource.config; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; /** @@ -18,9 +20,13 @@ import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; */ public class DynamicDataSource extends AbstractRoutingDataSource { + private Logger logger = LoggerFactory.getLogger(getClass()); + @Override protected Object determineCurrentLookupKey() { - return DynamicContextHolder.peek(); + String datasourceName = DynamicContextHolder.peek(); + logger.info("使用的数据源名称为:{}", datasourceName); + return datasourceName; } } diff --git a/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/enums/DataSourceEnum.java b/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/enums/DataSourceEnum.java new file mode 100644 index 0000000000..23ed9ba634 --- /dev/null +++ b/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/enums/DataSourceEnum.java @@ -0,0 +1,43 @@ +package com.epmet.commons.dynamic.datasource.enums; + +/** + * 服务-数据源flag-数据源名称对应关系 + */ +public enum DataSourceEnum { + + DATA_STATISTICAL_REAL("data-statistical-server", "real", "stats"), + DATA_STATISTICAL_FAKE("data-statistical-server", "fake", "statsDisplay"), + ; + + private String serviceName; + private String flag; + private String dataSourceName; + + DataSourceEnum(String serviceName, String flag, String dataSourceName) { + this.serviceName = serviceName; + this.flag = flag; + this.dataSourceName = dataSourceName; + } + + public static DataSourceEnum getEnum(String serviceName, String flag) { + DataSourceEnum[] values = DataSourceEnum.values(); + for (DataSourceEnum value : values) { + if (value.serviceName.equals(serviceName) && value.flag.equals(flag)) { + return value; + } + } + return null; + } + + public String getServiceName() { + return serviceName; + } + + public String getFlag() { + return flag; + } + + public String getDataSourceName() { + return dataSourceName; + } +} diff --git a/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/util/AbstractDataSourceNameFetcher.java b/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/util/AbstractDataSourceNameFetcher.java new file mode 100644 index 0000000000..5069bd5958 --- /dev/null +++ b/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/util/AbstractDataSourceNameFetcher.java @@ -0,0 +1,13 @@ +package com.epmet.commons.dynamic.datasource.util; + +import com.epmet.commons.dynamic.datasource.enums.DataSourceEnum; + +public abstract class AbstractDataSourceNameFetcher { + + public abstract String fetchDataSourceName(); + + //protected String getDataSourceName(String dataType, String serviceName) { + // return DataSourceEnum.getEnum(serviceName, dataType) + //} + +} diff --git a/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/util/HttpRequestDataSourceNameFetcher.java b/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/util/HttpRequestDataSourceNameFetcher.java new file mode 100644 index 0000000000..df11b546bf --- /dev/null +++ b/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/util/HttpRequestDataSourceNameFetcher.java @@ -0,0 +1,44 @@ +package com.epmet.commons.dynamic.datasource.util; + +import com.epmet.commons.dynamic.datasource.enums.DataSourceEnum; +import com.epmet.commons.tools.exception.RenException; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +/** + * Http请求中获取数据源名称 + */ +@Component +public class HttpRequestDataSourceNameFetcher extends AbstractDataSourceNameFetcher { + + protected Logger logger = LoggerFactory.getLogger(getClass()); + + @Autowired + private Environment environment; + + @Override + public String fetchDataSourceName() { + ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + javax.servlet.http.HttpServletRequest request = requestAttributes.getRequest(); + String dataType = request.getHeader("Data-Type"); + + logger.info("HttpRequestDataSourceNameFetcher获取到的DataType为:{}", dataType); + if (StringUtils.isBlank(dataType)) { + return null; + } + + String serviceName = environment.getProperty("spring.application.name"); + DataSourceEnum dataSourceEnum = DataSourceEnum.getEnum(serviceName, dataType); + if (dataSourceEnum == null) { + throw new RenException(String.format("根据前端传入的DataType[%s]无法找到对应的数据源。", dataType)); + } + logger.info("HttpRequestDataSourceNameFetcher根据DataType:[{}]获取到的DataSourceEnum为{}", dataType, dataSourceEnum.getDataSourceName()); + return dataSourceEnum.getDataSourceName(); + } +} diff --git a/epmet-module/data-statistical/data-statistical-client/src/main/java/com/epmet/constant/DataSourceConstant.java b/epmet-module/data-statistical/data-statistical-client/src/main/java/com/epmet/constant/DataSourceConstant.java index 920fc14e14..be529605de 100644 --- a/epmet-module/data-statistical/data-statistical-client/src/main/java/com/epmet/constant/DataSourceConstant.java +++ b/epmet-module/data-statistical/data-statistical-client/src/main/java/com/epmet/constant/DataSourceConstant.java @@ -4,6 +4,7 @@ public interface DataSourceConstant { String GOV_ORG = "govOrg"; String STATS = "stats"; + String STATS_DISPLAY = "statsDisplay"; String GOV_ISSUE = "govIssue"; String GOV_PROJECT = "govProject"; String GOV_VOICE = "govVoice"; diff --git a/epmet-module/data-statistical/data-statistical-server/src/main/java/com/epmet/controller/DemoController.java b/epmet-module/data-statistical/data-statistical-server/src/main/java/com/epmet/controller/DemoController.java index b8f7c3e3d2..6ed40fc377 100644 --- a/epmet-module/data-statistical/data-statistical-server/src/main/java/com/epmet/controller/DemoController.java +++ b/epmet-module/data-statistical/data-statistical-server/src/main/java/com/epmet/controller/DemoController.java @@ -1,11 +1,15 @@ package com.epmet.controller; import com.epmet.commons.tools.exception.RenException; +import com.epmet.commons.tools.utils.Result; import com.epmet.dto.AgencySubTreeDto; +import com.epmet.entity.stats.DimAgencyEntity; import com.epmet.service.StatsDemoService; +import com.epmet.service.stats.DimAgencyService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -26,6 +30,9 @@ public class DemoController { @Autowired private ExecutorService executorService; + @Autowired + private DimAgencyService dimAgencyService; + @GetMapping("testAlarm") public void testAlarm() { //for (int i = 0; i < 20; i++) { @@ -91,4 +98,14 @@ public class DemoController { List result = demoService.getAllAgency(); return result; } + + /** + * 参数指定数据源 + * @return + */ + @PostMapping("paramDataSource") + public Result paramDataSource() { + List list = dimAgencyService.getAgencyListByCustomerId("ba7c0b5b21e882b263ee8456e2cfb63e"); + return new Result().ok(list); + } } diff --git a/epmet-module/data-statistical/data-statistical-server/src/main/java/com/epmet/service/stats/impl/DimAgencyServiceImpl.java b/epmet-module/data-statistical/data-statistical-server/src/main/java/com/epmet/service/stats/impl/DimAgencyServiceImpl.java index d40987c1bc..10d4ba7a44 100644 --- a/epmet-module/data-statistical/data-statistical-server/src/main/java/com/epmet/service/stats/impl/DimAgencyServiceImpl.java +++ b/epmet-module/data-statistical/data-statistical-server/src/main/java/com/epmet/service/stats/impl/DimAgencyServiceImpl.java @@ -19,12 +19,14 @@ package com.epmet.service.stats.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; +import com.epmet.commons.dynamic.datasource.annotation.DataSource; import com.epmet.commons.mybatis.service.impl.BaseServiceImpl; import com.epmet.commons.tools.exception.EpmetErrorCode; import com.epmet.commons.tools.exception.RenException; import com.epmet.commons.tools.page.PageData; import com.epmet.commons.tools.utils.ConvertUtils; import com.epmet.commons.tools.constant.FieldConstant; +import com.epmet.constant.DataSourceConstant; import com.epmet.constant.DimAgencyConstant; import com.epmet.constant.RobotConstant; import com.epmet.constant.StatsSubject; @@ -208,6 +210,7 @@ public class DimAgencyServiceImpl extends BaseServiceImpl getAgencyListByCustomerId(String customerId) { if (StringUtils.isBlank(customerId)){ diff --git a/epmet-module/data-statistical/data-statistical-server/src/main/resources/bootstrap.yml b/epmet-module/data-statistical/data-statistical-server/src/main/resources/bootstrap.yml index a475fa198f..7ece13bb19 100644 --- a/epmet-module/data-statistical/data-statistical-server/src/main/resources/bootstrap.yml +++ b/epmet-module/data-statistical/data-statistical-server/src/main/resources/bootstrap.yml @@ -155,6 +155,16 @@ dynamic: url: @datasource.druid.user.url@ username: @datasource.druid.user.username@ password: @datasource.druid.user.password@ + stats: + driver-class-name: com.mysql.cj.jdbc.Driver + url: @datasource.druid.stats.url@ + username: @datasource.druid.stats.username@ + password: @datasource.druid.stats.password@ + statsDisplay: + driver-class-name: com.mysql.cj.jdbc.Driver + url: @datasource.druid.statsdisplay.url@ + username: @datasource.druid.statsdisplay.username@ + password: @datasource.druid.statsdisplay.password@ thread: # 线程池配置 diff --git a/epmet-module/data-statistical/data-statistical-server/src/main/resources/mapper/stats/DimAgencyDao.xml b/epmet-module/data-statistical/data-statistical-server/src/main/resources/mapper/stats/DimAgencyDao.xml index dedf82d8fe..3b7fb8b8ba 100644 --- a/epmet-module/data-statistical/data-statistical-server/src/main/resources/mapper/stats/DimAgencyDao.xml +++ b/epmet-module/data-statistical/data-statistical-server/src/main/resources/mapper/stats/DimAgencyDao.xml @@ -128,6 +128,7 @@ ID, CUSTOMER_ID, PID, + AGENCY_NAME, LEVEL FROM dim_agency From 2f029dc8e338b7b3593c797eb7bafffe8da6f151 Mon Sep 17 00:00:00 2001 From: wxz Date: Sun, 23 Aug 2020 10:46:03 +0800 Subject: [PATCH 2/5] =?UTF-8?q?=E5=8A=A8=E6=80=81=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E6=BA=90=E2=80=94=E5=A2=9E=E5=8A=A0data-report=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E7=9A=84=E6=95=B0=E6=8D=AE=E6=BA=90=E6=9E=9A=E4=B8=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../epmet/commons/dynamic/datasource/enums/DataSourceEnum.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/enums/DataSourceEnum.java b/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/enums/DataSourceEnum.java index 23ed9ba634..7a3632db54 100644 --- a/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/enums/DataSourceEnum.java +++ b/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/enums/DataSourceEnum.java @@ -7,6 +7,8 @@ public enum DataSourceEnum { DATA_STATISTICAL_REAL("data-statistical-server", "real", "stats"), DATA_STATISTICAL_FAKE("data-statistical-server", "fake", "statsDisplay"), + DATA_REPORT_REAL("data-report-server", "real", "stats"), + DATA_REPORT_FAKE("data-report-server", "fake", "statsDisplay"), ; private String serviceName; From 4b96b203579b8775b48df221817f67f12a5a4b39 Mon Sep 17 00:00:00 2001 From: wxz Date: Mon, 24 Aug 2020 10:25:24 +0800 Subject: [PATCH 3/5] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=A4=96=E9=83=A8?= =?UTF-8?q?=E5=BA=94=E7=94=A8=E7=9B=B8=E5=85=B3=E7=9A=84=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../datasource/enums/DataSourceEnum.java | 3 + .../resources/db/migration/V0.0.3__extApp.sql | 56 +++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 epmet-module/epmet-common-service/common-service-server/src/main/resources/db/migration/V0.0.3__extApp.sql diff --git a/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/enums/DataSourceEnum.java b/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/enums/DataSourceEnum.java index 7a3632db54..bca4441435 100644 --- a/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/enums/DataSourceEnum.java +++ b/epmet-commons/epmet-commons-dynamic-datasource/src/main/java/com/epmet/commons/dynamic/datasource/enums/DataSourceEnum.java @@ -11,8 +11,11 @@ public enum DataSourceEnum { DATA_REPORT_FAKE("data-report-server", "fake", "statsDisplay"), ; + // 服务名 private String serviceName; + // 数据源标记 private String flag; + // 数据源,跟yml中的数据源名称保持一致 private String dataSourceName; DataSourceEnum(String serviceName, String flag, String dataSourceName) { diff --git a/epmet-module/epmet-common-service/common-service-server/src/main/resources/db/migration/V0.0.3__extApp.sql b/epmet-module/epmet-common-service/common-service-server/src/main/resources/db/migration/V0.0.3__extApp.sql new file mode 100644 index 0000000000..8faeaf51f9 --- /dev/null +++ b/epmet-module/epmet-common-service/common-service-server/src/main/resources/db/migration/V0.0.3__extApp.sql @@ -0,0 +1,56 @@ +SET NAMES utf8mb4; +SET FOREIGN_KEY_CHECKS = 0; + +CREATE TABLE `external_app` ( + `ID` varchar(64) NOT NULL COMMENT '主键', + `APP_NAME` varchar(64) NOT NULL COMMENT 'APP名字', + `CUSTOMER_ID` varchar(64) DEFAULT NULL COMMENT '客户ID', + `DEL_FLAG` tinyint(1) DEFAULT NULL COMMENT '是否删除,0:未删除,1:已删除', + `REVISION` int(10) DEFAULT NULL COMMENT '乐观锁', + `CREATED_BY` varchar(64) DEFAULT NULL COMMENT '创建者id', + `CREATED_TIME` datetime DEFAULT NULL COMMENT '创建时间', + `UPDATED_BY` varchar(64) DEFAULT NULL COMMENT '更新者id', + `UPDATED_TIME` datetime DEFAULT NULL COMMENT '更新时间', + PRIMARY KEY (`ID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='外部应用列表'; + +CREATE TABLE `external_app_secret` ( + `ID` varchar(64) NOT NULL COMMENT '主键', + `APP_ID` varchar(64) NOT NULL COMMENT 'APP ID', + `SECRET` varchar(255) NOT NULL COMMENT '秘钥', + `DEL_FLAG` tinyint(1) DEFAULT NULL COMMENT '是否删除,0:未删除,1:已删除', + `REVISION` int(10) DEFAULT NULL COMMENT '乐观锁', + `CREATED_BY` varchar(64) DEFAULT NULL COMMENT '创建者id', + `CREATED_TIME` datetime DEFAULT NULL COMMENT '创建时间', + `UPDATED_BY` varchar(64) DEFAULT NULL COMMENT '更新者id', + `UPDATED_TIME` datetime DEFAULT NULL COMMENT '更新时间', + PRIMARY KEY (`ID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='外部应用秘钥列表'; + +CREATE TABLE `external_customer` ( + `ID` varchar(64) NOT NULL COMMENT '客户ID', + `CUSTOMER_NAME` varchar(255) NOT NULL COMMENT '客户名称', + `DEL_FLAG` tinyint(1) DEFAULT NULL COMMENT '是否删除,0:未删除,1:已删除', + `REVISION` int(10) DEFAULT NULL COMMENT '乐观锁', + `CREATED_BY` varchar(64) DEFAULT NULL COMMENT '创建者id', + `CREATED_TIME` datetime DEFAULT NULL COMMENT '创建时间', + `UPDATED_BY` varchar(64) DEFAULT NULL COMMENT '更新者id', + `UPDATED_TIME` datetime DEFAULT NULL COMMENT '更新时间', + PRIMARY KEY (`ID`) USING BTREE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +BEGIN; +INSERT INTO `external_app` VALUES ('227fb75ae4baa820755aaf43bf7f0a69', '便捷通行', '7e07311f4c4a56c65fa1dd5d16e0b743', 0, 0, 'wxz', '2020-08-18 13:39:32', 'wxz', '2020-08-18 13:39:37'); +INSERT INTO `external_app` VALUES ('acc4ad66c82a7b46e741364b4c62dce2', '市北大屏', 'b09527201c4409e19d1dbc5e3c3429a1', 0, 0, 'wxz', '2020-08-18 13:39:32', 'wxz', '2020-08-18 13:39:37'); +INSERT INTO `external_app` VALUES ('dbfad3110c124c89948d16e8b06a8888', '数据采集', 'b09527201c4409e19d1dbc5e3c3429a1', 0, 0, 'wxz', '2020-08-18 13:39:32', 'wxz', '2020-08-18 13:39:37'); + +INSERT INTO `external_app_secret` VALUES ('44ed58fd256ae51b473b6ff8555c7131', '227fb75ae4baa820755aaf43bf7f0a69', 'a44a4fc41eb513cd93a0f957db3ef764e189e6aebb2369471396a8c3b32f61ed', 0, 0, 'wxz', '2020-08-18 13:40:03', 'xz', '2020-08-18 13:40:07'); +INSERT INTO `external_app_secret` VALUES ('95d16f5fe76d1139023107476871a077', 'dbfad3110c124c89948d16e8b06a8888', '0f7e983b017ac180b0da1877abe11bab22ab6288580e64d39b5e415dbb0fcc8f', 0, 0, 'wxz', '2020-08-18 13:40:03', 'xz', '2020-08-18 13:40:07'); +INSERT INTO `external_app_secret` VALUES ('9ca67b7b02dc2e80e9ba6ba4793aea54', 'acc4ad66c82a7b46e741364b4c62dce2', '612d304095c50369c3ef06e490f05779eeb8f19ff16566c73aeafafc5fa01970', 0, 0, 'wxz', '2020-08-18 13:40:03', 'xz', '2020-08-18 13:40:07'); + +INSERT INTO `external_customer` VALUES ('7e07311f4c4a56c65fa1dd5d16e0b743', '外挂功能', 0, 0, 'wxz', '2020-08-19 14:21:52', 'APP_USER', '2020-08-21 15:23:35'); +INSERT INTO `external_customer` VALUES ('b09527201c4409e19d1dbc5e3c3429a1', '市北党建', 0, 0, 'wxz', '2020-08-19 14:21:52', 'wxz', '2020-08-19 14:21:58'); + +COMMIT; + +SET FOREIGN_KEY_CHECKS = 1; \ No newline at end of file From 0b6ee2a2eec5eb020848d1b746e324a338202370 Mon Sep 17 00:00:00 2001 From: wxz Date: Wed, 2 Sep 2020 15:12:53 +0800 Subject: [PATCH 4/5] =?UTF-8?q?=E6=96=B0=E5=A2=9E=EF=BC=9Amd5=E6=91=98?= =?UTF-8?q?=E8=A6=81=E9=AA=8C=E7=AD=BE=E6=96=B9=E5=BC=8F=E7=9A=84=E5=A4=96?= =?UTF-8?q?=E9=83=A8=E5=BA=94=E7=94=A8=E8=AE=A4=E8=AF=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../aspect/ExternalAppRequestAuthAspect.java | 13 ++- .../dto/form/ExternalAppAuthFormDTO.java | 10 ++ .../constant/ExtAppAuthTypeConstant.java | 8 ++ .../controller/ExternalAppController.java | 4 +- .../epmet/service/ExternalAppAuthService.java | 3 +- .../impl/ExternalAppAuthServiceImpl.java | 108 +++--------------- .../externalapp/ExtAppAuthProcessor.java | 73 ++++++++++++ .../externalapp/ExtAppJwtAuthProcessor.java | 61 ++++++++++ .../externalapp/ExtAppJwtTokenUtils.java | 8 +- .../externalapp/ExtAppMD5AuthProcessor.java | 42 +++++++ 10 files changed, 231 insertions(+), 99 deletions(-) create mode 100644 epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/constant/ExtAppAuthTypeConstant.java create mode 100644 epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/utils/externalapp/ExtAppAuthProcessor.java create mode 100644 epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/utils/externalapp/ExtAppJwtAuthProcessor.java create mode 100644 epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/utils/externalapp/ExtAppMD5AuthProcessor.java diff --git a/epmet-commons/epmet-commons-extapp-auth/src/main/java/com/epmet/commons/extappauth/aspect/ExternalAppRequestAuthAspect.java b/epmet-commons/epmet-commons-extapp-auth/src/main/java/com/epmet/commons/extappauth/aspect/ExternalAppRequestAuthAspect.java index b4cfd11c27..82ffd68882 100644 --- a/epmet-commons/epmet-commons-extapp-auth/src/main/java/com/epmet/commons/extappauth/aspect/ExternalAppRequestAuthAspect.java +++ b/epmet-commons/epmet-commons-extapp-auth/src/main/java/com/epmet/commons/extappauth/aspect/ExternalAppRequestAuthAspect.java @@ -37,6 +37,9 @@ public class ExternalAppRequestAuthAspect { public static final String ACCESS_TOKEN_HEADER_KEY = "AccessToken"; public static final String APP_ID_HEADER_KEY = "appId"; + public static final String APP_ID_TIMESTAMP_KEY = "ts"; + public static final String APP_ID_CUSTOMER_ID_KEY = "CustomerId"; + public static final String APP_ID_AUTY_TYPE_KEY = "AuthType"; @Autowired private EpmetCommonServiceOpenFeignClient commonServiceOpenFeignClient; @@ -52,6 +55,9 @@ public class ExternalAppRequestAuthAspect { HttpServletRequest request = getRequest(); String token = request.getHeader(ACCESS_TOKEN_HEADER_KEY); String appId = request.getHeader(APP_ID_HEADER_KEY); + String ts = request.getHeader(APP_ID_TIMESTAMP_KEY); + String customerId = request.getHeader(APP_ID_CUSTOMER_ID_KEY); + String authType = request.getHeader(APP_ID_AUTY_TYPE_KEY); if (StringUtils.isAnyBlank(token, appId)) { throw new RenException("请求头中的token和appId不能为空"); @@ -62,6 +68,11 @@ public class ExternalAppRequestAuthAspect { ExternalAppAuthFormDTO form = new ExternalAppAuthFormDTO(); form.setAppId(appId); form.setToken(token); + form.setAuthType(authType); + if (StringUtils.isNotBlank(ts)) { + // 将字符串转化为时间 + form.setTs(new Long(ts)); + } Result result = commonServiceOpenFeignClient.externalAppAuth(form); if (result == null) { throw new RenException("调用服务进行外部应用认证,返回null"); @@ -84,7 +95,7 @@ public class ExternalAppRequestAuthAspect { if (parameters[i].getType() == ExternalAppRequestParam.class) { ExternalAppRequestParam requestParam = (ExternalAppRequestParam) point.getArgs()[i]; requestParam.setAppId(appId); - requestParam.setCustomerId(authResult.getCustomerId()); + requestParam.setCustomerId(authResult.getCustomerId() == null ? customerId : authResult.getCustomerId()); } } } diff --git a/epmet-module/epmet-common-service/common-service-client/src/main/java/com/epmet/dto/form/ExternalAppAuthFormDTO.java b/epmet-module/epmet-common-service/common-service-client/src/main/java/com/epmet/dto/form/ExternalAppAuthFormDTO.java index 2d6470db80..a144b37f81 100644 --- a/epmet-module/epmet-common-service/common-service-client/src/main/java/com/epmet/dto/form/ExternalAppAuthFormDTO.java +++ b/epmet-module/epmet-common-service/common-service-client/src/main/java/com/epmet/dto/form/ExternalAppAuthFormDTO.java @@ -15,4 +15,14 @@ public class ExternalAppAuthFormDTO { */ private String token; + /** + * 时间戳 + */ + private Long ts; + + /** + * 认证类型:md5,jwt + */ + private String authType; + } diff --git a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/constant/ExtAppAuthTypeConstant.java b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/constant/ExtAppAuthTypeConstant.java new file mode 100644 index 0000000000..b281c6d7e6 --- /dev/null +++ b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/constant/ExtAppAuthTypeConstant.java @@ -0,0 +1,8 @@ +package com.epmet.constant; + +public interface ExtAppAuthTypeConstant { + + String JWT = "jwt"; + String MD5 = "md5"; + +} diff --git a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/controller/ExternalAppController.java b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/controller/ExternalAppController.java index 976c4e4ef0..50e9a7b891 100644 --- a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/controller/ExternalAppController.java +++ b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/controller/ExternalAppController.java @@ -40,12 +40,14 @@ public class ExternalAppController { public Result auth(@RequestBody ExternalAppAuthFormDTO formDTO) { String appId = formDTO.getAppId(); String token = formDTO.getToken(); + Long ts = formDTO.getTs(); + String authType = formDTO.getAuthType(); if (StringUtils.isAnyBlank(token, appId)) { throw new RenException("请求头中的token和appId不能为空"); } logger.info("外部应用请求认证拦截Aspect。appId:{}, token:{}", appId, token); - ExternalAppAuthResultDTO auth = externalAppAuthService.auth(appId, token); + ExternalAppAuthResultDTO auth = externalAppAuthService.auth(appId, token, ts, authType); return new Result().ok(auth); } diff --git a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/ExternalAppAuthService.java b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/ExternalAppAuthService.java index e1158c592c..3f76a1e83d 100644 --- a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/ExternalAppAuthService.java +++ b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/ExternalAppAuthService.java @@ -1,10 +1,9 @@ package com.epmet.service; import com.epmet.dto.result.ExternalAppAuthResultDTO; -import com.epmet.dto.result.ExternalAppResultDTO; public interface ExternalAppAuthService { - ExternalAppAuthResultDTO auth(String appId, String token); + ExternalAppAuthResultDTO auth(String appId, String token, Long ts, String authType); } diff --git a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/impl/ExternalAppAuthServiceImpl.java b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/impl/ExternalAppAuthServiceImpl.java index e87a4c6f46..e598c3ab2c 100644 --- a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/impl/ExternalAppAuthServiceImpl.java +++ b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/impl/ExternalAppAuthServiceImpl.java @@ -1,19 +1,10 @@ package com.epmet.service.impl; -import com.epmet.commons.tools.exception.EpmetErrorCode; -import com.epmet.commons.tools.exception.ExceptionUtils; -import com.epmet.commons.tools.exception.RenException; -import com.epmet.commons.tools.redis.RedisKeys; -import com.epmet.commons.tools.redis.RedisUtils; -import com.epmet.dao.ExternalAppDao; -import com.epmet.dao.ExternalAppSecretDao; +import com.epmet.constant.ExtAppAuthTypeConstant; import com.epmet.dto.result.ExternalAppAuthResultDTO; -import com.epmet.dto.result.ExternalAppResultDTO; -import com.epmet.entity.ExternalAppEntity; -import com.epmet.entity.ExternalAppSecretEntity; import com.epmet.service.ExternalAppAuthService; -import com.epmet.utils.externalapp.ExtAppJwtTokenUtils; -import io.jsonwebtoken.Claims; +import com.epmet.utils.externalapp.ExtAppJwtAuthProcessor; +import com.epmet.utils.externalapp.ExtAppMD5AuthProcessor; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -26,90 +17,23 @@ public class ExternalAppAuthServiceImpl implements ExternalAppAuthService { private static Logger logger = LoggerFactory.getLogger(ExternalAppAuthServiceImpl.class); @Autowired - private RedisUtils redisUtils; + private ExtAppJwtAuthProcessor jwtAuthProcessor; @Autowired - private ExtAppJwtTokenUtils jwtTokenUtils; - - @Autowired - private ExternalAppSecretDao externalAppSecretDao; - - @Autowired - private ExternalAppDao externalAppDao; - - private int diffMillins = 1000 * 60 * 5; + private ExtAppMD5AuthProcessor md5AuthProcessor; @Override - public ExternalAppAuthResultDTO auth(String appId, String token) { - String secret; - if (StringUtils.isBlank(secret = getTokenByAppId(appId))) { - return fillAuthResult(false, String.format("根据AppId:%s没有找到对应的秘钥", appId), null); + public ExternalAppAuthResultDTO auth(String appId, String token, Long ts, String authType) { + // 没传或者传的jwt都用jwtprocessor处理 + if (StringUtils.isBlank(authType) || ExtAppAuthTypeConstant.JWT.equals(authType)) { + return jwtAuthProcessor.auth(appId, token, ts); + } else if (ExtAppAuthTypeConstant.MD5.equals(authType)) { + return md5AuthProcessor.auth(appId, token, ts); + } else { + ExternalAppAuthResultDTO rst = new ExternalAppAuthResultDTO(); + rst.setMessage("错误的认证类型"); + rst.setSuccess(false); + return rst; } - - Claims claim; - try { - claim = jwtTokenUtils.getClaimByToken(token, secret); - } catch (Exception e) { - String errorStackTrace = ExceptionUtils.getErrorStackTrace(e); - logger.error("解析token失败:{}", errorStackTrace); - return fillAuthResult(false, "解析token失败", null); - } - - String appIdIn = (String)claim.get("appId"); - String customerId = (String)claim.get("customerId"); - Long timestamp = (Long)claim.get("ts"); - - //校验时间戳,允许5分钟误差 - if (StringUtils.isAnyBlank(appIdIn, customerId) || timestamp == null) { - logger.error("access token不完整。{},{},{}", appIdIn, customerId, timestamp); - return fillAuthResult(false, "access token不完整。", null); - } - - // TODO -// if (!validTimeStamp(timestamp)) { -// logger.error("服务器存在时差过大,请求被拒绝", appId, appIdIn); -// return fillAuthResult(false, "服务器存在时差过大,请求被拒绝", null); -// } - - if (!appId.equals(appIdIn)) { - logger.error("AppId不对应,token外部的:{}, token内部解析出来的:{}", appId, appIdIn); - return fillAuthResult(false, "Header中的AppId不匹配", null); - } - return fillAuthResult(true, "解析成功", customerId); - } - - private boolean validTimeStamp(Long timestamp) { - long now = System.currentTimeMillis(); -// System.out.println(new Date(timestamp)); - if (Math.abs(now - timestamp) > diffMillins) { - return false; - } - return true; - } - - /** - * 通过APP ID查询对应的秘钥 - * @param appId - * @return - */ - public String getTokenByAppId(String appId) { - String secret = (String)redisUtils.get(RedisKeys.getExternalAppSecretKey(appId)); - if (StringUtils.isBlank(secret)) { - ExternalAppSecretEntity secretEntity = externalAppSecretDao.getSecretsByAppId(appId); - if (secretEntity == null) { - return null; - } - secret = secretEntity.getSecret(); - redisUtils.set(RedisKeys.getExternalAppSecretKey(appId), secret); - } - return secret; - } - - public ExternalAppAuthResultDTO fillAuthResult(Boolean result, String message, String customerId) { - ExternalAppAuthResultDTO authResult = new ExternalAppAuthResultDTO(); - authResult.setSuccess(result); - authResult.setMessage(message); - authResult.setCustomerId(customerId); - return authResult; } } diff --git a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/utils/externalapp/ExtAppAuthProcessor.java b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/utils/externalapp/ExtAppAuthProcessor.java new file mode 100644 index 0000000000..b0f5fef000 --- /dev/null +++ b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/utils/externalapp/ExtAppAuthProcessor.java @@ -0,0 +1,73 @@ +package com.epmet.utils.externalapp; + +import com.epmet.commons.tools.redis.RedisKeys; +import com.epmet.commons.tools.redis.RedisUtils; +import com.epmet.dao.ExternalAppSecretDao; +import com.epmet.dto.result.ExternalAppAuthResultDTO; +import com.epmet.entity.ExternalAppSecretEntity; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; + + +/** + * 外部应用认证处理器父类 + */ +public abstract class ExtAppAuthProcessor { + + @Autowired + private RedisUtils redisUtils; + + @Autowired + private ExternalAppSecretDao externalAppSecretDao; + + private int diffMillins = 1000 * 60 * 5; + + public abstract ExternalAppAuthResultDTO auth(String appId, String token, Long ts); + + /** + * 通过APP ID查询对应的秘钥 + * @param appId + * @return + */ + public String getTokenByAppId(String appId) { + String secret = (String)redisUtils.get(RedisKeys.getExternalAppSecretKey(appId)); + if (StringUtils.isBlank(secret)) { + ExternalAppSecretEntity secretEntity = externalAppSecretDao.getSecretsByAppId(appId); + if (secretEntity == null) { + return null; + } + secret = secretEntity.getSecret(); + redisUtils.set(RedisKeys.getExternalAppSecretKey(appId), secret); + } + return secret; + } + + /** + * 时间戳校验 + * @param timestamp + * @return + */ + protected boolean validTimeStamp(Long timestamp) { + long now = System.currentTimeMillis(); + if (Math.abs(now - timestamp) > diffMillins) { + return false; + } + return true; + } + + /** + * 封装结果 + * @param result + * @param message + * @param customerId + * @return + */ + public ExternalAppAuthResultDTO fillAuthResult(Boolean result, String message, String customerId) { + ExternalAppAuthResultDTO authResult = new ExternalAppAuthResultDTO(); + authResult.setSuccess(result); + authResult.setMessage(message); + authResult.setCustomerId(customerId); + return authResult; + } + +} diff --git a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/utils/externalapp/ExtAppJwtAuthProcessor.java b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/utils/externalapp/ExtAppJwtAuthProcessor.java new file mode 100644 index 0000000000..2ec771fd02 --- /dev/null +++ b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/utils/externalapp/ExtAppJwtAuthProcessor.java @@ -0,0 +1,61 @@ +package com.epmet.utils.externalapp; + +import com.epmet.commons.tools.exception.ExceptionUtils; +import com.epmet.dto.result.ExternalAppAuthResultDTO; +import io.jsonwebtoken.Claims; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * jwt 认证处理器 + */ +@Component +public class ExtAppJwtAuthProcessor extends ExtAppAuthProcessor { + + private static Logger logger = LoggerFactory.getLogger(ExtAppJwtAuthProcessor.class); + + @Autowired + private ExtAppJwtTokenUtils jwtTokenUtils; + + public ExternalAppAuthResultDTO auth(String appId, String token, Long ts) { + String secret; + if (StringUtils.isBlank(secret = getTokenByAppId(appId))) { + return fillAuthResult(false, String.format("根据AppId:%s没有找到对应的秘钥", appId), null); + } + + Claims claim; + try { + claim = jwtTokenUtils.getClaimByToken(token, secret); + } catch (Exception e) { + String errorStackTrace = ExceptionUtils.getErrorStackTrace(e); + logger.error("解析token失败:{}", errorStackTrace); + return fillAuthResult(false, "解析token失败", null); + } + + String appIdIn = (String)claim.get("appId"); + String customerId = (String)claim.get("customerId"); + Long timestamp = (Long)claim.get("ts"); + + //校验时间戳,允许5分钟误差 + if (StringUtils.isAnyBlank(appIdIn, customerId) || timestamp == null) { + logger.error("access token不完整。{},{},{}", appIdIn, customerId, timestamp); + return fillAuthResult(false, "access token不完整。", null); + } + + // TODO 暂时去掉时间差判断 + //if (!validTimeStamp(timestamp)) { + // logger.error("服务器存在时差过大,请求被拒绝"); + // return fillAuthResult(false, "服务器存在时差过大,请求被拒绝", null); + //} + + if (!appId.equals(appIdIn)) { + logger.error("AppId不对应,token外部的:{}, token内部解析出来的:{}", appId, appIdIn); + return fillAuthResult(false, "Header中的AppId不匹配", null); + } + + return fillAuthResult(true, "解析成功,认证成功", customerId); + } +} diff --git a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/utils/externalapp/ExtAppJwtTokenUtils.java b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/utils/externalapp/ExtAppJwtTokenUtils.java index 1c3a326c75..2e49c80102 100644 --- a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/utils/externalapp/ExtAppJwtTokenUtils.java +++ b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/utils/externalapp/ExtAppJwtTokenUtils.java @@ -75,11 +75,13 @@ public class ExtAppJwtTokenUtils { public static void genToken() { HashMap claim = new HashMap<>(); - claim.put("appId", "227fb75ae4baa820755aaf43bf7f0a69"); + claim.put("appId", "2c448b7da527055fbeebb628f8d3dcb0"); claim.put("customerId", "c1"); - claim.put("ts", System.currentTimeMillis() - 1000 * 60 * 4); + long ts = System.currentTimeMillis() - 1000 * 60 * 4; + System.out.println("时间戳:" + ts); + claim.put("ts", ts); - String abc = new ExtAppJwtTokenUtils().createToken(claim, "4a762660254c57996343f8ee42fbc0a6"); + String abc = new ExtAppJwtTokenUtils().createToken(claim, "d4b73db4cf8e46ef99fa1f95149c2791ef2396fded114dd09e406cbce83fc88a"); System.out.println(abc); } diff --git a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/utils/externalapp/ExtAppMD5AuthProcessor.java b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/utils/externalapp/ExtAppMD5AuthProcessor.java new file mode 100644 index 0000000000..3954738758 --- /dev/null +++ b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/utils/externalapp/ExtAppMD5AuthProcessor.java @@ -0,0 +1,42 @@ +package com.epmet.utils.externalapp; + +import com.epmet.commons.tools.utils.Md5Util; +import com.epmet.dto.result.ExternalAppAuthResultDTO; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +/** + * md5 认证处理器 + */ +@Component +public class ExtAppMD5AuthProcessor extends ExtAppAuthProcessor { + + private static Logger logger = LoggerFactory.getLogger(ExtAppMD5AuthProcessor.class); + + public ExternalAppAuthResultDTO auth(String appId, String token, Long ts) { + if (ts == null) { + return fillAuthResult(false, "需要传入时间戳参数", null); + } + String secret; + if (StringUtils.isBlank(secret = getTokenByAppId(appId))) { + return fillAuthResult(false, String.format("根据AppId:%s没有找到对应的秘钥", appId), null); + } + + String localDigest = Md5Util.md5(secret.concat(":") + ts); + if (!localDigest.equals(token)) { + // 调用方生成的摘要跟本地生成的摘要不匹配 + return fillAuthResult(false, "签名不匹配,认证失败", null); + } + + // TODO 暂时去掉时间差判断 + //if (!validTimeStamp(ts)) { + // logger.error("服务器存在时差过大,请求被拒绝"); + // return fillAuthResult(false, "服务器存在时差过大,请求被拒绝", null); + //} + + return fillAuthResult(true, "签名匹配,认证成功", null); + } + +} From d65cc6cea2d8753f603a358887c04557af2657b8 Mon Sep 17 00:00:00 2001 From: wxz Date: Thu, 3 Sep 2020 09:56:15 +0800 Subject: [PATCH 5/5] =?UTF-8?q?=E6=96=B0=E5=A2=9E=EF=BC=9A=E5=A4=96?= =?UTF-8?q?=E9=83=A8=E5=BA=94=E7=94=A8=E7=A7=98=E9=92=A5=E9=87=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../commons/tools/exception/EpmetErrorCode.java | 1 + .../com/epmet/dto/form/ExternalAppFormDTO.java | 3 ++- .../epmet/controller/ExternalAppController.java | 17 +++++++++++++++++ .../com/epmet/dao/ExternalAppSecretDao.java | 1 + .../com/epmet/service/ExternalAppService.java | 2 ++ .../service/impl/ExternalAppServiceImpl.java | 9 +++++++++ .../resources/mapper/ExternalAppSecretDao.xml | 7 +++++++ 7 files changed, 39 insertions(+), 1 deletion(-) diff --git a/epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/exception/EpmetErrorCode.java b/epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/exception/EpmetErrorCode.java index 24e795fd1a..b16ad96bc0 100644 --- a/epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/exception/EpmetErrorCode.java +++ b/epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/exception/EpmetErrorCode.java @@ -102,6 +102,7 @@ public enum EpmetErrorCode { OPER_EXTERNAL_APP_AUTH_ERROR(8709, "外部应用认证失败"), OPER_EXTERNAL_CUSTOMER_NOT_EXISTS(8710, "该客户不存在"), OPER_EXTERNAL_APP_EXISTS(8711, "应用已存在"), + OPER_EXT_APP_SECRET_RESET_FAIL(8712, "秘钥更新失败"), // 党建声音 前端提示 88段 DRAFT_CONTENT_IS_NULL(8801, "至少需要添加一个段落"), diff --git a/epmet-module/epmet-common-service/common-service-client/src/main/java/com/epmet/dto/form/ExternalAppFormDTO.java b/epmet-module/epmet-common-service/common-service-client/src/main/java/com/epmet/dto/form/ExternalAppFormDTO.java index 36a504a135..00b99a500e 100644 --- a/epmet-module/epmet-common-service/common-service-client/src/main/java/com/epmet/dto/form/ExternalAppFormDTO.java +++ b/epmet-module/epmet-common-service/common-service-client/src/main/java/com/epmet/dto/form/ExternalAppFormDTO.java @@ -9,8 +9,9 @@ public class ExternalAppFormDTO { public interface AddExternalApp {} public interface UpdateExternalApp {} + public interface UpdateAppSecret {} - @NotBlank(message = "缺少应用ID", groups = { UpdateExternalApp.class }) + @NotBlank(message = "缺少应用ID", groups = { UpdateExternalApp.class, UpdateAppSecret.class }) private String appId; @NotBlank(message = "缺少应用名称", groups = { AddExternalApp.class, UpdateExternalApp.class }) diff --git a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/controller/ExternalAppController.java b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/controller/ExternalAppController.java index 50e9a7b891..45bdb8bef6 100644 --- a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/controller/ExternalAppController.java +++ b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/controller/ExternalAppController.java @@ -1,5 +1,6 @@ package com.epmet.controller; +import com.epmet.commons.tools.exception.EpmetErrorCode; import com.epmet.commons.tools.exception.RenException; import com.epmet.commons.tools.page.PageData; import com.epmet.commons.tools.utils.Result; @@ -97,4 +98,20 @@ public class ExternalAppController { return new Result>().ok(page); } + /** + * 重置应用秘钥 + * @param formDTO + * @return + */ + @PostMapping("/resetsecret") + public Result resetSecret(@RequestBody ExternalAppFormDTO formDTO) { + ValidatorUtils.validateEntity(formDTO, ExternalAppFormDTO.UpdateAppSecret.class); + String newSecret = externalAppService.resetSecret(formDTO.getAppId()); + if (StringUtils.isBlank(newSecret)) { + return new Result().error(EpmetErrorCode.OPER_EXT_APP_SECRET_RESET_FAIL.getCode(), + EpmetErrorCode.OPER_EXT_APP_SECRET_RESET_FAIL.getMsg()); + } + return new Result().ok(newSecret); + } + } diff --git a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/dao/ExternalAppSecretDao.java b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/dao/ExternalAppSecretDao.java index f56aa08cb0..fd2342c7c6 100644 --- a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/dao/ExternalAppSecretDao.java +++ b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/dao/ExternalAppSecretDao.java @@ -40,4 +40,5 @@ public interface ExternalAppSecretDao extends BaseDao { */ ExternalAppSecretEntity getSecretsByAppId(@Param("appId") String appId); + int updateSecret(@Param("appId") String appId, @Param("secret") String secret); } \ No newline at end of file diff --git a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/ExternalAppService.java b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/ExternalAppService.java index dff718695f..8f38fa2a83 100644 --- a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/ExternalAppService.java +++ b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/ExternalAppService.java @@ -32,4 +32,6 @@ public interface ExternalAppService { ExternalAppResultDTO updateById(String appId, String appName, String customerId); PageData listPage(Integer pageNo, Integer pageSize, String customerId); + + String resetSecret(String appId); } \ No newline at end of file diff --git a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/impl/ExternalAppServiceImpl.java b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/impl/ExternalAppServiceImpl.java index 5f92de268e..dcfc930aad 100644 --- a/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/impl/ExternalAppServiceImpl.java +++ b/epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/impl/ExternalAppServiceImpl.java @@ -130,4 +130,13 @@ public class ExternalAppServiceImpl implements ExternalAppService { return new PageData<>(list, pageInfo.getTotal()); } + @Override + public String resetSecret(String appId) { + String secret = genSecret(); + if (externalAppSecretDao.updateSecret(appId, secret) > 0) { + return secret; + } + return null; + } + } \ No newline at end of file diff --git a/epmet-module/epmet-common-service/common-service-server/src/main/resources/mapper/ExternalAppSecretDao.xml b/epmet-module/epmet-common-service/common-service-server/src/main/resources/mapper/ExternalAppSecretDao.xml index e207a36013..995dbd0270 100644 --- a/epmet-module/epmet-common-service/common-service-server/src/main/resources/mapper/ExternalAppSecretDao.xml +++ b/epmet-module/epmet-common-service/common-service-server/src/main/resources/mapper/ExternalAppSecretDao.xml @@ -15,6 +15,13 @@ + + + update external_app_secret + set SECRET=#{secret} + where ID = #{appId} + +