jjwt生成jwt token

JJWT生成token

  • jjwt 0.9.0版本
  • jjwt0.11.2版本
  • 版本区别
    • 第一个问题
    • 第二个问题
    • 第三个问题

最近在一个项目中不经意间升级了jjwt的版本(0.9.0升级到0.11.2),随之遇到了一些问题。主要问题如下:

  • 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版本

package com.example;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.DefaultClaims;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtTest {

    /**
     * 生成SecretKey
     * @param secret
     * @return
     */
    private static SecretKey generateKey(String secret) {
        byte[] encodedKey = Base64.decodeBase64(secret);
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }

    /**
     * 新生成token
     *
     * @param clientId
     * @param exp
     * @return
     * @throws IOException
     */
    public static String createToken(String clientId, Long exp) throws IOException {
        Claims claims = new DefaultClaims();

        // milliseconds是毫秒  1000毫秒=1秒
        long expVal = System.currentTimeMillis() + exp*1000;

        claims.setExpiration(new Date(expVal));

        try {
            claims.setSubject(clientId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String compactJws = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS256, generateKey("jinan_20220511"))
                .compact();

        return compactJws;
    }

    public static void main( String[] args )
    {
        try {
            String token = createToken("18605318888", 15*24*60*60L);
            System.out.println(token);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

jjwt0.11.2版本

package com.example;

import com.google.gson.Gson;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.gson.io.GsonSerializer;
import io.jsonwebtoken.impl.DefaultClaims;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.util.Date;

public class JwtTest11 {

    /**
     * 生成SecretKey
     * @param secret
     * @return
     */
    private static SecretKey generateKey(String secret) {
        byte[] encodedKey = Base64.decodeBase64(secret);
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "HmacSHA256");
    }

    /**
     * 新生成token
     *
     * @param clientId
     * @param exp
     * @return
     * @throws IOException
     */
    public static String createToken(String clientId, Long exp) throws IOException {
        Claims claims = new DefaultClaims();

        // milliseconds是毫秒  1000毫秒=1秒
        long expVal = System.currentTimeMillis() + exp*1000;

        claims.setExpiration(new Date(expVal));

        try {
            claims.setSubject(clientId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String compactJws = Jwts.builder()
                .setClaims(claims)
                .signWith(generateKey("jinan_20220511jinan_20220511jinan_20220511jinan_20220511"), SignatureAlgorithm.HS256)
                .serializeToJsonWith(new GsonSerializer<>(new Gson()))
                .compact();

        return compactJws;
    }

    public static void main( String[] args )
    {
        try {
            String token = createToken("18605318888", 15*24*60*60L);
            System.out.println(token);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

版本区别

第一个问题

The signing key’s algorithm ‘AES’ does not equal a valid HmacSHA* algorithm name and cannot be used with HS256

    // 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");
    }

AES改为HmacSHA256

第二个问题

The signing key’s size is 16 bits which is not secure enough for the HS256 algorithm.

// 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("jinan_20220511jinan_20220511jinan_20220511jinan_20220511"), SignatureAlgorithm.HS256)
                .serializeToJsonWith(new GsonSerializer<>(new Gson()))
                .compact();

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

第三个问题

Unable to find an implementation for interface io.jsonwebtoken.io.Serializer using java.util.ServiceLoader.
代码参考第二个问题。

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

    <dependency>
        <groupId>io.jsonwebtokengroupId>
        <artifactId>jjwt-gsonartifactId>
        <version>0.11.2version>
    dependency>
String compactJws = Jwts.builder()
                .setClaims(claims)
                .signWith(generateKey("jinan_20220511jinan_20220511jinan_20220511jinan_20220511"), SignatureAlgorithm.HS256)
                // 添加序列化相关
                .serializeToJsonWith(new GsonSerializer<>(new Gson()))
                .compact();

你可能感兴趣的:(JAVA,java)