com.github.dennisit.vplus.data.security.token.JwtToken Maven / Gradle / Ivy
package com.github.dennisit.vplus.data.security.token;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.lang3.time.DateUtils;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JwtToken {
// 关键字域
public static class Fields {
public static final String USER_ID = "user_id";
public static final String PROVIDER_ID = "provider_id";
public static final String PROVIDER_USER_ID = "provider_user_id";
}
private static final String ISSUER = "user";
public static Map parser(String token, String secret) {
Algorithm algorithm;
Map map;
try {
algorithm = Algorithm.HMAC256(secret);
JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
DecodedJWT jwt = verifier.verify(token);
map = jwt.getClaims();
} catch (JWTVerificationException e) {
throw new RuntimeException("鉴权失败");
}
Map resultMap = new HashMap<>(map.size());
map.forEach((k, v) -> resultMap.put(k, v.asString()));
return resultMap;
}
public static String create(Map claims, String secret) {
return create(claims, secret, 30);
}
public static String create(Map claims, String secret, int days) {
try {
Algorithm algorithm = Algorithm.HMAC256(secret);
JWTCreator.Builder builder = JWT.create()
.withIssuer(ISSUER)
.withExpiresAt(DateUtils.addMinutes(new Date(), days));
claims.forEach(builder::withClaim);
return builder.sign(algorithm);
} catch (IllegalArgumentException | JWTCreationException e) {
throw new RuntimeException("生成token失败");
}
}
}