|
@@ -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;
|
|
|
+ }
|
|
|
+
|
|
|
}
|