Commit 31448eae by 刘宇峰

授权服务

0 parents
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>cn.com.glsx</groupId>
<artifactId>platform-auth-server</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<description>Microservice Scaffolding Api Base on Spring Cloud</description>
<artifactId>platform-auth-api</artifactId>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-jwt</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-feign</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.auth.config;
import cn.com.glsx.auth.model.GatewayService;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author huangch
* @version V1.0
* @Title: ApiGatewayConsumerConfig
* @Description:
* @Company: Didihu.com.cn
* @Date 2023/4/6 10:36
*/
@ConfigurationProperties(prefix = "gateway")
@Component
public class ApiGatewayServiceConfig {
private Map<String, GatewayService> services;
private Boolean signSwitch;
public void setSignSwitch(Boolean signSwitch) {
this.signSwitch = signSwitch;
}
public void setServices(Map<String, GatewayService> services) {
Map<String, GatewayService> newMap = new ConcurrentHashMap<>();
for(Map.Entry<String, GatewayService> entry : services.entrySet()){
GatewayService gatewayService = entry.getValue();
gatewayService.setName(entry.getKey());
newMap.put(gatewayService.getAppKey(), gatewayService);
}
this.services = newMap;
}
public GatewayService getServiceByAppKey(String appKey){
return this.services .get(appKey);
}
}
package cn.com.glsx.auth.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author huangch
* @version V1.0
* @Title: Consumer
* @Description:
* @Company: Didihu.com.cn
* @Date 2023/4/6 10:40
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class GatewayService {
/**
* 调用方英文名称
*/
private String name;
/**
* 调用方中文名称
*/
private String remark;
/**
* appKey
*/
private String appKey;
/**
* secret:秘钥
*/
private String secret;
/**
* 是否对调用方开启IP鉴权
*/
private Boolean ipAuth;
/**
* 调用方IP白名单
*/
private String whiteIps;
/**
* 是否校验调用方的签名
*/
private Boolean checkSign;
/**
* 是否校验调用方的JWT
*/
private Boolean jwtAuth;
/**
* 签名的有效时间,默认24小时
*/
private Long jwtTtl = 24 * 60 * 60 * 1000L;
/**
* 生效时间偏移量
*/
private Integer jwtIssueAtOffset;
}
package cn.com.glsx.auth.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@Builder
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class OpenApiResult<T> implements Serializable {
private static final String SUCCESS_DEFAULT_CODE = "00000";
private static final String FAILURE_DEFAULT_CODE = "40004";
private Boolean success;
private String code;
private String desc;
private T result;
private Long time;
public static <T> OpenApiResult<T> success(T result) {
return OpenApiResult.<T>builder()
.code(SUCCESS_DEFAULT_CODE)
.success(true)
.desc("成功")
.result(result)
.time(System.currentTimeMillis())
.build();
}
public static <T> OpenApiResult<T> failure(String code, String desc) {
return OpenApiResult.<T>builder()
.success(true)
.code(code)
.desc(desc)
.result(null)
.time(System.currentTimeMillis())
.build();
}
}
package cn.com.glsx.auth.utils;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import cn.com.glsx.auth.model.GatewayService;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class GatewayJwtUtils {
private static final Logger log = LoggerFactory.getLogger(GatewayJwtUtils.class);
private static final String PAYLOAD_MAP = "payloadMap";
public final String JWT_SESSION_PREFIX = "JWT-SESSION-";
public final String CLAZZ = "clazz";
public final String BEARER = "Bearer ";
@Resource
private StringRedisTemplate stringRedisTemplate;
public GatewayJwtUtils() {
}
public static void main(String[] args) {
// GatewayService gatewayService = GatewayService.builder().name("scrm-shopmall")
// .remark("scrm商城")
// .appKey("48e5e13229b82c1b4e6e8c96151f0637")
// .secret("c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b")
// .ipAuth(true)
// .whiteIps("192.168.1.140,192.168.0.1")
// .checkSign(true)
// .jwtAuth(true)
// .jwtTtl(86400000L)
// .jwtIssueAtOffset(60000)
// .build();
// Map<String, Object> userMap = new ConcurrentHashMap<>();
// userMap.put("name", gatewayService.getName());
// GatewayJwtUtils jwtUtils = new GatewayJwtUtils();
// String token = jwtUtils.createToken(userMap, gatewayService);
// DecodedJWT decode = jwtUtils.decode(token);
// System.out.println(decode.getClaim("name"));
}
public String genSecretKey(Instant instant) {
return String.valueOf(instant.getEpochSecond());
}
public static String createToken(Map<String, Object> userMap, GatewayService gatewayService) {
String token = create(userMap, Instant.now(), gatewayService);
log.debug("create id {} token [" + token + "]", gatewayService.getName());
return token;
}
public String createCachedToken(Map<String, Object> userMap, GatewayService gatewayService) {
String token = this.create(userMap, Instant.now(), gatewayService);
this.stringRedisTemplate.opsForValue().set(gatewayService.getName(), token, gatewayService.getJwtTtl(), TimeUnit.MILLISECONDS);
log.debug("create id {} token [" + token + "]", gatewayService.getName());
return token;
}
private static String create(Map<String, Object> claims, Instant issueAt, GatewayService gatewayService) {
Algorithm algorithm = Algorithm.HMAC256(gatewayService.getSecret());
Instant exp = issueAt.plusSeconds(gatewayService.getJwtTtl());
Map<String, Object> newClaims = new HashMap();
Iterator var9 = claims.entrySet().iterator();
while(var9.hasNext()) {
Entry<String, Object> entry = (Entry)var9.next();
String key = (String)entry.getKey();
Object value = entry.getValue();
if (!"class".equals(key) && !Objects.isNull(value)) {
newClaims.put(key, value);
}
}
JWTCreator.Builder builder = JWT.create().withJWTId(gatewayService.getName()).withClaim("iat", Date.from(issueAt.plusSeconds(gatewayService.getJwtIssueAtOffset() == null ? 0L : (long)(-gatewayService.getJwtIssueAtOffset())))).withClaim("exp", Date.from(exp)).withClaim("payloadMap", newClaims);
builder.withSubject(gatewayService.getName()).withClaim("name", gatewayService.getName());
String token = builder.sign(algorithm);
log.trace("create token [" + token + "]; iat: " + Date.from(exp) + " exp: " + Date.from(exp));
return token;
}
public DecodedJWT decode(String token) {
if (token.startsWith(BEARER)) {
token = token.replace(BEARER, "");
}
return com.auth0.jwt.JWT.decode(token);
}
public DecodedJWT verify(String token, GatewayService gatewayService) {
return this.verify(gatewayService.getSecret(), token);
}
public DecodedJWT verify(String secretKey, String token) {
if (token.startsWith(BEARER)) {
token = token.replace(BEARER, "");
}
Algorithm algorithm = Algorithm.HMAC256(secretKey);
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT jwt = null;
try {
jwt = verifier.verify(token);
} catch (JWTVerificationException var7) {
log.error(var7.getMessage());
} catch (Exception var8) {
var8.printStackTrace();
log.error(var8.getMessage());
}
return jwt;
}
public Map<String, Object> parseClaim(String token) {
return this.decode(token).getClaim("payloadMap").asMap();
}
public Class getJwtUserClass(String token) throws ClassNotFoundException {
String jwtUserClazz = (String)this.parseClaim(token).get("clazz");
log.debug("token jwt user clazz [" + jwtUserClazz + "]");
Class clazz = Class.forName(jwtUserClazz);
return clazz;
}
public boolean verifyToken(String token, GatewayService gatewayService) {
log.debug("verify token [" + token + "]");
try {
this.verify(token, gatewayService);
return true;
} catch (JWTVerificationException var3) {
log.error(var3.getMessage());
} catch (Exception var4) {
var4.printStackTrace();
log.error(var4.getMessage());
}
return false;
}
public boolean verifyCachedToken(String token, GatewayService gatewayService) {
if (StringUtils.isEmpty(token)) {
return false;
} else {
if (token.startsWith(BEARER)) {
token = token.replace(BEARER, "");
}
try {
DecodedJWT decodedJWT = this.verify(token, gatewayService);
String redisToken = (String)this.stringRedisTemplate.opsForValue().get(decodedJWT.getId());
if (!token.equals(redisToken)) {
return false;
}
this.stringRedisTemplate.opsForValue().set(decodedJWT.getId(), redisToken, gatewayService.getJwtTtl(), TimeUnit.SECONDS);
return true;
} catch (TokenExpiredException var4) {
log.error(var4.getMessage());
} catch (Exception var5) {
var5.printStackTrace();
log.error(var5.getMessage());
}
return false;
}
}
public boolean isTokenOutExpiresAt(DecodedJWT jwtToken, Instant instant) {
Instant exp = jwtToken.getExpiresAt().toInstant();
return instant.compareTo(exp) >= 0;
}
public String refreshCachedToken(DecodedJWT jwtToken, GatewayService gatewayService) {
String refreshToken = this.refreshToken(jwtToken, gatewayService);
this.stringRedisTemplate.opsForValue().set(gatewayService.getName(), refreshToken, gatewayService.getJwtTtl(), TimeUnit.SECONDS);
return refreshToken;
}
public String refreshToken(DecodedJWT jwtToken, GatewayService gatewayService) {
Instant now = Instant.now();
Instant exp = jwtToken.getExpiresAt().toInstant();
Algorithm algorithm = Algorithm.HMAC256(gatewayService.getSecret());
Instant newExp = exp.plusSeconds(gatewayService.getJwtTtl());
String token = JWT.create().withJWTId(jwtToken.getId()).withClaim("sub", jwtToken.getSubject()).withClaim("iat", Date.from(exp)).withClaim("exp", Date.from(newExp)).withClaim("payloadMap", jwtToken.getClaim("payloadMap").asMap()).sign(algorithm);
log.debug("create refresh token [" + token + "]; iat: " + Date.from(exp) + " exp: " + Date.from(newExp));
return token;
}
public void destroyToken(String token) {
this.decode(token);
}
public void destroyCachedToken(String token) {
DecodedJWT decodedJWT = this.decode(token);
this.stringRedisTemplate.delete(decodedJWT.getId());
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>cn.com.glsx</groupId>
<artifactId>platform-auth-server</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<description>Microservice Scaffolding Project Base on Spring Cloud</description>
<artifactId>platform-auth</artifactId>
<dependencies>
<!-- 运行环境上下文 -->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-context</artifactId>
</dependency>
<!-- 接入微服务组件联盟 配置、注册、网关、链路、监控等 ,单体应用无需引入(logback-spring.xml与logstash相关内容需要注释掉)-->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-swagger3</artifactId>
</dependency>
<!-- local api -->
<dependency>
<groupId>cn.com.glsx</groupId>
<artifactId>platform-auth-api</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx;
import cn.com.glsx.auth.config.ApiGatewayServiceConfig;
import com.glsx.plat.context.EnableRestAdmin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
import static java.time.ZoneId.of;
import static java.util.TimeZone.getTimeZone;
/**
* @author payu
*/
@EnableRestAdmin
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableConfigurationProperties({ApiGatewayServiceConfig.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@PostConstruct
void started() {
TimeZone.setDefault(getTimeZone(of("Asia/Shanghai")));
}
}
package cn.com.glsx.auth.modules.controller;
import cn.com.glsx.auth.config.ApiGatewayServiceConfig;
import cn.com.glsx.auth.model.GatewayService;
import cn.com.glsx.auth.model.OpenApiResult;
import cn.com.glsx.auth.modules.request.CraneQueryAccessTokenRequest;
import cn.com.glsx.auth.modules.utils.SM3Utils;
import cn.com.glsx.auth.utils.GatewayJwtUtils;
import com.glsx.plat.common.utils.DateUtils;
import com.glsx.plat.common.utils.MD5Util;
import com.glsx.plat.exception.OpenApiResultException;
import com.glsx.plat.exception.ResultException;
import lombok.extern.slf4j.Slf4j;
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;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author huangch
* @version V1.0
* @Title: AuthController
* @Description:
* @Company: Didihu.com.cn
* @Date 2023/4/6 18:08
*/
@Slf4j
@RestController
@RequestMapping(value = "/open/api")
public class AuthController {
@Autowired
private ApiGatewayServiceConfig apiGatewayServiceConfig;
@Autowired
private GatewayJwtUtils gatewayJwtUtils;
@PostMapping("/access/queryAccessToken")
public OpenApiResult<Map<String, Object>> queryAccessToken(@Valid @RequestBody CraneQueryAccessTokenRequest request) {
try {
GatewayService gatewayService = verrfyRequestParam(request);
//生成token返回
Map<String, Object> userMap = new HashMap<>();
userMap.put("name", gatewayService.getName());
String token = gatewayJwtUtils.createToken(userMap, gatewayService);
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("accessToken", token);
resultMap.put("expiresAt", DateUtils.format(DateUtils.addDateDays(new Date(), 1), DateUtils.NORMAL_DATE_TIME_PATTERN));
return OpenApiResult.success(resultMap);
} catch (Exception e) {
throw OpenApiResultException.create("授权失败");
}
}
private GatewayService verrfyRequestParam(CraneQueryAccessTokenRequest request) {
GatewayService gatewayService = apiGatewayServiceConfig.getServiceByAppKey(request.getAppKey());
if (gatewayService == null) {
throw ResultException.create("请求参数校验不通过");
}
//验证时间戳
long diff = System.currentTimeMillis() - Long.parseLong(request.getTimestamp());
if (diff < 0 || diff > 5 * 60 * 1000L) {
throw ResultException.create("请求参数timestamp不在系统允许的范围内");
}
//验证secret
if ("SM3".equals(request.getGrantType())) {
if (!SM3Utils.verify(gatewayService.getSecret(), request.getAppSecret(), gatewayService.getAppKey())) {
throw ResultException.create("请求参数校验不通过");
}
} else {
if (!request.getAppSecret().equals(gatewayService.getSecret().toLowerCase())) {
throw ResultException.create("请求参数校验不通过");
}
}
//验证签名
String signedParams = gatewayService.getAppKey() + gatewayService.getSecret() + request.getTimestamp() + gatewayService.getSecret();
String sign = MD5Util.convert32(signedParams).toLowerCase();
log.info("签名参数:{}", signedParams);
log.info("生成签名:{}", sign);
if ("SM3".equals(request.getGrantType())) {
sign = SM3Utils.encrypt(signedParams, gatewayService.getAppKey());
}
if (!sign.equals(request.getSign())) {
throw ResultException.create("签名错误");
}
return gatewayService;
}
}
package cn.com.glsx.auth.modules.request;
import lombok.Data;
import javax.validation.constraints.NotBlank;
/**
* @author huangch
* @version V1.0
* @Title: CraneQueryAccessTokenRequest
* @Description:
* @Company: Didihu.com.cn
* @Date 2023/4/13 15:31
*/
@Data
public class CraneQueryAccessTokenRequest {
@NotBlank(message = "appKey不能为空")
private String appKey;
@NotBlank(message = "appSecret不能为空")
private String appSecret;
@NotBlank(message = "sign不能为空")
private String sign;
@NotBlank(message = "timestamp不能为空")
private String timestamp;
private String grantType;
}
package cn.com.glsx.auth.modules.utils;
import com.glsx.plat.common.utils.MD5Util;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Arrays;
public class SM3Utils {
private static final String ENCODING = "UTF-8";
static {
Security.addProvider(new BouncyCastleProvider());
}
/**
* sm3 算法加密
*
* @param paramStr 待加密的参数字符串
* @param appKey 加密的密钥 appKey(接口访问秘钥 Key)
* @return 返回 SM3 加密后固定长度为 32 的 16 进制密内容文字符串
* @explain
*/
public static String encrypt(String paramStr, String appKey) {
// 将返回的 hash 值转换成 16 进制字符串
String resultHexStr = "";
try {
// 将字符串转换成 byte 数组
byte[] srcData = paramStr.getBytes(ENCODING);
// 调用 hash()
byte[] resultHash = hmac(srcData, appKey.getBytes(ENCODING));
// 将返回的 hash 值转换成 16 进制字符串
resultHexStr = ByteUtils.toHexString(resultHash);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return resultHexStr;
}
/**
* 通过密钥进行哈希
*
* @param appKey 加密的密钥 appKey 的 byte 数组
* @param srcData 被加密参数字符串的 byte 数组
* @return
*/
public static byte[] hmac(byte[] appKey, byte[] srcData) {
KeyParameter keyParameter = new KeyParameter(appKey);
SM3Digest digest = new SM3Digest();
HMac mac = new HMac(digest);
mac.init(keyParameter);
mac.update(srcData, 0, srcData.length);
byte[] result = new byte[mac.getMacSize()];
mac.doFinal(result, 0);
return result;
}
/**
* 第 8 页 共 105 页
* 第 9 页 共 105 页
* 判断待加密的原始数据与加密后的数据是否一致
*
* @param paramStr 待加密的参数字符串
* @param resultHexStr SM3 加密后固定长度为 32 的 16 进制密内容文字符串
* @param appKey 加密的密钥 appKey 的 byte 数组
* @return 校验结果
*/
public static boolean verify(String paramStr, String resultHexStr, String appKey) {
boolean flag = false;
try {
byte[] srcData = paramStr.getBytes(ENCODING);
byte[] sm3Hash = ByteUtils.fromHexString(resultHexStr);
byte[] newHash = hmac(srcData, appKey.getBytes(ENCODING));
if (Arrays.equals(newHash, sm3Hash)) {
flag = true;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return flag;
}
public static void main(String[] args) {
// // 待加密的待加密的参数字符串
// String paramStr = "6bba9d97c252661067758b2b6f80e7c558e562b8";
// // 加密的密钥 appKey
// String appKey = "RaOF35Kw";
// // sm3 算法加密
// String resultHexStr = SM3Utils.encrypt(paramStr, appKey);
// System.out.println("待加密的待加密的参数字符串:" + paramStr);
// System.out.println("SM3 加密后的密文字符串内容:" + resultHexStr);
// System.out.println("校验结果:" + SM3Utils.verify(paramStr, resultHexStr, appKey));
System.out.println(System.currentTimeMillis());
System.out.println(MD5Util.convert32("e7794d5173c29275ed74f3e8fc2d9d8171d3d7d3a8953f27").toLowerCase());
}
}
\ No newline at end of file \ No newline at end of file
#项目名称
spring.application.name=platform-auth
server.servlet.context-path=/
server.port=8081
#日志路径(logback-spring.xml读取,不要加入配置中心)
logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
#nacos配置中心
spring.cloud.nacos.config.server-addr=192.168.0.63:8868
#nacos配置id,完整dataId=${spring.cloud.nacos.config.prefix}-${spring.profiles.active}.${file-extension(由新增配置时选的文件类型决定)}
#示例:http://192.168.0.63:8848/nacos/v1/cs/configs?dataId=glsx-rest-admin.properties&group=DEV_GROUP
#配置分组(改成项目相关的)
spring.cloud.nacos.config.group=PLATFORM_GROUP
#配置prefix,默认值同${spring.application.name}
spring.cloud.nacos.config.prefix=${spring.application.name}
#配置环境
spring.profiles.active=dev
#配置格式
spring.cloud.nacos.config.file-extension=properties
#微服务sentinel、zipkin、actuator等公共配置
spring.cloud.nacos.config.shared-configs[0].data-id=platform-microservice-share.properties
spring.cloud.nacos.config.shared-configs[0].group=${spring.cloud.nacos.config.group}
spring.cloud.nacos.config.shared-configs[0].refresh=true
#数据库、redis等公共配置
spring.cloud.nacos.config.shared-configs[1].data-id=platform-share-dev.properties
spring.cloud.nacos.config.shared-configs[1].group=${spring.cloud.nacos.config.group}
spring.cloud.nacos.config.shared-configs[1].refresh=true
#鉴权公共配置
spring.cloud.nacos.config.shared-configs[2].data-id=plateform-auth-common-dev.properties
spring.cloud.nacos.config.shared-configs[2].group=${spring.cloud.nacos.config.group}
spring.cloud.nacos.config.shared-configs[2].refresh=true
spring.main.allow-circular-references=true
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
<?xml version="1.0" encoding="UTF-8" ?>
<!--
说明:
1. 文件的命名和加载顺序有关
logback.xml早于application.yml加载,logback-spring.xml晚于application.yml加载
如果logback配置需要使用application.yml中的属性,需要命名为logback-spring.xml
2. logback使用application.yml中的属性
使用springProperty才可使用application.yml中的值 可以设置默认值
如果非要用yaml文件,那么只能使用绝对路径,例如:
logback-spring.xml引入文件:
<property file="${HOME}/configuration/application.yaml"/>
-->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property resource="bootstrap.properties"/>
<property name="APP_NAME" value="${spring.application.name}"/>
<!-- 生成日志文件目录 -->
<property name="LOG_FILE" value="${logging.path}"/>
<contextName>${APP_NAME}</contextName>
<turboFilter class="com.glsx.plat.common.loggin.BootTurboFilter">
<Marker>${APP_NAME}</Marker>
</turboFilter>
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<!-- <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />-->
<!-- <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />-->
<!-- <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />-->
<!-- 配置日志输出参数,彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<!-- 控制台打印日志 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!-- Minimum logging level to be presented in the console logs-->
<level>INFO</level>
</filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志定时生成压缩文件 -->​
<appender name="flatfile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FILE}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志进行格式化 -->
<!-- <appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">-->
<!-- <file>${LOG_FILE}.json</file>-->
<!-- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">-->
<!-- <fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>-->
<!-- <maxHistory>7</maxHistory>-->
<!-- </rollingPolicy>-->
<!-- <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">-->
<!-- <providers>-->
<!-- <timestamp>-->
<!-- <timeZone>UTC</timeZone>-->
<!-- </timestamp>-->
<!-- <pattern>-->
<!-- <pattern>-->
<!-- {-->
<!-- "severity": "%level",-->
<!-- "service": "${APP_NAME:-}",-->
<!-- "trace": "%X{X-B3-TraceId:-}",-->
<!-- "span": "%X{X-B3-SpanId:-}",-->
<!-- "parent": "%X{X-B3-ParentSpanId:-}",-->
<!-- "exportable": "%X{X-Span-Export:-}",-->
<!-- "pid": "${PID:-}",-->
<!-- "thread": "%thread",-->
<!-- "class": "%logger{40}",-->
<!-- "rest": "%message"-->
<!-- }-->
<!-- </pattern>-->
<!-- </pattern>-->
<!-- </providers>-->
<!-- </encoder>-->
<!-- </appender>-->
​
<root level="INFO">
<appender-ref ref="console"/>
<appender-ref ref="flatfile"/>
<!-- uncomment this to have also JSON logs -->
<!-- <appender-ref ref="logstash"/>-->
</root>
</configuration>
\ No newline at end of file \ No newline at end of file
#!/bin/bash
cd `dirname $0`
./stop.sh
if [ ! $? -eq 2 ];then
./start.sh
fi
\ No newline at end of file \ No newline at end of file
#!/bin/bash
cd `dirname $0`
if [ "$1" = "start" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV
else
if [ "$1" = "stop" ]; then
./stop.sh
else
if [ "$1" = "debug" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV debug
else
if [ "$1" = "restart" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./restart.sh $ENV
else
if [ "$1" = "dump" ]; then
./dump.sh
else
echo "ERROR: Please input argument: start or stop or debug or restart or dump"
exit 1
fi
fi
fi
fi
fi
#!/bin/bash
####################################
# #
# General shell v1.0.0.1 #
# #
# #
####################################
###########init variable#############
JAVA_HOME="/app/soft/jdk1.8.0_144"
SERVER_PORT="8820"
DUBBO_PORT=""
JMX_ARG="-Xmx1024m -Xms512m -Xmn256m"
MAIN="cn.com.glsx.Application"
SERVER_NAME="rest-admin"
###########end#######################
PID_DIR="/app/soft/java_project/pids"
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
if [ -d "classes" ];then
CONF_DIR="$(pwd)/classes"
LIB_DIR="$(pwd)/lib"
elif [ -d "conf" ];then
CONF_DIR="$(pwd)/conf"
LIB_DIR="$(pwd)/lib"
fi
LIB_JARS=`ls $LIB_DIR|grep .jar|awk '{print "'$LIB_DIR'/"$0}'|tr "\n" ":"`
export CLASSPATH=$CONF_DIR:$LIB_JARS
if [ -z "$CONF_DIR" ];then
echo "Configure dir not found"
exit 1
fi
PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
if [ -n "$PIDS" ]; then
echo "ERROR: The app is already started!"
echo "PID: $PIDS"
exit 1
fi
if [ ! -d "$PID_DIR" ];then
mkdir -p $PID_DIR
fi
CHECK_PORT=$2
if [ -n "$SERVER_PORT" ];then
SERVER_PORT_COUNT=`netstat -tln | grep -w $SERVER_PORT | wc -l`
if [ $SERVER_PORT_COUNT -gt 0 ]; then
echo "ERROR: The port $SERVER_PORT is already used!"
exit 1
fi
fi
if [ -n "$DUBBO_PORT" ];then
DUBBO_PORT_COUNT=`netstat -tln | grep -w $DUBBO_PORT | wc -l`
if [ $DUBBO_PORT_COUNT -gt 0 ]; then
echo "ERROR: The port $DUBBO_PORT already used!"
exit 1
fi
fi
if [[ -z "$SERVER_PORT" && -z "$DUBBO_PORT" ]];then
CHECK_PORT="skip"
fi
LOG_FILE="/data/java_log/jetty/${SERVER_NAME}/${SERVER_NAME}.log"
LOG_DIR=`dirname $LOG_FILE`
if [ ! -d $LOG_DIR ];then
mkdir -p $LOG_DIR
fi
############java args #######
#JAVA_OPTS="$PINPOINT -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true -Ddubbo.registry.file=/home/jdkapp/.dubbo/${SERVER_NAME}.cache"
JAVA_OPTS="$PINPOINT -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true"
#JAVA_OPTS=" -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true"
JAVA_DEBUG_OPTS=""
if [ "$2" = "debug" ]; then
JAVA_DEBUG_OPTS=" -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n "
fi
JAVA_JMX_OPTS=""
if [ "$2" = "jmx" ]; then
JAVA_JMX_OPTS=" -Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false "
fi
BITS=`file $JAVA_HOME/bin/java | grep 64-bit`
if [ -n "$BITS" ]; then
if [ -n "$JMX_ARG" ];then
JAVA_MEM_OPTS="-server $JMX_ARG -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70"
else
JAVA_MEM_OPTS=" -server -Xmx1g -Xms1g -Xmn256m -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 "
fi
else
JAVA_MEM_OPTS=" -server -Xms1024m -Xmx1024m -XX:PermSize=128m -XX:SurvivorRatio=2 -XX:+UseParallelGC "
fi
echo -e "Starting $SERVER_NAME \c"
nohup $JAVA_HOME/bin/java $JAVA_OPTS $JAVA_MEM_OPTS $JAVA_DEBUG_OPTS $JAVA_JMX_OPTS -DCLASS_DIR=$CONF_DIR:$LIB_DIR $MAIN > /dev/null 2>&1 &
PIDS=$!
if [ "$CHECK_PORT" != "skip" ];then
COUNT=0
ERROR=0
TIME_OUT=60
ctime=`date +"%s"`
while [ $COUNT -lt 1 ]; do
ctime2=`date +"%s"`
echo -e ".\c"
sleep 1
#PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" | awk '{print $2}'`
RESULT=`ps --no-heading -p $PIDS`
if [ -n "$RESULT" ];then
if [ -n "$DUBBO_PORT" ]; then
#COUNT=`echo status | nc 127.0.0.1 $DUBBO_PORT -i 1 | grep -c OK`
COUNT=`/usr/sbin/ss -lpn | grep "${DUBBO_PORT}.*$PIDS" | wc -l`
else
if [ -n "$SERVER_PORT" ]; then
#COUNT=`netstat -ntl | grep -w $SERVER_PORT | wc -l`
COUNT=`/usr/sbin/ss -lpn | grep "${SERVER_PORT}.*$PIDS" | wc -l`
fi
fi
if [ $COUNT -gt 0 ]; then
echo $PIDS > $PID_DIR/${SERVER_NAME}.pid
break
fi
dtime=$((ctime2 - ctime))
if [ "$dtime" -ge "$TIME_OUT" ];then
echo $PIDS > $PID_DIR/${SERVER_NAME}.pid
echo -e "\ncheck port status timeout"
exit 1
fi
else
ERROR=$((ERROR + 1))
if [ "$ERROR" -gt 3 ];then
echo -e "\nProgram startup failed"
exit 2
fi
fi
done
fi
#服务检测与注册
if [[ "x$SERVER_PORT" != "x" && -f ./bin/check.sh ]]
then
./bin/check.sh $SERVER_NAME $SERVER_PORT $PIDS &
fi
echo "PID: $PIDS"
echo "LOGFILE: $LOG_FILE"
\ No newline at end of file \ No newline at end of file
#!/bin/bash
####################################
# #
# General shell v1.0.0.1 #
# #
# #
####################################
SERVER_NAME="rest-admin"
PID_DIR="/app/soft/java_project/pids"
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
if [ -d "classes" ];then
CONF_DIR="$(pwd)/classes"
elif [ -d "conf" ];then
CONF_DIR="$(pwd)/conf"
fi
#if [ -f "$PID_DIR/${SERVER_NAME}.pid" ];then
# PID=`cat $PID_DIR/${SERVER_NAME}.pid`
#else
PID=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
#fi
if [ -z "$PID" ];then
echo "The program is not running"
exit 1
fi
pcount=`ps --no-heading -p $PID | wc -l`
if [ "$pcount" -ne 1 ];then
echo "ERROR: $SERVER_NAME does not started!"
exit 1
fi
echo -e "Stopping $SERVER_NAME ...\c"
kill $PID > /dev/null 2>&1
COUNT=0
ctime=`date +"%s"`
while [ $COUNT -lt 1 ]; do
echo -e ".\c"
sleep 1
COUNT=1
PID_EXIST=`ps --no-heading -p $PID`
if [ -n "$PID_EXIST" ]; then
ctime2=`date +"%s"`
dtime=$((ctime2 - ctime))
if [ "$dtime" -ge 10 ];then
echo -e "\nstop program timeout, use kill -9 $PID"
kill -9 $PID >/dev/null 2>&1
if [ ! $? -eq 0 ];then
echo "No permissions"
exit 2
else
rm -rf $PID_DIR/${SERVER_NAME}.pid
fi
fi
COUNT=0
continue
fi
done
echo "OK!"
rm -rf $PID_DIR/${SERVER_NAME}.pid
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.auth.modules;
public class Test {
public static void main(String[] args) {
System.out.println(System.currentTimeMillis());
}
}
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfiguration PUBLIC
"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>
<!--classPathEntry:数据库的JDBC驱动,换成你自己的驱动位置 可选 -->
<!-- <classPathEntry location="F://jdbc//mysql-connector-java-8.0.18.jar"/>-->
<!-- 一个数据库一个context -->
<context id="DB2Tables" targetRuntime="Mybatis3">
<!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表;一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖 -->
<property name="autoDelimitKeywords" value="true"/>
<!-- 生成的Java文件的编码 -->
<property name="javaFileEncoding" value="utf-8"/>
<!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<!-- 格式化java代码 -->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- 格式化XML代码 -->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<!-- 配置 tk.mybatis 插件 -->
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="com.glsx.plat.mybatis.mapper.CommonBaseMapper"/>
</plugin>
<!--配置生成注释信息,最多配置一个 -->
<commentGenerator>
<!-- 阻止生成注释包含时间戳 默认为false -->
<property name="suppressDate" value="true"/>
<!-- 注释是否添加数据库表的备注信息 默认为false -->
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<!-- jdbc连接-->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://192.168.3.190:3306/scrm_account_test?serverTimeZone=Shanghai&amp;useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false"
userId="dev_user"
password="df234fl">
<!--防止生成其他库同名表-->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成实体类地址 -->
<javaModelGenerator targetPackage="cn.com.glsx.auth.modules.entity" targetProject="../platform-auth-api/src/main/java">
<!-- 是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="true"/>
<!-- 从数据库返回的值去掉前后空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成mapper.xml文件存放地址 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成接口dao type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="cn.com.glsx.auth.modules.mapper" targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- table可以有多个,每个数据库中的表都可以写一个table,tableName表示要匹配的数据库表,也可以在tableName属性中通过使用%通配符来匹配所有数据库表,只有匹配的表才会自动生成文件 enableSelectByPrimaryKey相应的配置表示是否生成相应的接口 -->
<table tableName="platform_merchant" domainObjectName="PlatformMerchant" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-framework</artifactId>
<version>2.0.0-SNAPSHOT</version>
<relativePath/>
</parent>
<groupId>cn.com.glsx</groupId>
<artifactId>platform-auth-server</artifactId>
<version>1.0.0-SNAPSHOT</version>
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<description>Microservice Scaffolding project for Spring Boot</description>
<modules>
<module>platform-auth</module>
<module>platform-auth-api</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
</build>
</project>
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!