Browse Source

增加 JWT 工具

wuheng 1 năm trước cách đây
mục cha
commit
b8f06d3a18

+ 5 - 0
common/src/main/java/com/koobietech/eas/common/constant/Gender.java

@@ -0,0 +1,5 @@
+package com.koobietech.eas.common.constant;
+
+public enum Gender {
+    MALE, FEMALE
+}

+ 10 - 0
common/src/main/java/com/koobietech/eas/common/pojo/JwtUserDto.java

@@ -0,0 +1,10 @@
+package com.koobietech.eas.common.pojo;
+
+import lombok.Data;
+
+@Data
+public class JwtUserDto {
+    String username;
+    Long id;
+    Enum type;
+}

+ 39 - 0
common/src/main/java/com/koobietech/eas/common/utils/JwtManager.java

@@ -1,5 +1,44 @@
 package com.koobietech.eas.common.utils;
 
+import com.auth0.jwt.JWT;
+import com.auth0.jwt.algorithms.Algorithm;
+import com.auth0.jwt.exceptions.JWTVerificationException;
+import com.auth0.jwt.interfaces.DecodedJWT;
+import com.auth0.jwt.interfaces.JWTVerifier;
+import com.koobietech.eas.common.constant.Gender;
+import com.koobietech.eas.common.exception.EasException;
+import com.koobietech.eas.common.pojo.JwtUserDto;
+import org.springframework.beans.factory.annotation.Value;
+
+import java.util.Calendar;
+
 public class JwtManager {
 
+    @Value("${eas.jwt-secret-key}")
+    private String SECRET;
+
+    public String createJwt(JwtUserDto userDto){
+        Calendar calendar = Calendar.getInstance();
+        String sign = JWT.create()
+                .withClaim("user", userDto.getUsername())
+                .withClaim("id", userDto.getId())
+                .withClaim("type", userDto.getType().toString())
+                .withExpiresAt( calendar.getTime() )
+                .sign(Algorithm.HMAC256(SECRET));
+        return sign;
+    }
+    public JwtUserDto decodeJwt(String token){
+        JwtUserDto jwtUserDto = new JwtUserDto();
+        JWTVerifier build = JWT.require(Algorithm.HMAC256(SECRET)).build();
+        try {
+            DecodedJWT verify = build.verify(token);
+            jwtUserDto.setId(verify.getClaim("id").asLong());
+            jwtUserDto.setUsername(verify.getClaim("user").asString());
+            jwtUserDto.setType(Gender.valueOf(verify.getClaim("type").asString()));
+        } catch ( JWTVerificationException e){
+            throw new EasException("token 不正确!");
+        }
+        return jwtUserDto;
+    }
+
 }

+ 1 - 0
controller/src/main/resources/application.yaml

@@ -15,4 +15,5 @@ security:
       - /test
 
 eas:
+  jwt-secret-key: 123456
   password-sign-key: eas-key-password