如何使用Java中的标记和公钥验证JWT签名 [英] How to verify JWT signature using a token and public key in Java

查看:1606
本文介绍了如何使用Java中的标记和公钥验证JWT签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串形式的令牌,我下载了公共证书并从中创建了一个公钥,如下所示。

I have a token in the form of a string and I downloaded the public cert and created a public key out of it as follows.

但我不是确定如何使用这么多信息进行验证。

But I'm not sure how proceed for verification with just this much info.

我找到了C#和.NET的解决方案,但没有找到Java的解决方案。
请注意我没有jks文件或私钥。

I found solutions for C# and .NET but not for Java. Please note I don't have the jks file or private key.

    FileInputStream fin = new FileInputStream("d://public.crt");
    CertificateFactory f = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate)f.generateCertificate(fin);
    PublicKey pk = certificate.getPublicKey();


推荐答案

使用Auth0库验证Java中的JWT(com .auth0:java-jwt):

To verify a JWT in Java using Auth0 library (com.auth0:java-jwt):


  1. 检索密钥已签名的算法,例如:

  1. Retrieve the algorithm the key has been signed with, for example:

// Load your public key from a file
final PublicKey ecdsa256PublicKey = getPublicKey(...);
final Algorithm algorithm = Algorithm.ECDSA256((ECPublicKey) ecdsa256PublicKey, null);


  • 使用相应的算法验证其签名:

  • Verify its signature using the corresponding algorithm:

    final DecodedJWT decodedJWT = JWT.decode("J.W.T[...]");
    // Will throw a SignatureVerificationException if the token's signature is invalid
    algorithm.verify(decodedJWT);
    


  • 这篇关于如何使用Java中的标记和公钥验证JWT签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆