3

I am attempting to download metric data from Google Analytics using C# and am performing user authentication with OAuth 2.0. I'm using the Installed Application authorisation flow, which requires logging into Google and copy-and-pasting a code into the application. I'm following the code taken from google-api-dotnet-client:

private void DownloadData()
{
    Service = new AnalyticsService(new BaseClientService.Initializer() {
        Authenticator = CreateAuthenticator(),
    });
    var request = service.Data.Ga.Get(AccountID, StartDate, EndDate, Metrics);
    request.Dimensions = Dimensions;
    request.StartIndex = 1;
    request.MaxResults = 10000;
    var response = request.Execute(); // throws Google.GoogleApiException
}

private IAuthenticator CreateAuthenticator()
{
    var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) {
        ClientIdentifier = "123456789012.apps.googleusercontent.com",
        ClientSecret = "xxxxxxxxxxxxxxxxxxxxxxxx",
    };
    return new OAuth2Authenticator<NativeApplicationClient>(provider, Login);
}

private static IAuthorizationState Login(NativeApplicationClient arg)
{
    // Generate the authorization URL.
    IAuthorizationState state = new AuthorizationState(new[] { AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue() });
    state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
    Uri authUri = arg.RequestUserAuthorization(state);

    // Request authorization from the user by opening a browser window.
    Process.Start(authUri.ToString());
    Console.Write("Google Authorization Code: ");
    string authCode = Console.ReadLine();

    // Retrieve the access token by using the authorization code.
    state = arg.ProcessUserAuthorization(authCode, state);
    return state;
}

The Google account xxxxxx@gmail.com registered the Client ID and secret. The same account has full administration rights in Google Analytics. When I try to pull data from Google Analytics, it goes through the authorisation process, which appears to work properly. Then it fails with:

Google.GoogleApiException
Google.Apis.Requests.RequestError
User does not have sufficient permissions for this profile. [403]
Errors [
Message[User does not have sufficient permissions for this profile.] Location[ - ] Reason [insufficientPermissions] Domain[global]
]

I've been struggling with this for a few hours. I've double checked that the correct user is being used, and is authorised on Google Analytics. I'm at a loss as to what is misconfigured. Any ideas as to what requires configuring or changing?

Hand-E-Food
  • 12,368
  • 8
  • 45
  • 80

3 Answers3

16

If auth seems to be working working then my suggestion is that you make sure you're providing the correct ID because based on your code snippet:

var request = service.Data.Ga.Get(AccountID, StartDate, EndDate, Metrics);

one can only assume that you're using the Account ID. If so, that is incorrect and you'd receive the error you've encountered. You need to query with the Profile ID.

If you login to Google Analytics using the web interface you'll see the following pattern in URL of the browser's address bar:

/a12345w654321p9876543/

The number following the p is the profile ID, so 9876543 in the example above. Make sure you're using that and actually you should be using the table id which would be ga:9876543.

If it isn't an ID issue then instead query the Management API to list accounts and see what you have access to and to verify auth is working correctly.

Pete
  • 1,862
  • 11
  • 12
  • Thank you very much! It'd be nice if the Google Analytics Administration UI advertised this number somewhere... – Hand-E-Food Jul 18 '13 at 05:30
  • Whelp, five hours of my life is now gone and never coming back. There is literally nothing in Google's documentation that suggests that this value exists apart from the account ID and it's not exposed by any other mechanism. Thank you very much for sharing this. – Justin Searls Aug 07 '14 at 01:03
  • Excellent! After 2 days of trying to get the Google API to work with analytics in .net, I just got to the final hurdle and this last step helped me tremendously. – Myke Black Sep 08 '15 at 19:18
0

This can help : https://developers.google.com/analytics/devguides/reporting/core/v3/coreErrors, look error 403.

Jose Rodriguez
  • 9,753
  • 13
  • 36
  • 52
0

//Thanks for this post. The required profile id can be read from the account summaries.

Dictionary profiles = new Dictionary();

        var accounts = service.Management.AccountSummaries.List().Execute();
        foreach (var account in accounts.Items)
        {
            var profileId = account.WebProperties[0].Profiles[0].Id;

            profiles.Add("ga:" + profileId, account.Name);
        }