【发布时间】:2017-11-22 05:48:54
【问题描述】:
我使用这个库 Aut0 Java JWT 为我使用 Spring 框架的 REST API 实现了 JSON Web 令牌。
这里是代码
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 就安全吗?我应该使用到期日期吗?
【问题讨论】:
-
定义“安全”。即,您试图保护哪种威胁模型?
-
这将是一个公共应用程序,因此可能的威胁是人们能够根据电子邮件地址(某些用户公开)生成令牌。如果我必须重新提出问题,我会说“我对库的使用是否正确,SHA256 是否牢不可破?”
-
令牌加密只适用于知道密钥的人。您的标头和正文将使用 base64 加密,并且可以很容易地解密。 Jwt 不是加密数据的方法,它是基于 header + body + secret_key 创建一些签名进行验证