记一次Jwt生成 token

  • The signing key’s algorithm ‘AES’ does not equal a valid HmacSHA* algorithm name and cannot be used with HS256.
  • The signing key’s size is 16 bits which is not secure enough for the HS256 algorithm. The JWT JWA Specification (RFC 7518, Section 3.2) states that keys used with HS256 MUST have a size >= 256 bits (the key size must be greater than or equal to the hash output size). Consider using the io.jsonwebtoken.security.Keys class’s ‘secretKeyFor(SignatureAlgorithm.HS256)’ method to create a key guaranteed to be secure enough for HS256. See https://tools.ietf.org/html/rfc7518#section-3.2 for more information.
  • Unable to find an implementation for interface io.jsonwebtoken.io.Serializer using java.util.ServiceLoader. Ensure you include a backing implementation .jar in the classpath, for example jjwt-impl.jar, or your own .jar for custom implementations.
三个错误 , jjwt的版本(0.9.0升级到0.11.2)

问题一

AES 改为 HmacSHA256

// jjwt 0.9.0版本
private static SecretKey generateKey(String secret) {
    byte[] encodedKey = Base64.decodeBase64(secret);
    return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
}
// jjwt 0.11.2版本
private static SecretKey generateKey(String secret) {
    byte[] encodedKey = Base64.decodeBase64(secret);
    return new SecretKeySpec(encodedKey, 0, encodedKey.length, "HmacSHA256");
}

问题二

密钥位数不够,必须大于256位,一个字符按照8位算,至少32个字符。

// jjwt 0.9版本
String compactJws = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS256, generateKey("jinan_20220511"))
                .compact();
// jjwt 0.11.2版本
String compactJws = Jwts.builder()
                .setClaims(claims)
                .signWith(generateKey("AtanycostscodecodecodecodeAllbushpullcommit"), SignatureAlgorithm.HS256)
                .serializeToJsonWith(new GsonSerializer<>(new Gson()))
                .compact();

问题三

没找到序列化的实现,添加序列化相关依赖和代码。

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-gson</artifactId>
    <version>0.11.2</version>
</dependency>
String compactJws = Jwts.builder()
                .setClaims(claims)
                .signWith(generateKey("AtanycostscodecodecodecodeAllbushpullcommit"), SignatureAlgorithm.HS256)
                // 添加序列化相关
                .serializeToJsonWith(new GsonSerializer<>(new Gson()))
                .compact();
最后修改:2023 年 05 月 04 日
如果觉得我的文章对你有用,请随意赞赏