authentication - 无法使用 OAuth 2 查询 Google Analytics 报告 API

标签 authentication oauth-2.0 google-analytics-api

我正在尝试使用 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/

相关文章:

ios - Pinterest OAuth API 不重定向?

php - 我如何在 Laravel Auth::attempt 中使用条件参数?

spring-boot - 如何使用 Spring boot keycloak 适配器 + spring security 强制更新 oAuth token (访问 token + 刷新 token )?

google-analytics - 显示 'not set' 的移动设备信息

google-app-engine - 使用 App Engine 开发服务器向 Google API 声明身份

javascript - Facebook 登录获取错误。 "Cannot read property ' id'未定义”

java - 我如何使用 java 在不进行身份验证的情况下发送电子邮件

javascript - 无法将 Twitter 与 Satellizer.js 链接

scope - Oauth2 访问 token 规范和处理范围

google-analytics - 增加 Google Analytics API 配额