How to verify JWT signature using a token and publ

2019-05-07 15:41发布

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.

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();

标签: java jwt
2条回答
戒情不戒烟
2楼-- · 2019-05-07 16:06

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

  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);
    
  2. 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);
    
查看更多
Lonely孤独者°
3楼-- · 2019-05-07 16:12

If you ask about JSON WebToken, You can follow below code sample:

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());
}

For further reading, you can visit Click here

查看更多
登录 后发表回答