Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify JWT signature using a token and public key in Java

Tags:

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.

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();
like image 494
Arham Avatar asked Jul 31 '17 11:07

Arham


People also ask

Can you verify JWT with public key?

The jwt token is signed using private key. The auth server provides the public key publicly on a url in the form of JSON Web Key Set(JWKS). During verification the public keys are fetched.

Can you verify a JWT without knowing the secret?

There are two ways in which a public/private keys can be used by a JWT: signing and encryption. If you use a private key for signing, it allows for the recipient to identify the sender of the JWT and the integrity of the message but not to hide its contents from others (confidentiality).

What is public key in JWT token?

The JSON Web Key Set (JWKS) is a set of keys containing the public keys used to verify any JSON Web Token (JWT) issued by the authorization server and signed using the RS256 signing algorithm. When creating applications and APIs in Auth0, two algorithms are supported for signing JWTs: RS256 and HS256.


1 Answers

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.

like image 172
Abhishek Chandran Avatar answered Sep 21 '22 19:09

Abhishek Chandran