<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class JWTUtil{
public static String createJWTByObj(Map<String, Object> tokenMap, String secret) throws IOException {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
SecretKey secretKey = generalKey(secret);
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = LocalDateTime.now().plusDays(3).atZone(zoneId);
JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
.setId("myApp")
.setIssuedAt(Date.from(zdt.toInstant()))
.setHeaderParam("alg", "HS256")
.addClaims(tokenMap)
.setExpiration(Date.from(zdt.toInstant()))
.signWith(signatureAlgorithm, secretKey);
return builder.compact();
}
public static VerifyResult verifyJwt(String token, String secret) {
SecretKey key = generalKey(secret);
try {
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = LocalDateTime.now().atZone(zoneId);
Jwt jwt = Jwts.parser()
.setSigningKey(key)
.parse(token);
Date date = ((Claims) jwt.getBody()).getExpiration();
if (date == null) {
return new VerifyResult(false, 5002);
}
LocalDateTime expires = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
if (expires.isBefore(LocalDateTime.now())) {
return new VerifyResult(false, 5001);
}
return new VerifyResult(true, 200);
} catch (Exception e) {
e.printStackTrace();
return new VerifyResult(false, 5002);
}
}
public static Map<String,Object> decode(String token) throws IOException {
String bodyData = token.split("\\.")[1];
String bodyStr = new String(Base64.decodeBase64(bodyData),"UTF-8");
return JSON.parseObject(bodyStr,Map.class);
}
private static SecretKey generalKey(String jwtSecret) {
String stringKey = jwtSecret;
byte[] encodedKey = Base64.decodeBase64(stringKey);
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return key;
}
@Data
public static class VerifyResult{
private boolean isValidate;
private int code;
private Map<String,Object> tokenMap;
public VerifyResult(boolean isValidate, int code) {
this.isValidate = isValidate;
this.code = code;
System.out.println("1111");
}
}
}