13

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();
Arham
  • 2,072
  • 2
  • 18
  • 30

4 Answers4

6

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);
    
Florian Lopes
  • 1,093
  • 1
  • 13
  • 20
2

I did something like this to verify JWT

try {
        DecodedJWT decodedJWT = JWT.decode(jwt); // your string
        JwkProvider provider =  new JwkProviderBuilder(new URL("JWKS URL")).build();
        Jwk jwk = provider.get(decodedJWT.getKeyId());
        Algorithm algorithm = Algorithm.RSA256((RSAPublicKey) jwk.getPublicKey(), null);

        Verification verifier = JWT.require(algorithm);
        verifier.build().verify(decodedJWT);
    } catch (JWTVerificationException | JwkException | MalformedURLException e) {
        // throw your exception
    }

JwkProviderBuilder can be expensive, so if you are using Spring, you can extract it as another method and annotate it with @PostConstruct to optimise.

Abhishek Chandran
  • 1,536
  • 1
  • 13
  • 21
0

A working example with RSA key is as given below:

/* Verification of JWT */
try {
    String token = "some-token";
    String publicKey = "some-key";
    
    //Convert public key string to RSAPublicKey
    byte[] publicKeyByteArr = Base64.getDecoder().decode(publicKey);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    RSAPublicKey rsaPublicKey = (RSAPublicKey) keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyByteArr));

    //If the token has an invalid signature, JWTVerificationException will raise.
    Algorithm algorithm = Algorithm.RSA256(rsaPublicKey, null);
    JWTVerifier verifier = JWT.require(algorithm)
                //.withIssuer("auth0")
                .build(); //Reusable verifier instance
    DecodedJWT jwt = verifier.verify(token);

}catch(InvalidKeySpecException | NoSuchAlgorithmException | JWTVerificationException e) {
    logger.info("JWT verification is failed");
    throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
}

It's obvious but please note that token and publicKey are arbitrary.

Sezerb
  • 1
  • 1
-3

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

Yogi
  • 1,805
  • 13
  • 24
  • 1
    What object is apiKey and how do I fetch it's secret given that I have only a public key cert file. – Arham Jul 31 '17 at 12:51
  • apiKey is object of com.stormpath.sdk.api.ApiKey, which is used for holding apikey. String path = "resources/.stormpath/apiKey.properties"; ApiKey apiKey = ApiKeys.builder().setFileLocation(path).build(); – Yogi Jul 31 '17 at 14:25
  • 2
    This is not answering what the user asked. Verify using secret key is using HS256 (hmac) while verifying using public key is RS256. – jumper rbk Aug 13 '18 at 02:46