如何在 Java 中使用令牌和公钥验证 JWT 签名

Arh*_*ham 10 java jwt

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

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

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

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

Flo*_*pes 6

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

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

    // Load your public key from a file
    final PublicKey ecdsa256PublicKey = getPublicKey(...);
    final Algorithm algorithm = Algorithm.ECDSA256((ECPublicKey) ecdsa256PublicKey, null);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用相应的算法验证其签名:

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


Yog*_*ogi -3

如果您询问 JSON WebToken,您可以按照以下代码示例操作:

import javax.xml.bind.DatatypeConverter;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.Claims;

//Sample method to validate and read the JWT
private void parseJWT(String jwt) {

    //This line will throw an exception if it is not a signed JWS (as expected)
    Claims claims = Jwts.parser()         
       .setSigningKey(DatatypeConverter.parseBase64Binary(apiKey.getSecret()))
       .parseClaimsJws(jwt).getBody();
    System.out.println("ID: " + claims.getId());
    System.out.println("Subject: " + claims.getSubject());
    System.out.println("Issuer: " + claims.getIssuer());
    System.out.println("Expiration: " + claims.getExpiration());
}
Run Code Online (Sandbox Code Playgroud)

如需进一步阅读,您可以访问点击这里

  • 这不是回答用户的问题。使用密钥验证是使用 HS256 (hmac),而使用公钥验证是 RS256。 (2认同)