简体   繁体   中英

decode java google oauth2.0 JWT

Im trying to decode the google oauth token_id using the below stmts..For some reason, the claims are decoded partially...

String token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IjdkZGQwOGEwM2IyNWQwZjVhMDllMjNiMmJlMTBkZDIyODQyYTg1NjkifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTAxOTI0MjQ2MzYwNDM0OTY2NzMzIiwiYXpwIjoiNTk0OTU1MjgxODg2LWJxcjBkYm1kcmFicWFvbm1oZWlxazBza2RkZjVhbGs1LmxCLTO3GHRBn0";

        //String[] jwtParts = token.split("\\.");
        String[] base64EncodedSegments = token.split("\\.");
        System.out.println(Arrays.toString(base64EncodedSegments));
        String base64EncodedHeader = base64EncodedSegments[0];
        String base64EncodedClaims = base64EncodedSegments[1];
        byte[] claims = new byte[1000000];
        claims = DatatypeConverter.parseBase64Binary(base64EncodedClaims);
        String s = new String(claims);
        System.out.println(s);
        System.out.println(s.getClass().getName());

        JSONObject emailobject = new JSONObject(s);
        String emailid = emailobject.getString("email");
        System.out.println(emailid);

Decoded claims below:

It starts with a "{" braces but does not close with "}" and because of that I'm unable to convert to a JSON object and get the actual email id

{"iss":"accounts.google.com","sub":"101924246360434966733","azp":"594955281886-bqr0d0skddf5alk5.apps.googleusercontent.com","email":"test@gmail.com","at_hash":"dVrka2339w4Cezz32ssrY_w","email_verified":true,"aud":"594955281-bqr0dbmdrak5.apps.googleusercontent.com","iat":1423238546,"exp":1413223244

***********Update************

This piece of code works for to connect to google oauth and retrieve the email id...

ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource webResource = client.resource(UriBuilder.fromUri("https://accounts.google.com/o/oauth2/token").build());
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("code", request.getParameter("code"));
formData.add("client_id", Global.GOOGLE_CLIENT_ID);
formData.add("redirect_uri", Global.GOOGLE_REDIRECT_URL);
formData.add("client_secret", Global.GOOGLE_SECRET);
formData.add("grant_type", "authorization_code");
ClientResponse response1 = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class, formData);
JSONObject jobject = new JSONObject(response1.getEntity(String.class));
String token_id = jobject.getString("id_token");
String[] base64EncodedSegments = token_id.split("\\.");

String base64EncodedHeader = base64EncodedSegments[0];
String base64EncodedClaims = base64EncodedSegments[1];
JsonParser parser = new JsonParser();
JsonElement payload = parser.parse(StringUtils.newStringUtf8(Base64.decodeBase64(base64EncodedClaims)));
JSONObject emailobject = new JSONObject(payload.toString());
String emailid = emailobject.getString("email");

Jars needed -

<dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.3</version>
        </dependency>


<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.3</version>
</dependency>

I also stuck with the same issue that you had faced. Finally, I found a solution

private byte[] extract_email(JSONObject json) throws Exception {
        String id_token = String.valueOf(json.get("id_token"));
        String[] jwtParts = id_token.split("\\.");
        return Base64.getDecoder().decode((jwtParts[1]));
}

The oauth2 tokens are encoded with Base64URL, however DatatypeConverter.parseBase64Binary() decodes standard Base64.

To convert them into standard Base64 you'll have to turn - into + , _ into / and appending padding chars = until each of the separate Base64URL-Strings ( base64EncodedSegments[] ) String.length() is a multiple of 4.

This should fix your problem with the missing } char which was lost due to the non-existent = padding chars in Base64URL Strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM