Google Analytics会引发403错误

Han*_*ood 2 c# google-analytics google-oauth

我正在尝试使用C#从Google Analytics下载指标数据,并且正在使用OAuth 2.0执行用户身份验证.我正在使用已安装的应用程序授权流程,该流程需要登录Google并将代码复制并粘贴到应用程序中.我正在关注从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;
}
Run Code Online (Sandbox Code Playgroud)

Google帐户xxxxxx@gmail.com注册了客户ID和密码.同一帐户在Google Analytics中具有完全管理权限.当我尝试从Google Analytics中提取数据时,它会通过授权流程,该流程似乎正常运行.然后它失败了:

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

几个小时我一直在努力.我已经仔细检查过正确的用户是否正在使用,并且已获得Google Analytics授权.我对于错误配置的东西感到茫然.有关需要配置或更改的内容的任何想法?

Pet*_*ete 15

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

var request = service.Data.Ga.Get(AccountID, StartDate, EndDate, Metrics);
Run Code Online (Sandbox Code Playgroud)

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

如果您使用网络界面登录Google Analytics,您会在浏览器地址栏的网址中看到以下模式:

/a12345w654321p9876543/
Run Code Online (Sandbox Code Playgroud)

p后面的数字是配置文件ID,因此上例中的9876543.请确保您使用的,实际上你应该使用表ID这将是GA:9876543.

如果它不是ID问题,则查询Management API以列出帐户并查看您有权访问的内容并验证auth是否正常工作.