jjwt生成jwt token

最近在一个项目中不经意间升级了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.jsonwebtoken</groupId>
        <artifactId>jjwt-gson</artifactId>
        <version>0.11.2</version>
    </dependency>
String compactJws = Jwts.builder()
                .setClaims(claims)
                .signWith(generateKey("jinan_20220511jinan_20220511jinan_20220511jinan_20220511"), SignatureAlgorithm.HS256)
                // 添加序列化相关
                .serializeToJsonWith(new GsonSerializer<>(new Gson()))
                .compact();
  • 11
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
生成token的一种方式是使用JWTJSON Web Token)技术。JWT是一种开放标准,它定义了一种紧凑且自包含的方式来在各方之间安全地传输信息。下面是使用Java生成token的步骤: 1. 导入依赖 使用JWT需要导入以下依赖: ``` <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>0.11.2</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>0.11.2</version> <scope>runtime</scope> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> <version>0.11.2</version> <scope>runtime</scope> </dependency> ``` 2. 创建JWT ``` String secretKey = "yourSecretKey"; String shortToken = Jwts.builder() .setSubject("subject") .setExpiration(new Date(System.currentTimeMillis() + 60000)) .signWith(SignatureAlgorithm.HS512, secretKey.getBytes()) .compact(); ``` 其中,`setSubject`方法设置token主题,`setExpiration`方法设置token过期时间,`signWith`方法使用HS512算法对token进行签名,`compact`方法生成token字符串。 3. 解析JWT ``` Jws<Claims> jws = Jwts.parserBuilder() .setSigningKey(secretKey.getBytes()) .build() .parseClaimsJws(shortToken); String subject = jws.getBody().getSubject(); ``` 其中,`setSigningKey`方法设置签名密钥,`parseClaimsJws`方法解析token并返回Jws对象,`getBody`方法获取token的内容,`getSubject`方法获取token的主题。 以上就是使用Java生成token的步骤。需要注意的是,使用JWT生成token并不一定是短token,而是一种安全且可靠的token传输方式。如果要生成token,可以根据需要对生成token字符串进行截取等处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jinwen5290

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值