【问题标题】:Why does my code skip the try statement and go directly to the catch?为什么我的代码会跳过try语句直接进入catch?
【发布时间】:2020-05-15 12:50:47
【问题描述】:

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

jwtbuilder.com with desired header, payload and signature

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

Output of code

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
            }

        }


    }

【问题讨论】:

  • 注意:此主题始于 YouTube 评论:youtube.com/…
  • 您的 catch 块正在阻止打印堆栈跟踪。您可以删除 try/catch 块,您将看到完整的异常(并获得非零退出状态)

标签: jjwt


【解决方案1】:

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

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

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

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

另一个是:

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

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

【讨论】:

    猜你喜欢
    • 2017-09-11
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    相关资源
    最近更新 更多