userName 2 weeks ago
parent
commit
b17f136c2c

+ 7 - 7
src/main/java/com/zhentao/common/user/service/impl/GooseUserServiceImpl.java

@@ -9,10 +9,10 @@ import com.zhentao.common.user.domain.GooseUser;
 import com.zhentao.common.user.dto.LoginDto;
 import com.zhentao.common.user.mapper.GooseUserMapper;
 import com.zhentao.common.user.service.GooseUserService;
+import com.zhentao.util.AppJwtUtil;
 import com.zhentao.util.HttpUtils;
 import com.zhentao.util.ResultVo;
 import com.zhentao.util.SnowflakeIdGenerator;
-import com.zhentao.util.TokenUtils;
 import lombok.SneakyThrows;
 import org.apache.http.HttpResponse;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -66,7 +66,7 @@ public class GooseUserServiceImpl extends ServiceImpl<GooseUserMapper, GooseUser
                     gooseUser1.setPassword(pwd);
                     gooseUser1.setSalt(salt);
                     userMapper.insert(gooseUser1);
-                    String token= TokenUtils.createJwtToken(gooseUser1.getId().toString());
+                    String token= AppJwtUtil.getToken(gooseUser1.getId());
                     return ResultVo.OK(token);
                 }
                 if(StringUtils.checkValNotNull(loginDto.getCode())){
@@ -76,7 +76,7 @@ public class GooseUserServiceImpl extends ServiceImpl<GooseUserMapper, GooseUser
                     String code = jedis.get("code");
                     if(loginDto.getCode().equals(code)){
                         userMapper.insert(gooseUser1);
-                        String token= TokenUtils.createJwtToken(gooseUser1.getId().toString());
+                        String token= AppJwtUtil.getToken(gooseUser1.getId());
                         return ResultVo.OK(token);
                     }
                 }
@@ -87,7 +87,7 @@ public class GooseUserServiceImpl extends ServiceImpl<GooseUserMapper, GooseUser
                 String salt= user.getSalt();
                 String pwd=DigestUtils.md5DigestAsHex((loginDto.getPassword()+salt).getBytes(StandardCharsets.UTF_8));
                 if(pwd.equals(password)){
-                    String token=TokenUtils.createJwtToken(user.getId().toString());
+                    String token=AppJwtUtil.getToken(user.getId());
                     return ResultVo.OK();
                 }
                 return ResultVo.ERROR();
@@ -96,7 +96,7 @@ public class GooseUserServiceImpl extends ServiceImpl<GooseUserMapper, GooseUser
                 Jedis jedis=new Jedis("localhost");
                 String code = jedis.get("code");
                 if(loginDto.getCode().equals(code)){
-                    String token= TokenUtils.createJwtToken(user.getId().toString());
+                    String token=AppJwtUtil.getToken(user.getId());
                     return ResultVo.OK(token);
                 }
             }
@@ -145,10 +145,10 @@ public class GooseUserServiceImpl extends ServiceImpl<GooseUserMapper, GooseUser
                 user.setOpenId(openId);
                 user.setNickname("微信用户"+ UUID.randomUUID().toString().replace("-","").substring(0,8));
                 userMapper.insert(user);
-                String token=TokenUtils.createJwtToken(user.getId().toString());
+                String token=AppJwtUtil.getToken(user.getId());
                 return new ResultVo(200,"登录成功",token);
             }
-            String token=TokenUtils.createJwtToken(gooseUser.getId().toString());
+            String token=AppJwtUtil.getToken(gooseUser.getId());
             return new ResultVo(200,"登录成功",token);
         } catch (HttpClientErrorException e) { // 处理 HTTP 错误(如 400、500)
             return new ResultVo(400,"请求微信接口失败: " + e.getResponseBodyAsString(),null);

+ 119 - 0
src/main/java/com/zhentao/util/AppJwtUtil.java

@@ -0,0 +1,119 @@
+package com.zhentao.util;
+
+import io.jsonwebtoken.*;
+
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+import java.util.*;
+
+public class AppJwtUtil {
+
+    // TOKEN的有效期一天(S)
+    private static final int TOKEN_TIME_OUT = 3_600;
+    // 加密KEY
+    private static final String TOKEN_ENCRY_KEY = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY";
+    // 最小刷新间隔(S)
+    private static final int REFRESH_TIME = 300;
+
+    // 生产ID
+    public static String getToken(Long id){
+        Map<String, Object> claimMaps = new HashMap<>();
+        claimMaps.put("id",id);
+        long currentTime = System.currentTimeMillis();
+        return Jwts.builder()
+                .setId(UUID.randomUUID().toString())
+                .setIssuedAt(new Date(currentTime))  //签发时间
+                .setSubject("system")  //说明
+                .setIssuer("") //签发者信息
+                .setAudience("app")  //接收用户
+                .compressWith(CompressionCodecs.GZIP)  //数据压缩方式
+                .signWith(SignatureAlgorithm.HS512, generalKey()) //加密方式
+                .setExpiration(new Date(currentTime + TOKEN_TIME_OUT * 1000))  //过期时间戳
+                .addClaims(claimMaps) //cla信息
+                .compact();
+    }
+
+    /**
+     * 获取token中的claims信息
+     *
+     * @param token
+     * @return
+     */
+    private static Jws<Claims> getJws(String token) {
+            return Jwts.parser()
+                    .setSigningKey(generalKey())
+                    .parseClaimsJws(token);
+    }
+
+    /**
+     * 获取payload body信息
+     *
+     * @param token
+     * @return
+     */
+    public static Claims getClaimsBody(String token) {
+        try {
+            return getJws(token).getBody();
+        }catch (ExpiredJwtException e){
+            return null;
+        }
+    }
+
+    /**
+     * 获取hearder body信息
+     *
+     * @param token
+     * @return
+     */
+    public static JwsHeader getHeaderBody(String token) {
+        return getJws(token).getHeader();
+    }
+
+    /**
+     * 是否过期
+     *
+     * @param claims
+     * @return -1:有效,0:有效,1:过期,2:过期
+     */
+    public static int verifyToken(Claims claims) {
+        if(claims==null){
+            return 1;
+        }
+        try {
+            claims.getExpiration()
+                    .before(new Date());
+            // 需要自动刷新TOKEN
+            if((claims.getExpiration().getTime()-System.currentTimeMillis())>REFRESH_TIME*1000){
+                return -1;
+            }else {
+                return 0;
+            }
+        } catch (ExpiredJwtException ex) {
+            return 1;
+        }catch (Exception e){
+            return 2;
+        }
+    }
+
+    /**
+     * 由字符串生成加密key
+     *
+     * @return
+     */
+    public static SecretKey generalKey() {
+        byte[] encodedKey = Base64.getEncoder().encode(TOKEN_ENCRY_KEY.getBytes());
+        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
+        return key;
+    }
+
+    public static void main(String[] args) {
+       /* Map map = new HashMap();
+        map.put("id","11");*/
+        System.out.println(AppJwtUtil.getToken(1102L));
+        Jws<Claims> jws = AppJwtUtil.getJws("eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAADWLQQqEMAwA_5KzhURNt_qb1KZYQSi0wi6Lf9942NsMw3zh6AVW2DYmDGl2WabkZgreCaM6VXzhFBfJMcMARTqsxIG9Z888QLui3e3Tup5Pb81013KKmVzJTGo11nf9n8v4nMUaEY73DzTabjmDAAAA.4SuqQ42IGqCgBai6qd4RaVpVxTlZIWC826QA9kLvt9d-yVUw82gU47HDaSfOzgAcloZedYNNpUcd18Ne8vvjQA");
+        Claims claims = jws.getBody();
+        System.out.println(claims.get("id"));
+
+    }
+
+}

+ 0 - 112
src/main/java/com/zhentao/util/TokenUtils.java

@@ -1,112 +0,0 @@
-package com.zhentao.util;
-
-
-import io.jsonwebtoken.Claims;
-import io.jsonwebtoken.JwtBuilder;
-import io.jsonwebtoken.Jwts;
-import io.jsonwebtoken.SignatureAlgorithm;
-
-import javax.crypto.spec.SecretKeySpec;
-import javax.xml.bind.DatatypeConverter;
-import java.security.Key;
-import java.util.Date;
-
-/**
- * 生成Token工具类
- */
-public class TokenUtils {
-
-    /**
-     * 签名秘钥
-     */
-    public static final String SECRET = "cjyfutu1688";
-
-    /**
-     * 生成token
-     * @param id 一般传入userName
-     * @return
-     */
-    public static String createJwtToken(String id){
-        String issuer = "www.futureading.com";
-        String subject = "65532781@qq.com";
-        long ttlMillis = System.currentTimeMillis();
-        return createJwtToken(id, issuer, subject, ttlMillis);
-    }
-
-    /**
-     * 生成Token
-     *
-     * @param id
-     *            编号
-     * @param issuer
-     *            该JWT的签发者,是否使用是可选的
-     * @param subject
-     *            该JWT所面向的用户,是否使用是可选的;
-     * @param ttlMillis
-     *            签发时间
-     * @return token String
-     */
-    public static String createJwtToken(String id, String issuer, String subject, long ttlMillis) {
-
-        // 签名算法 ,将对token进行签名
-        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
-
-        // 生成签发时间
-        long nowMillis = System.currentTimeMillis();
-        Date now = new Date(nowMillis);
-
-        // 通过秘钥签名JWT
-        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
-        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
-
-        // Let's set the JWT Claims
-        JwtBuilder builder = Jwts.builder().setId(id)
-                .setIssuedAt(now)
-                .setSubject(subject)
-                .setIssuer(issuer)
-                .signWith(signatureAlgorithm, signingKey);
-
-        // if it has been specified, let's add the expiration
-        if (ttlMillis >= 0) {
-            long expMillis = nowMillis + ttlMillis;
-            Date exp = new Date(expMillis);
-            builder.setExpiration(exp);
-        }
-
-        // Builds the JWT and serializes it to a compact, URL-safe string
-        return builder.compact();
-
-    }
-
-    // Sample method to validate and read the JWT
-    public static Claims parseJWT(String jwt) {
-        // This line will throw an exception if it is not a signed JWS (as expected)
-        Claims claims = Jwts.parser()
-                .setSigningKey(DatatypeConverter.parseBase64Binary(SECRET))
-                .parseClaimsJws(jwt).getBody();
-        return claims;
-    }
-
-    public static Long getUserId(String token) throws RRException {
-        Claims claims = null;
-        try {
-            claims = TokenUtils.parseJWT(token);
-        } catch (Exception e) {
-            throw new RRException("token错误,请重新登录",101);
-        }
-
-        if(null==claims) {
-            throw new RRException("token错误,请重新登录",101);
-        }
-        String id = claims.getId();
-        Long userId=Long.valueOf(id);
-
-        return userId;
-
-
-    }
-
-    public static void main(String[] args) {
-        System.out.println(TokenUtils.createJwtToken("admin"));
-    }
-}