Search code examples
google-apps-marketplacegoogle-oauth

How to get google Token response which includes authorization code?


I need a way to get the google's response which includes authorization code once I install an app from Google apps marketplace Or is there a way I can get the authorization code?

code I use to retrieve the access token

 String url = "https://www.googleapis.com/oauth2/v3/token";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "code=authorization code returned from previous request&client_id=my_client_id&client_secret=my_client_secret_from dev console&redirect_uri=google app oauth redirect uri&grant_type=authorization_code";
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
            wr.flush();

Solution

  • Ok this is how you do it.

    First get the authorization URL like the following,

    String authorizationUrl = new GoogleAuthorizationCodeRequestUrl(
                    GoogleOAuthConstants.AUTHORIZATION_SERVER_URL, clientId,
                    nextUrl, GoogleResellerAdvController.SCOPES)
                    .setAccessType("offline").build();
    

    Once this is invoked you will get the authorization code which will be passed to retrieve the refresh token and access token. setAccessType("offline") during authorization is necessary only if you need refresh token, you can ignore it if you need only the access token, but access token will expire in an hour.

    Token Response retrieval:

    AuthorizationCodeFlow codeFlow = new AuthorizationCodeFlow.Builder(
                    BearerToken.authorizationHeaderAccessMethod(),
                    HTTP_TRANSPORT,
                    JSON_FACTORY,
                    new GenericUrl(GoogleOAuthConstants.TOKEN_SERVER_URL),
                    new ClientParametersAuthentication(
                            clientId, clientSecret),
                            clientId,
                            GoogleOAuthConstants.AUTHORIZATION_SERVER_URL
                    ).setScopes(SCOPES).build();
    
    
    
            TokenResponse response = codeFlow.newTokenRequest(authorizationCode)
                    .setRedirectUri(redirectUri).setScopes(SCOPES).execute();
    

    Response will have both access token and refresh tokens! Cheers!