|
|
@@ -0,0 +1,93 @@
|
|
|
+package com.leanwo.gateway.service;
|
|
|
+
|
|
|
+import java.util.Date;
|
|
|
+import java.util.UUID;
|
|
|
+
|
|
|
+import org.slf4j.Logger;
|
|
|
+import org.slf4j.LoggerFactory;
|
|
|
+import org.springframework.beans.factory.annotation.Value;
|
|
|
+import org.springframework.context.annotation.Configuration;
|
|
|
+
|
|
|
+import com.auth0.jwt.JWT;
|
|
|
+import com.auth0.jwt.algorithms.Algorithm;
|
|
|
+import com.auth0.jwt.exceptions.JWTCreationException;
|
|
|
+import com.leanwo.gateway.exception.TokenException;
|
|
|
+
|
|
|
+@Configuration
|
|
|
+public class TokenServiceImpl implements TokenService {
|
|
|
+
|
|
|
+ private static Logger logger = LoggerFactory.getLogger(TokenServiceImpl.class);
|
|
|
+
|
|
|
+ /** The regist overtime ms. */
|
|
|
+ // 注册超时时间
|
|
|
+ private static long REGIST_OVERTIME_MS = (long)(30 * 1000);
|
|
|
+
|
|
|
+ /** The token secret. */
|
|
|
+ // 密钥
|
|
|
+ @Value("${server.token.secret}")
|
|
|
+ private String tokenSecret;
|
|
|
+
|
|
|
+ /** The token issuer. */
|
|
|
+ // 密钥
|
|
|
+ @Value("${server.token.issuer}")
|
|
|
+ private String tokenIssuer;
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public String generateTempToken() {
|
|
|
+ long currentMs = new Date().getTime();
|
|
|
+ Date expireDate = new Date(currentMs + REGIST_OVERTIME_MS);
|
|
|
+ Date notBeforeDate = new Date(currentMs + 3 * 1000);
|
|
|
+ String tokenString = null;
|
|
|
+ // Create and Sign a Token
|
|
|
+ try {
|
|
|
+ Algorithm algorithm = Algorithm.HMAC256(tokenSecret);
|
|
|
+ tokenString = JWT.create().withIssuer(tokenIssuer) // 签发者
|
|
|
+ .withExpiresAt(expireDate) // 过期时间
|
|
|
+ .withIssuedAt(new Date()) // 签发时间
|
|
|
+ // .withNotBefore(notBeforeDate) // 下次可访问的时间
|
|
|
+ .withClaim("uuid", UUID.randomUUID().toString()).sign(algorithm);
|
|
|
+ } catch (JWTCreationException exception) {
|
|
|
+ logger.error("JWT Token生成失败.", exception);
|
|
|
+ throw new TokenException("JWT Token生成失败.");
|
|
|
+ }
|
|
|
+ return tokenString;
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ /**
|
|
|
+ * Gets the token 密钥.
|
|
|
+ *
|
|
|
+ * @return the token 密钥
|
|
|
+ */
|
|
|
+ public String getTokenSecret() {
|
|
|
+ return tokenSecret;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * Sets the token 密钥.
|
|
|
+ *
|
|
|
+ * @param tokenSecret the new token 密钥
|
|
|
+ */
|
|
|
+ public void setTokenSecret(String tokenSecret) {
|
|
|
+ this.tokenSecret = tokenSecret;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * Gets the token 授权单位.
|
|
|
+ *
|
|
|
+ * @return the token 授权单位
|
|
|
+ */
|
|
|
+ public String getTokenIssuer() {
|
|
|
+ return tokenIssuer;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * Sets the token 授权单位.
|
|
|
+ *
|
|
|
+ * @param tokenIssuer the new token 授权单位
|
|
|
+ */
|
|
|
+ public void setTokenIssuer(String tokenIssuer) {
|
|
|
+ this.tokenIssuer = tokenIssuer;
|
|
|
+ }
|
|
|
+
|
|
|
+}
|