Search code examples
javaoauth-2.0google-analytics-api

Confusion with redirect_uri in OAuth 2.0


I have been using Google Analytics for my website which I have created in weebly. I am using the Google APIs to implement the whole thing programmatically.

The Problem I am facing during the OAuth flow, is that I am getting this error:

Error: redirect_uri_mismatch
The redirect URI in the request:localhost:34190/Callback did not match a registered redirect URI

        Request Details
        scope=https://www.googleapis.com/auth/analytics.readonly
        response_type=code
        access_type=online
        redirect_uri=local_host:34190/Callback
        display=page
        client_id={CLIENT_ID}.apps.googleusercontent.com

My google api console config is:

Redirect URI: localhost/oauth2callback
JavaScript origins: localhost

Why on earth redirect_uri is localhost:34190/Callback when I set it to: http://mya.com/oauth2callback?

Code which I have written for openauth:

public static void main(String[] args) throws Exception {
    Analytics analytics = initializeAnalytics();
}

private static Analytics initializeAnalytics() throws Exception {
    Credential credential = authorize();
}

private static Credential authorize() throws Exception {
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
        JSON_FACTORY, Testcode.class.getResourceAsStream("/client_secrets.json"));
    FileCredentialStore credentialStore = new FileCredentialStore(
        new File(System.getProperty("user.home"), ".credentials/analytics.json"),
        JSON_FACTORY);
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets,
        Collections.singleton(AnalyticsScopes.ANALYTICS_READONLY)).setCredentialStore(
            credentialStore).build();
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
                   .authorize(clientSecrets.getDetails().getClientId());
  }       

How can I get rid of this error?


Solution

  • So your website tells Google to use localhost:34190/Callback as redirect URI. But you've said to the Google server, that he only should accept requests when your app specifies localhost/oauth2callback as redirect URI.

    The easy fix would be to setup Google Console as follows:

    Redirect URI: http://localhost:34190/Callback
    

    Anyway, you are talking about you wanting to redirect to http://mya.com/oauth2callback.

    In this case you should alter the link the user clicks on your website to specify this

    [...]&redirect_uri=http://mya.com/oauth2callback[...]
    

    and then set this up in Google Console:

    Redirect URI: http://mya.com/oauth2callback