我正在尝试使用 OAuth 2 来使用最新版本的 Report API。似乎还没有很多人使用这个版本,所以很难找到示例。
我有一个刷新 token ,我用它来生成访问 token 。
private AnalyticsService getAnalyticsService()
{
AuthorizationServerDescription description = new AuthorizationServerDescription();
description.TokenEndpoint = new Uri(login.TokenEndpoint);
description.AuthorizationEndpoint = new Uri(login.AuthorizationEndpoint);
WebServerClient client = new WebServerClient(description, login.ClientId, login.ClientSecret);
OAuth2Authenticator<WebServerClient> authenticator = new OAuth2Authenticator<WebServerClient>(client, authenticate);
AnalyticsService service = new AnalyticsService(authenticator);
return service;
}
private IAuthorizationState authenticate(WebServerClient client)
{
string[] scopes = new string[] { login.ScopeUrl }; // not sure if this is necessary
IAuthorizationState state = new AuthorizationState(scopes) { RefreshToken = login.RefreshToken };
client.RefreshToken(state);
return state;
}
这似乎工作得很好:
{
"access_token" : "ya29.AHES6ZQy67SSLHWJWGWcLbLn69yKfq59y6dTHDf4ZoH9vHY",
"token_type" : "Bearer",
"expires_in" : 3600
}
但是,当我执行请求时,出现错误。例如,这里 是一个导致错误的查询:
AnalyticsService service = getAnalyticsService();
ManagementResource.ProfilesResource.ListRequest request = service.Management.Profiles.List("~all", "~all");
return request.Fetch();
这是我得到的错误:
{"error":{"errors":[{"domain":"global","reason":"authError","message":"Invalid
Credentials","locationType":"header","location":"Authorization"}],"code":401,"message":"Invalid
Credentials"}}
我尝试了其他查询,提供了有效的个人资料 ID。然而,我是 总是收到 401 错误,说我无权。我有 很难找到人们使用此代码的示例。它可能是 一些简单的东西,比如错误的 URL 之类的。不幸的是,我没有 方式来讲述。我可以获得访问 token ,这似乎很奇怪,但我 似乎无法执行任何查询。
最佳答案
使用 OAuth 2,范围更改为:
https://www.google.com/analytics/feeds/
至:
https://www.googleapis.com/auth/analytics.readonly
您收到身份验证错误,因为您尝试在没有适当范围的情况下获取访问权限。
快速轻松地修复。
关于authentication - 无法使用 OAuth 2 查询 Google Analytics 报告 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9080383/