【JWT】Java生成token使用python或其他语言解析失败解决方案
我使用的java jwt库如下:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
python jwt库如下:
Name: PyJWT
Version: 2.8.0
Summary: JSON Web Token implementation in Python
Home-page: https://github.com/jpadilla/pyjwt
Author: Jose Padilla
Author-email: hello@jpadilla.com
在secret相同的情况下,出现java生成的token、python无法解析。
分析源码发现,jsonwebtoken对密钥进行了base64的decode:
public JwtBuilder signWith(SignatureAlgorithm alg, String base64EncodedSecretKey) {
Assert.hasText(base64EncodedSecretKey, "base64-encoded secret key cannot be null or empty.");
Assert.isTrue(alg.isHmac(), "Base64-encoded key bytes may only be specified for HMAC signatures. If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead.");
byte[] bytes = TextCodec.BASE64.decode(base64EncodedSecretKey);
return this.signWith(alg, bytes);
}
解决办法:
python对secret也decode一下就好了:
JWT_SK = base64.b64decode('your secret')
或者java方面妥协,加密前对密钥处理, 就不写代码了。