谷歌分析抛出403错误

本文关键字:错误 谷歌 | 更新日期: 2023-09-27 18:23:36

我正试图使用C#从Google Analytics下载度量数据,并使用OAuth 2.0执行用户身份验证。我使用的是已安装的应用程序授权流程,它需要登录谷歌并将代码复制粘贴到应用程序中。我下面的代码取自谷歌api dotnet客户端:

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

Google帐户xxxxxx@gmail.com注册了客户端ID和机密。同一帐户在Google Analytics中拥有完全的管理权限。当我试图从谷歌分析中提取数据时,它会经过授权程序,看起来工作正常。然后失败:

Google.GoogleApiException
Google.Apis.Requests.RequestError
用户对此配置文件没有足够的权限。[403]
错误[
消息[用户对此配置文件没有足够的权限。]位置[-]原因[infullicientPermissions]域[global]
]

我已经为此挣扎了几个小时。我已经仔细检查了是否使用了正确的用户,并在谷歌分析上获得了授权。我不知道什么地方被误解了。关于什么需要配置或更改,有什么想法吗?

谷歌分析抛出403错误

如果auth似乎在工作,那么我的建议是确保提供正确的ID,因为基于您的代码片段:

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

人们只能假设你正在使用帐户ID。如果是这样,那就不正确了,你会收到你遇到的错误。您需要使用配置文件ID进行查询。

如果你使用网络界面登录谷歌分析,你会在浏览器地址栏的URL中看到以下模式:

/a12345w654321p9876543/

p后面的数字是配置文件ID,因此在上例中为9876543。请确保您正在使用它,并且实际上您应该使用表id,它将是ga:9876543

如果不是ID问题,则查询管理API以列出帐户,查看您可以访问的内容,并验证验证是否正常工作。

这可以帮助:https://developers.google.com/analytics/devguides/reporting/core/v3/coreErrors,查看错误403。

//感谢您的这篇文章。可以从帐户摘要中读取所需的配置文件id。

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