Search code examples
javaoauthjwt

How to verify and decode a jwt oauth token in java?


I get a JWT token from google, but I can't find out how to verify and decode this.

I am trying to use the library com.auth0.jwt.JWT, and I have this code:

public static void main(String[] args) throws ServerFailException, IOException, GeneralSecurityException {
    System.out.println("Starting now");

    String publicKey="885016258715-j50dd8tkkee3ttqaqer14s4vd9fvbtbd.apps.googleusercontent.com";
    String token="eyJhbGciOiJSUz..."
    
    RSAPrivateKey privateKey=null; // This should be null, because we don't need the private key to decode the token.
    RSAPublicKey pubKey=How do I convert My string public key to a RSAPublicKey.
    
    Algorithm algorithm = Algorithm.RSA256(pubKey, privateKey);
    JWTVerifier verifier = JWT.require(algorithm)
            .withIssuer("auth0")
            .build();

    DecodedJWT decodedJWT=verifier.verify(token);
    Map<String, Claim> claims = decodedJWT.getClaims();
    System.out.println(claims);
    System.out.println("Done");
}

But the probelm is how I get the RSAPublicKey from the public key string, I got from google. Or Is there a fundamental better way to do this? (A different library).


Solution

  • I don't think it's possible to convert that string to an RSA public key. What you usually do in this scenario is to call a JWKS endpoint exposed by Google, where you would have the key in a format similar to this:

    {
        "kty":"RSA",
        "kid":"2091097665",
        "use":"sig",
        "alg":"RS256",
        "n":"nuR5CoNGpJCFRVDQyitG_0oX8d_O1f4QWT5M_ZHoS_XXjJ2ZGCDwukArnyBfEiXmzS4sEITFHmR6eS_y4fIDjkQxlH8wrhEL8enPe6Qs2qNphACydaDyvBurSEuH73JqU7hiXvge6DMONwlv0zhzqYOG4_SFiH8Qxk4gewmTFmw-ib5u-yuXTAKckYIRpQAnLTDAm1HK-MUQWZTALi1QVcpjh-afsGR42GlgWNcGip7UuPv_4YoIVj0G-6HTpdCj1SrV1dkxGPOYxFeJ96-9EWRJ6mJt0r1J9u-A1Yp9Le_FPdR6nhN7N4CzZYoG8lwdXXPeDmV8LD8PHW-SpoyPzw",
        "e":"AQAB",
        "x5t":"OjVeMZFPa9LLP0pyd4Z_dN5-Iis"
    }
    

    Alternatively, you could get the key in a PEM format, where it would look something like this:

    -----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyemE1zfNxurz773Igh8r
    cbXaqeIiKcoOYkcKyx5CYb01A69mDkOD6L6dIva9gAI2abyp3PCNKCCsCECgxAnn
    eAzzNad+I5y02SdxWo17yR1/KmkpSAB7bbqwSeG3gJ3aUfgSIWr47kama3R2epm+
    50G6zFrI8GK5Sy5J1qVXbdsMXLMWiEjCMQv5BUp/e4k/nLnyOvUkALGaqIc7BdJb
    LznNehxLv2xysS5T0gjQ0yknr/QaSqV6rZpCv08uIuO+uC6jKyZUUSxcW5eokco6
    LnoLkTBwnhg8ztERp1QU3RVWBUxAgs+xhNsarySrpoePOEpoaLSIAwLT8xAQLVOo
    xwIDAQAB
    -----END PUBLIC KEY-----
    

    Once you have the key in one of these formats, it should be straightforward to import it to the library. (It might be event that the constructor method accepts one of these formats.)