Search code examples
javagoogle-oauthgoogle-contacts-apigoogle-oauth-java-client

Problems while getting Google oAuth2 access token - Redirect Uri Mismatch


I am trying to fetch google contacts for a user via oAuth2 mechanism. I am following this tutorial - https://developers.google.com/identity/sign-in/web/server-side-flow

I have javascript code that calls start() on pageload -

function start() {
  gapi.load('auth2', function() {
    auth2 = gapi.auth2.init({
      client_id: 'SOME_CLEINT_ID',
      scope: 'https://www.googleapis.com/auth/contacts.readonly'
    });
  });
}

and

auth2.grantOfflineAccess().then(signInCallback);

and then -

function signInCallback(authResult) {
    if (authResult['code']) {
        var callback = function(data){
            data = JSON.parse(data);
            console.log(data);
        };
        callAjax({action: 'saveGmailAuth', gaccesscode: authResult['code']}, callback, true);
    } else {
        // There was an error.
    }
}

This front end code calls my backend Java web servlet, which tries to get access token -

String authCode = request.getParameter("gaccesscode");
        String REDIRECT_URI = "";
        String CLIENT_SECRET_FILE = "G:/eclipse_proj/GoogleContacts/CLIENT_JSON_FILE.json";
        GoogleClientSecrets clientSecrets;
        try {
            clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(),
                    new FileReader(CLIENT_SECRET_FILE));
            REDIRECT_URI = clientSecrets.getDetails().getRedirectUris().get(0);
            GoogleAuthorizationCodeTokenRequest tokenRequest = new GoogleAuthorizationCodeTokenRequest(new NetHttpTransport(),
                    JacksonFactory.getDefaultInstance(), "https://www.googleapis.com/oauth2/v3/token",
                    clientSecrets.getDetails().getClientId(), clientSecrets.getDetails().getClientSecret(), authCode,
                    REDIRECT_URI);
            GoogleTokenResponse tokenResponse = tokenRequest.execute();
            String accessToken = tokenResponse.getAccessToken();
            GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

Every time I try this java code, every time it gives me error at tokenRequest.execute() -

com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
  "error" : "redirect_uri_mismatch",
  "error_description" : "Bad Request"
}

With REDIRECT_URI as empty string, it give another error saying - redirect_uri_not_provided.

I tried it with both "https://www.googleapis.com/oauth2/v3/token" and "https://www.googleapis.com/oauth2/v4/token"

I need help figuring this out. What am I doing wrong here?

My redirect URI is - http://localhost:8080/GoogleContacts/Callback in both json file and in developer console for oauth2.


Solution

  • For redirect_uri in using Google APIs,go to your Google Dev console and type what you see as is:

    //you can use any port you want
    http:localhost:8080/oauth2callback
    

    oauth2callback is the key ingredient.