Browse Source

增加外部应用请求鉴权模块

master
wxz 5 years ago
parent
commit
b905d4765e
  1. 54
      epmet-commons/epmet-commons-extapp-auth/pom.xml
  2. 32
      epmet-commons/epmet-commons-extapp-auth/src/main/java/com/epmet/commons/extappauth/annotation/ExternalAppRequestAuth.java
  3. 99
      epmet-commons/epmet-commons-extapp-auth/src/main/java/com/epmet/commons/extappauth/aspect/ExternalAppRequestAuthAspect.java
  4. 12
      epmet-commons/epmet-commons-extapp-auth/src/main/java/com/epmet/commons/extappauth/bean/ExternalAppRequestParam.java
  5. 1
      epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/exception/EpmetErrorCode.java
  6. 9
      epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/redis/RedisKeys.java
  7. 1
      epmet-commons/pom.xml
  8. 5
      epmet-module/data-report/data-report-server/pom.xml
  9. 19
      epmet-module/data-report/data-report-server/src/main/java/com/epmet/controller/test/TestController.java
  10. 18
      epmet-module/epmet-common-service/common-service-client/src/main/java/com/epmet/dto/form/ExternalAppAuthFormDTO.java
  11. 10
      epmet-module/epmet-common-service/common-service-client/src/main/java/com/epmet/dto/result/ExternalAppAuthResultDTO.java
  12. 13
      epmet-module/epmet-common-service/common-service-client/src/main/java/com/epmet/feign/EpmetCommonServiceOpenFeignClient.java
  13. 7
      epmet-module/epmet-common-service/common-service-client/src/main/java/com/epmet/feign/fallback/EpmetCommonServiceOpenFeignClientFallback.java
  14. 6
      epmet-module/epmet-common-service/common-service-server/pom.xml
  15. 39
      epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/controller/ExternalAppController.java
  16. 33
      epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/dao/ExternalAppDao.java
  17. 43
      epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/dao/ExternalAppSecretDao.java
  18. 51
      epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/entity/ExternalAppEntity.java
  19. 51
      epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/entity/ExternalAppSecretEntity.java
  20. 9
      epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/ExternalAppAuthService.java
  21. 28
      epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/ExternalAppSecretService.java
  22. 27
      epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/ExternalAppService.java
  23. 83
      epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/impl/ExternalAppAuthServiceImpl.java
  24. 31
      epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/impl/ExternalAppSecretServiceImpl.java
  25. 33
      epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/impl/ExternalAppServiceImpl.java
  26. 92
      epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/utils/externalapp/ExtAppJwtTokenUtils.java
  27. 19
      epmet-module/epmet-common-service/common-service-server/src/main/resources/mapper/ExternalAppDao.xml
  28. 37
      epmet-module/epmet-common-service/common-service-server/src/main/resources/mapper/ExternalAppSecretDao.xml

54
epmet-commons/epmet-commons-extapp-auth/pom.xml

@ -0,0 +1,54 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.epmet</groupId>
<artifactId>epmet-commons</artifactId>
<version>2.0.0</version>
</parent>
<artifactId>epmet-commons-extapp-auth</artifactId>
<packaging>jar</packaging>
<properties>
<hibernate.validator.version>6.0.17.Final</hibernate.validator.version>
<commons.lang.version>3.7</commons.lang.version>
<commons.fileupload.version>1.3.3</commons.fileupload.version>
<commons.io.version>2.6</commons.io.version>
<hutool.version>4.6.1</hutool.version>
<easypoi.version>4.1.0</easypoi.version>
<joda.time.version>2.9.9</joda.time.version>
<fastjson.version>1.2.60</fastjson.version>
<gson.version>2.8.6</gson.version>
<jsoup.version>1.11.3</jsoup.version>
<lombok.version>1.18.4</lombok.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>com.epmet</groupId>
<artifactId>common-service-client</artifactId>
<version>2.0.0</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
</build>
</project>

32
epmet-commons/epmet-commons-extapp-auth/src/main/java/com/epmet/commons/extappauth/annotation/ExternalAppRequestAuth.java

@ -0,0 +1,32 @@
/**
* Copyright 2018 人人开源 http://www.renren.io
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.epmet.commons.extappauth.annotation;
import java.lang.annotation.*;
/**
* 需要认证的外部请求
* @Author wxz
* @Description
* @Date 2020/4/23 16:17
**/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExternalAppRequestAuth {
}

99
epmet-commons/epmet-commons-extapp-auth/src/main/java/com/epmet/commons/extappauth/aspect/ExternalAppRequestAuthAspect.java

@ -0,0 +1,99 @@
package com.epmet.commons.extappauth.aspect;
import com.epmet.commons.extappauth.bean.ExternalAppRequestParam;
import com.epmet.commons.tools.exception.EpmetErrorCode;
import com.epmet.commons.tools.exception.RenException;
import com.epmet.commons.tools.utils.Result;
import com.epmet.dto.form.ExternalAppAuthFormDTO;
import com.epmet.dto.result.ExternalAppAuthResultDTO;
import com.epmet.feign.EpmetCommonServiceOpenFeignClient;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
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.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Parameter;
/**
* 外部应用请求认证切面
*/
@Aspect
@Component
@Order(100)
public class ExternalAppRequestAuthAspect {
private static Logger logger = LoggerFactory.getLogger(ExternalAppRequestAuthAspect.class);
public static final String ACCESS_TOKEN_HEADER_KEY = "access_token";
public static final String APP_ID_HEADER_KEY = "appId";
@Autowired
private EpmetCommonServiceOpenFeignClient commonServiceOpenFeignClient;
/**
* 拦截加了ExternalRequestAuth注解的方法
*
* @param point
* @throws Throwable
*/
@Before("@annotation(com.epmet.commons.extappauth.annotation.ExternalAppRequestAuth)")
public void auth(JoinPoint point) throws Throwable {
HttpServletRequest request = getRequest();
String token = request.getHeader(ACCESS_TOKEN_HEADER_KEY);
String appId = request.getHeader(APP_ID_HEADER_KEY);
if (StringUtils.isAnyBlank(token, appId)) {
throw new RenException("请求头中的token和appId不能为空");
}
logger.info("外部应用请求认证拦截Aspect执行,appId:{}, token:{}", appId, token);
ExternalAppAuthFormDTO form = new ExternalAppAuthFormDTO();
form.setAppId(appId);
form.setToken(token);
Result<ExternalAppAuthResultDTO> result = commonServiceOpenFeignClient.externalAppAuth(form);
if (result == null) {
throw new RenException("调用external鉴权服务,返回null");
}
if (!result.success()) {
throw new RenException(result.getInternalMsg());
}
ExternalAppAuthResultDTO authResult = result.getData();
if (!authResult.getSuccess()) {
throw new RenException(EpmetErrorCode.OPER_EXTERNAL_APP_AUTH_ERROR.getCode(),
result.getData().getMessage());
}
// header参数赋值
MethodSignature signature = (MethodSignature) point.getSignature();
Parameter[] parameters = signature.getMethod().getParameters();
if (parameters != null && parameters.length != 0) {
for (int i = 0; i < parameters.length; i++) {
if (parameters[i].getType() == ExternalAppRequestParam.class) {
ExternalAppRequestParam requestParam = (ExternalAppRequestParam) point.getArgs()[i];
requestParam.setAppId(appId);
requestParam.setCustomerId(authResult.getCustomerId());
}
}
}
}
public HttpServletRequest getRequest() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;
return sra.getRequest();
}
}

12
epmet-commons/epmet-commons-extapp-auth/src/main/java/com/epmet/commons/extappauth/bean/ExternalAppRequestParam.java

@ -0,0 +1,12 @@
package com.epmet.commons.extappauth.bean;
import lombok.Data;
/**
* 外部应用请求信息
*/
@Data
public class ExternalAppRequestParam {
private String customerId;
private String appId;
}

1
epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/exception/EpmetErrorCode.java

@ -99,6 +99,7 @@ public enum EpmetErrorCode {
OPER_ADD_CUSTOMER_MANAGER_ERROR(8706, "新增客户管理员失败"),
OPER_UPLOAD_FILE_OVER_SIZE(8707, "文件体积过大"),
OPER_UPLOAD_FILE_TYPE_ERROR(8708, "文件类型错误"),
OPER_EXTERNAL_APP_AUTH_ERROR(8709, "外部应用鉴权失败"),
// 党建声音 前端提示 88段
DRAFT_CONTENT_IS_NULL(8801, "至少需要添加一个段落"),

9
epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/redis/RedisKeys.java

@ -288,4 +288,13 @@ public class RedisKeys {
public static String getVolunteerSmsCodeKey(String phone) {
return String.format(rootPrefix+"smscode:regvolunteer:%s",phone);
}
/**
* 外部应用的secret key
* @param appId
* @return
*/
public static String getExternalAppSecretKey(String appId) {
return String.format(rootPrefix+"externalapp:secret:%s",appId);
}
}

1
epmet-commons/pom.xml

@ -22,6 +22,7 @@
<module>epmet-commons-tools-wx-ma</module>
<module>epmet-commons-tools-wx-mp</module>
<module>epmet-commons-service-call</module>
<module>epmet-commons-extapp-auth</module>
</modules>
</project>

5
epmet-module/data-report/data-report-server/pom.xml

@ -62,6 +62,11 @@
<version>0.3.1</version>
</dependency>
<dependency>
<groupId>com.epmet</groupId>
<artifactId>epmet-commons-extapp-auth</artifactId>
<version>2.0.0</version>
</dependency>
</dependencies>
<build>

19
epmet-module/data-report/data-report-server/src/main/java/com/epmet/controller/test/TestController.java

@ -0,0 +1,19 @@
package com.epmet.controller.test;
import com.epmet.commons.extappauth.annotation.ExternalAppRequestAuth;
import com.epmet.commons.extappauth.bean.ExternalAppRequestParam;
import com.epmet.commons.tools.utils.Result;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("test")
public class TestController {
@ExternalAppRequestAuth
@RequestMapping("/test")
public Result test(ExternalAppRequestParam externalAppRequestParam, String ext) {
return new Result().ok("调用成功,客户信息:"+externalAppRequestParam);
}
}

18
epmet-module/epmet-common-service/common-service-client/src/main/java/com/epmet/dto/form/ExternalAppAuthFormDTO.java

@ -0,0 +1,18 @@
package com.epmet.dto.form;
import lombok.Data;
@Data
public class ExternalAppAuthFormDTO {
/**
* 应用ID
*/
private String appId;
/**
* token字符串
*/
private String token;
}

10
epmet-module/epmet-common-service/common-service-client/src/main/java/com/epmet/dto/result/ExternalAppAuthResultDTO.java

@ -0,0 +1,10 @@
package com.epmet.dto.result;
import lombok.Data;
@Data
public class ExternalAppAuthResultDTO {
private Boolean success;
private String message;
private String customerId;
}

13
epmet-module/epmet-common-service/common-service-client/src/main/java/com/epmet/feign/EpmetCommonServiceOpenFeignClient.java

@ -2,7 +2,9 @@ package com.epmet.feign;
import com.epmet.commons.tools.constant.ServiceConstant;
import com.epmet.commons.tools.utils.Result;
import com.epmet.dto.form.ExternalAppAuthFormDTO;
import com.epmet.dto.form.WorkDayFormDTO;
import com.epmet.dto.result.ExternalAppAuthResultDTO;
import com.epmet.dto.result.WorkDayResultDTO;
import com.epmet.feign.fallback.EpmetCommonServiceOpenFeignClientFallback;
import org.springframework.cloud.openfeign.FeignClient;
@ -17,7 +19,8 @@ import java.util.List;
* @author yinzuomei@elink-cn.com
* @date 2020/6/4 10:28
*/
@FeignClient(name = ServiceConstant.EPMET_COMMON_SERVICE, fallback = EpmetCommonServiceOpenFeignClientFallback.class)
//@FeignClient(name = ServiceConstant.EPMET_COMMON_SERVICE, fallback = EpmetCommonServiceOpenFeignClientFallback.class)
@FeignClient(name = ServiceConstant.EPMET_COMMON_SERVICE, fallback = EpmetCommonServiceOpenFeignClientFallback.class, url = "http://localhost:8103")
public interface EpmetCommonServiceOpenFeignClient {
/**
* @param formDTO
@ -28,4 +31,12 @@ public interface EpmetCommonServiceOpenFeignClient {
**/
@PostMapping("commonservice/workday/detentiondays")
Result<List<WorkDayResultDTO>> detentionDays(@RequestBody List<WorkDayFormDTO> formDTO);
/**
* 外部应用认证接口
* @param formDTO
* @return
*/
@PostMapping("/commonservice/externalapp/auth")
Result<ExternalAppAuthResultDTO> externalAppAuth(@RequestBody ExternalAppAuthFormDTO formDTO);
}

7
epmet-module/epmet-common-service/common-service-client/src/main/java/com/epmet/feign/fallback/EpmetCommonServiceOpenFeignClientFallback.java

@ -3,7 +3,9 @@ package com.epmet.feign.fallback;
import com.epmet.commons.tools.constant.ServiceConstant;
import com.epmet.commons.tools.utils.ModuleUtils;
import com.epmet.commons.tools.utils.Result;
import com.epmet.dto.form.ExternalAppAuthFormDTO;
import com.epmet.dto.form.WorkDayFormDTO;
import com.epmet.dto.result.ExternalAppAuthResultDTO;
import com.epmet.dto.result.WorkDayResultDTO;
import com.epmet.feign.EpmetCommonServiceOpenFeignClient;
import org.springframework.stereotype.Component;
@ -22,4 +24,9 @@ public class EpmetCommonServiceOpenFeignClientFallback implements EpmetCommonSer
public Result<List<WorkDayResultDTO>> detentionDays(List<WorkDayFormDTO> formDTO) {
return ModuleUtils.feignConError(ServiceConstant.EPMET_COMMON_SERVICE, "detentionDays", formDTO);
}
@Override
public Result<ExternalAppAuthResultDTO> externalAppAuth(ExternalAppAuthFormDTO formDTO) {
return ModuleUtils.feignConError(ServiceConstant.EPMET_COMMON_SERVICE, "externalAppAuth", formDTO);
}
}

6
epmet-module/epmet-common-service/common-service-server/pom.xml

@ -58,6 +58,12 @@
<artifactId>feign-httpclient</artifactId>
<version>10.3.0</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
</dependencies>
<build>

39
epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/controller/ExternalAppController.java

@ -0,0 +1,39 @@
package com.epmet.controller;
import com.epmet.commons.tools.exception.RenException;
import com.epmet.commons.tools.utils.Result;
import com.epmet.dto.form.ExternalAppAuthFormDTO;
import com.epmet.dto.result.ExternalAppAuthResultDTO;
import com.epmet.service.ExternalAppAuthService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/externalapp")
public class ExternalAppController {
private static Logger logger = LoggerFactory.getLogger(ExternalAppController.class);
@Autowired
private ExternalAppAuthService externalAppAuthService;
@PostMapping("/auth")
public Result<ExternalAppAuthResultDTO> auth(@RequestBody ExternalAppAuthFormDTO formDTO) {
String appId = formDTO.getAppId();
String token = formDTO.getToken();
if (StringUtils.isAnyBlank(token, appId)) {
throw new RenException("请求头中的token和appId不能为空");
}
logger.info("外部应用请求认证拦截Aspect。appId:{}, token:{}", appId, token);
ExternalAppAuthResultDTO auth = externalAppAuthService.auth(appId, token);
return new Result<ExternalAppAuthResultDTO>().ok(auth);
}
}

33
epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/dao/ExternalAppDao.java

@ -0,0 +1,33 @@
/**
* Copyright 2018 人人开源 https://www.renren.io
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epmet.dao;
import com.epmet.commons.mybatis.dao.BaseDao;
import com.epmet.entity.ExternalAppEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* 外部应用列表
*
* @author generator generator@elink-cn.com
* @since v1.0.0 2020-08-18
*/
@Mapper
public interface ExternalAppDao extends BaseDao<ExternalAppEntity> {
}

43
epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/dao/ExternalAppSecretDao.java

@ -0,0 +1,43 @@
/**
* Copyright 2018 人人开源 https://www.renren.io
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epmet.dao;
import com.epmet.commons.mybatis.dao.BaseDao;
import com.epmet.entity.ExternalAppSecretEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 外部应用秘钥列表
*
* @author generator generator@elink-cn.com
* @since v1.0.0 2020-08-18
*/
@Mapper
public interface ExternalAppSecretDao extends BaseDao<ExternalAppSecretEntity> {
/**
* 查询app对应的秘钥
* @param appId
* @return
*/
ExternalAppSecretEntity getSecretsByAppId(@Param("appId") String appId);
}

51
epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/entity/ExternalAppEntity.java

@ -0,0 +1,51 @@
/**
* Copyright 2018 人人开源 https://www.renren.io
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epmet.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.epmet.commons.mybatis.entity.BaseEpmetEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
/**
* 外部应用列表
*
* @author generator generator@elink-cn.com
* @since v1.0.0 2020-08-18
*/
@Data
@EqualsAndHashCode(callSuper=false)
@TableName("external_app")
public class ExternalAppEntity extends BaseEpmetEntity {
private static final long serialVersionUID = 1L;
/**
* APP名字
*/
private String appName;
/**
* 客户ID
*/
private String customerId;
}

51
epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/entity/ExternalAppSecretEntity.java

@ -0,0 +1,51 @@
/**
* Copyright 2018 人人开源 https://www.renren.io
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epmet.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.epmet.commons.mybatis.entity.BaseEpmetEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
/**
* 外部应用秘钥列表
*
* @author generator generator@elink-cn.com
* @since v1.0.0 2020-08-18
*/
@Data
@EqualsAndHashCode(callSuper=false)
@TableName("external_app_secret")
public class ExternalAppSecretEntity extends BaseEpmetEntity {
private static final long serialVersionUID = 1L;
/**
* APP ID
*/
private String appId;
/**
* 秘钥
*/
private String secret;
}

9
epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/ExternalAppAuthService.java

@ -0,0 +1,9 @@
package com.epmet.service;
import com.epmet.dto.result.ExternalAppAuthResultDTO;
public interface ExternalAppAuthService {
ExternalAppAuthResultDTO auth(String appId, String token);
}

28
epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/ExternalAppSecretService.java

@ -0,0 +1,28 @@
/**
* Copyright 2018 人人开源 https://www.renren.io
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epmet.service;
/**
* 外部应用秘钥列表
*
* @author generator generator@elink-cn.com
* @since v1.0.0 2020-08-18
*/
public interface ExternalAppSecretService {
}

27
epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/ExternalAppService.java

@ -0,0 +1,27 @@
/**
* Copyright 2018 人人开源 https://www.renren.io
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epmet.service;
/**
* 外部应用列表
*
* @author generator generator@elink-cn.com
* @since v1.0.0 2020-08-18
*/
public interface ExternalAppService {
}

83
epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/impl/ExternalAppAuthServiceImpl.java

@ -0,0 +1,83 @@
package com.epmet.service.impl;
import com.epmet.commons.tools.exception.ExceptionUtils;
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 com.epmet.service.ExternalAppAuthService;
import com.epmet.utils.externalapp.ExtAppJwtTokenUtils;
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.Service;
@Service
public class ExternalAppAuthServiceImpl implements ExternalAppAuthService {
private static Logger logger = LoggerFactory.getLogger(ExternalAppAuthServiceImpl.class);
@Autowired
private RedisUtils redisUtils;
@Autowired
private ExtAppJwtTokenUtils jwtTokenUtils;
@Autowired
private ExternalAppSecretDao externalAppSecretDao;
@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);
}
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");
if (!appId.equals(appIdIn)) {
logger.error("AppId不对应,token外部的:{}, token内部解析出来的:{}", appId, appIdIn);
return fillAuthResult(false, "Header中的AppId不匹配", null);
}
return fillAuthResult(true, "解析成功", customerId);
}
/**
* 通过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;
}
}

31
epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/impl/ExternalAppSecretServiceImpl.java

@ -0,0 +1,31 @@
/**
* Copyright 2018 人人开源 https://www.renren.io
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epmet.service.impl;
import com.epmet.service.ExternalAppSecretService;
import org.springframework.stereotype.Service;
/**
* 外部应用秘钥列表
*
* @author generator generator@elink-cn.com
* @since v1.0.0 2020-08-18
*/
@Service
public class ExternalAppSecretServiceImpl implements ExternalAppSecretService {
}

33
epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/service/impl/ExternalAppServiceImpl.java

@ -0,0 +1,33 @@
/**
* Copyright 2018 人人开源 https://www.renren.io
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epmet.service.impl;
import com.epmet.service.ExternalAppService;
import org.springframework.stereotype.Service;
/**
* 外部应用列表
*
* @author generator generator@elink-cn.com
* @since v1.0.0 2020-08-18
*/
@Service
public class ExternalAppServiceImpl implements ExternalAppService {
}

92
epmet-module/epmet-common-service/common-service-server/src/main/java/com/epmet/utils/externalapp/ExtAppJwtTokenUtils.java

@ -0,0 +1,92 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有侵权必究
*/
package com.epmet.utils.externalapp;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Jwt工具类
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Component
public class ExtAppJwtTokenUtils {
private static final Logger logger = LoggerFactory.getLogger(ExtAppJwtTokenUtils.class);
public Claims getClaimByToken(String token, String secret) {
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
}
public Claims tryGetClaimByToken(String token, String secret) {
try {
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
} catch (Exception e) {
logger.debug("validate is token error, token = " + token, e);
return null;
}
}
public String createToken(Map<String, Object> map, String secret) {
return Jwts.builder()
.setHeaderParam("typ", "JWT")
.setClaims(map)
.setIssuedAt(new Date())
// .setExpiration(DateTime.now().plusSeconds(jwtProperties.getExpire()).toDate())
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
// /**
// * token是否过期
// *
// * @return true:过期
// */
// public boolean isTokenExpired(Date expiration) {
// return expiration.before(new Date());
// }
public static void main(String[] args) {
genToken();
// getClaim();
}
public static void genToken() {
HashMap<String, Object> claim = new HashMap<>();
claim.put("appId", "1");
// claim.put("customerId", "c1");
String abc = new ExtAppJwtTokenUtils().createToken(claim, "4a762660254c57996343f8ee42fbc0a6");
System.out.println(abc);
}
public static void getClaim() {
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJhcHBJZCI6IjEiLCJjdXN0b21lcklkIjoiYzEiLCJpYXQiOjE1OTc3NDI2NTB9.09Vop0Nobg3LENAJoAZaCUKtgAjADAK48BS11ky3YdAp6h-cXYtGeqUxbgvE_4F6239rc7UE2fjxtEvMuWEJuA";
Claims claimByToken = new ExtAppJwtTokenUtils().getClaimByToken(token, "4a762660254c57996343f8ee42fbc0a6");
System.out.println(claimByToken);
}
}

19
epmet-module/epmet-common-service/common-service-server/src/main/resources/mapper/ExternalAppDao.xml

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.epmet.dao.ExternalAppDao">
<resultMap type="com.epmet.entity.ExternalAppEntity" id="externalAppMap">
<result property="id" column="ID"/>
<result property="appName" column="APP_NAME"/>
<result property="customerId" column="CUSTOMER_ID"/>
<result property="delFlag" column="DEL_FLAG"/>
<result property="revision" column="REVISION"/>
<result property="createdBy" column="CREATED_BY"/>
<result property="createdTime" column="CREATED_TIME"/>
<result property="updatedBy" column="UPDATED_BY"/>
<result property="updatedTime" column="UPDATED_TIME"/>
</resultMap>
</mapper>

37
epmet-module/epmet-common-service/common-service-server/src/main/resources/mapper/ExternalAppSecretDao.xml

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.epmet.dao.ExternalAppSecretDao">
<resultMap type="com.epmet.entity.ExternalAppSecretEntity" id="externalAppSecretMap">
<result property="id" column="ID"/>
<result property="appId" column="APP_ID"/>
<result property="secret" column="SECRET"/>
<result property="delFlag" column="DEL_FLAG"/>
<result property="revision" column="REVISION"/>
<result property="createdBy" column="CREATED_BY"/>
<result property="createdTime" column="CREATED_TIME"/>
<result property="updatedBy" column="UPDATED_BY"/>
<result property="updatedTime" column="UPDATED_TIME"/>
</resultMap>
<select id="getSecretsByAppId" resultType="com.epmet.entity.ExternalAppSecretEntity">
SELECT
ID,
APP_ID,
SECRET,
DEL_FLAG,
REVISION,
CREATED_BY,
CREATED_TIME,
UPDATED_BY,
UPDATED_TIME
FROM
external_app_secret
WHERE
APP_ID = #{appId}
AND DEL_FLAG = 0
</select>
</mapper>
Loading…
Cancel
Save