【问题标题】:how to set expire of jwt when using jjwt使用jjwt时如何设置jwt的过期时间
【发布时间】:2021-06-17 11:35:02
【问题描述】:

现在我正在使用此代码生成 JWT 令牌并在我的项目中设置过期时间:

SecretKey secretKey = new SecretKeySpec(jwtSignKey.getBytes(), SignatureAlgorithm.HS256.getJcaName());
        JwtPayload jwtPayload = new JwtPayload();
        jwtPayload.setUserId(user.getId());
        jwtPayload.setDeviceId(request.getDeviceId());
        jwtPayload.setAppId(Long.valueOf(request.getApp().getKey()));
        byte[] bytesEncoded = Base64.encodeBase64(JSON.toJSONString(jwtPayload).getBytes());
        String accessToken = Jwts.builder().setPayload(new String(bytesEncoded))
                .setExpiration(new Date(System.currentTimeMillis() + 30*1000))
                .signWith(secretKey).compact();

但它告诉我:

Both 'payload' and 'claims' cannot both be specified. Choose either one.

那么我应该怎么做才能使用令牌设置过期时间?

【问题讨论】:

    标签: java jwt


    【解决方案1】:

    根据this,Payload 必须是纯文本(非 JSON)字符串。您可以尝试对该值进行 base64 编码,或者可能通过Jwts.claims() 创建一个声明

    你能详细说明你的目标是什么吗?

    【讨论】:

    • 我想生成一个访问令牌并设置这个令牌的过期时间。@Dave G
    【解决方案2】:

    playload 和 claim 应该选择其中之一,setExpiration 属于 claim,所以只需像这样调整代码:

     public static String generateAccessToken(String jwtSignKey, JwtPayload jwtPayload) {
            SecretKey secretKey = new SecretKeySpec(jwtSignKey.getBytes(), SignatureAlgorithm.HS256.getJcaName());
            ObjectMapper objectMapper = new ObjectMapper();
            Map claims = objectMapper.convertValue(jwtPayload, Map.class);
            String accessToken = Jwts.builder().setClaims(claims)
                    .setExpiration(new Date(System.currentTimeMillis() + 30 * 1000))
                    .signWith(secretKey).compact();
            return accessToken;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-29
      • 2015-12-13
      • 2016-11-13
      • 2017-02-15
      • 2020-11-08
      • 2018-10-18
      • 2020-08-18
      • 2016-08-08
      相关资源
      最近更新 更多