public class JwtUtil {
private static Algorithm algorithm;
static {
try {
algorithm = Algorithm.HMAC512(KeyGenerator.getInstance("HmacSHA512").generateKey().getEncoded());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public static String create(String username) {
Date now = new Date();
return JWT.create()
.withIssuedAt(now)
.withClaim("username", username)
.withExpiresAt(new Date(now.getTime() + 60000*60))
.sign(algorithm);
}
public static String verify(String token) {
return JWT.require(algorithm).build()
.verify(token)
.getClaim("username")
.asString();
}
}
上面是 jwt 的生成和验证的类
public class TestToken {
public static void main(String[] args) {
String token = JwtUtil.create("123");
System.out.println(token);
System.out.println(JwtUtil.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1NzM4MTU2MzYsImlhdCI6MTU3MzgxMjAzNiwidXNlcm5hbWUiOiIxMjMifQ.4xIgdDx44A_4vdebICw-FmzxMqw5R48OODJ7HPst4rEe-4k2ob1cKat2CKqw7VSTsKAEBl1abxv6EpBU5AhIwg"));
}
}
问题:当我把获得的 token 手动填入到这个测试类里的时候,就是给我报一个错 com.auth0.jwt.exceptions.SignatureVerificationException: The Token's Signature resulted invalid when verified using the Algorithm: HmacSHA512,但是如果我直接写成JwtUtil.verify(token)
,一切就 ok,请问这是为什么?(手动填入的 token 是正确的,未过期的)
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.