首页 > 解决方案 > 为什么我的代码会跳过try语句直接进入catch?

问题描述

我正在尝试解码用户输入的 JWT 令牌字符串并验证签名,我正在使用 io.jsonwebtoken 库。我通过在终端中使用“openssl rand -base64 32”命令获得了“密钥”。我目前正在使用“ http://jwtbuilder.jamiekurtz.com ”来计算标头和有效负载。然后我在 jwtbuilder 网站的 Key 字段中输入我的“密钥”,如下面链接中的图片所示:

jwtbuilder.com 具有所需的标头、有效负载和签名

这是我运行代码时的输出:

代码输出

package com.okta.developer;

    import io.jsonwebtoken.*;
    import io.jsonwebtoken.security.Keys;

    import java.util.Base64;
    import java.util.Scanner;

    public class JWTexercise
    {
        public static void main(String [] args)
        {
            Scanner input = new Scanner(System.in);

            byte[] key = Base64.getDecoder().decode("b8SwFJZVgo+S5Cuhf5LWUeXpHxDm5mp30GCuQHX2TpY=");

            System.out.println("Enter your JWT token: ");
            String jwtString = input.nextLine();

            Jws<Claims> jws;

            try
            {
              // we can safely trust the JWT

                jws = Jwts.parser()         // (1)
                      .setSigningKey(Keys.hmacShaKeyFor(key))        // (2)
                      .parseClaimsJws(jwtString); // (3)

                System.out.println("The decoded JWT token id listed below:");
                System.out.println(jws);
                System.out.println();
                System.out.println("The signature is verified!");

            }
            catch (JwtException ex)
            {    
                System.out.println("Cannot trust JWT because the signature is not verified!");
                // we *cannot* use the JWT as intended by its creator
            }

        }


    }

标签: jjwt

解决方案


我的猜测是,您用于创建令牌的密钥在验证令牌时并不相同。

openssl rand -base64 32 应该创建一个随机密钥,但这些字符不太可能是可打印的。它看起来像http://jwtbuilder.jamiekurtz.com/使用直接输入文本字段的密钥,而不是首先对其进行 base 64 解码。我从来没有使用过那个网站,所以这只是一个猜测。

这实质上意味着其中一个关键是:

byte[] key = Base64.getDecoder().decode("b8SwFJZVgo+S5Cuhf5LWUeXpHxDm5mp30GCuQHX2TpY=");

另一个是:

byte[] key = "b8SwFJZVgo+S5Cuhf5LWUeXpHxDm5mp30GCuQHX2TpY=".getBytes()

第一个选项是一个更好的做法,但我猜当你这个网站时,你会想要使用第二个选项。


推荐阅读