Validate JWT Token with Public Key & RSA256 Algo – Java & Spring Boot

In this post, we’re going to see how we can validate JWT Token using a public key and RSA256 Algorithm.

I’ll demonstrate this with Java & Spring boot in the below example.

Dependencies

Other than common dependencies of Spring Boot we would need auth0 to validate JWT.

		<dependency>
			<groupId>com.auth0</groupId>
			<artifactId>java-jwt</artifactId>
			<version>4.0.0</version>
		</dependency>

Step 1: Build RSAPublicKey

By using our public key, we need to create an RSAPublic key out of it using X.509 certificate.

    private RSAPublicKey getRSAPublicKey() throws CertificateException {
        var decode = Base64.getDecoder().decode(publicKey);
        var certificate = CertificateFactory.getInstance("X.509")
                .generateCertificate(new ByteArrayInputStream(decode));
        var publicKey = (RSAPublicKey) certificate.getPublicKey();
        return publicKey;
    }

Step 2: Build JWT Verifier

Using RSAPublic key from Step1 we need to create JWTVerifier in order to verify the token.

    private JWTVerifier buildJWTVerifier() throws CertificateException {
        var algo = Algorithm.RSA256(getRSAPublicKey(), null);
        return JWT.require(algo).build();
    }

Step 3: Validate

Now, it’s time to validate the JWT token.

    public Boolean isValidToken(String token) {
            buildJWTVerifier().verify(token.replace("Bearer ", ""));
            return Boolean.TRUE;
    }
          // if token is invalid an exception will be thrown

That’s how you can validate a JWT token with public key.

Complete Solution:

package com.masterincoding.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;

@Component
@Slf4j
public class JwtVerifierUsingRSA256 {

    // please input your jwt token & public key here
    public static final String jwtToken = "";
    public static final String publicKey = "";

    public Boolean isValidToken(String token) {
        try {
            buildJWTVerifier().verify(token.replace("Bearer ", ""));
            // if token is valid no exception will be thrown
            log.info("Valid TOKEN");
            return Boolean.TRUE;
        } catch (CertificateException e) {
            //if CertificateException comes from buildJWTVerifier()
            log.info("InValid TOKEN");
            e.printStackTrace();
            return Boolean.FALSE;
        } catch (JWTVerificationException e) {
            // if JWT Token in invalid
            log.info("InValid TOKEN");
            e.printStackTrace();
            return Boolean.FALSE;
        } catch (Exception e) {
            // If any other exception comes
            log.info("InValid TOKEN, Exception Occurred");
            e.printStackTrace();
            return Boolean.FALSE;
        }
    }


    private JWTVerifier buildJWTVerifier() throws CertificateException {
        var algo = Algorithm.RSA256(getRSAPublicKey(), null);
        return JWT.require(algo).build();
    }

    private RSAPublicKey getRSAPublicKey() throws CertificateException {
        var decode = Base64.getDecoder().decode(publicKey);
        var certificate = CertificateFactory.getInstance("X.509")
                .generateCertificate(new ByteArrayInputStream(decode));
        var publicKey = (RSAPublicKey) certificate.getPublicKey();
        return publicKey;
    }
}

The same can be found here on Github

1 thought on “Validate JWT Token with Public Key & RSA256 Algo – Java & Spring Boot”

  1. Good post. I learn something new and challenging on sites I StumbleUpon every day. It’s always interesting to read articles from other authors and practice something from other sites.

    Reply

Leave a Comment