我使用了这个库Auth0 Java JWT来实现我的REST API的JSON Web Tokens,该API使用了Spring Framework。
以下是代码:
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.io.UnsupportedEncodingException;
public class JWTutils {
private final static String secret = "fj32Jfv02Mq33g0f8ioDkw";
public static String createToken(String email)
{
try {
return JWT.create()
.withIssuer("auth0")
.withClaim("email", email)
.sign(Algorithm.HMAC256(secret));
} catch (JWTCreationException exception){
throw new RuntimeException("You need to enable Algorithm.HMAC256");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage());
}
}
public static String getEmailInToken(String token)
{
try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret))
.withIssuer("auth0")
.build();
DecodedJWT jwt = verifier.verify(token);
return jwt.getClaim("email").asString();
} catch (JWTDecodeException exception){
return null;
} catch (UnsupportedEncodingException e) {
return null;
}
}
}
只要使用HTTPS,我的JWT就是安全的吗?我应该使用过期日期吗?