Google Analytics throws 403 error

2020-04-16 17:23发布

问题:

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?

回答1:

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.



回答2:

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



回答3:

//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);
        }