无法获取 Google Analytics API 的 oAuth2 访问令牌 [英] Cannot get oAuth2 Access Token for Google Analytics API

查看:36
本文介绍了无法获取 Google Analytics API 的 oAuth2 访问令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Rails + Garb Gem(Sija Branch)+ omniauth-google-oauth2 Gem,我可以成功通过 Google Analytics API 进行身份验证并提取我们的应用程序在使用用户登录时生成的数据,例如:

I am using Rails + Garb Gem (Sija Branch) + omniauth-google-oauth2 Gem and I can successfully authenticate with the Google Analytics API and extract data that our app is generating when using a user login, e.g.:

Garb::Session.login('USERNAME', '<PASSWORD>')

然后我可以使用 Garb 连接到我想要的分析配置文件并从中提取数据并在网页上显示一些图表.这一切正常.

I can then use Garb to connect to the Analytics Profile I want and pull the data from it and display some charts on a webpage. This all works fine.

但是,我想使用 oAuth2 对 Analytics 进行身份验证,这就是为什么我必须从 Github 安装 Garb Gem 的 Sija 分支(它支持 oAuth2)并且我还安装了 omniauth-google-oauth2 Gem.现在理论上我应该能够使用以下代码进行身份验证:

However, I want to use oAuth2 to authenticate with Analytics which is why I had to install the Sija branch of the Garb Gem from Github (it supports oAuth2) and I also installed the omniauth-google-oauth2 Gem. Now in theory I should be able to authenticate using the following code:

Garb::Session.access_token = access_token # an instance of OAuth2::Client

此时对我来说有点模糊,我非常感谢您的指导.这是我已经走了多远:

It's at this point that it gets a little hazy for me and I would greatly appreciate some guidance. Here's how far I have gotten:

1) 我在 Google API 控制台中创建了一个项目并在服务下打开了 Analytics API

1) I created a Project in the Google API console and turned on Analytics API under Services

2) 这为我提供了客户端 ID 和客户端密钥

2) This provided me with a Client ID and Client Secret

3) 我遇到了可以用上面的 ID 和 Secret 填充的代码:

3) I came across this code which I could populate with the ID and Secret above:

client = OAuth2::Client.new(
GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET,
{
    :site          => 'https://accounts.google.com',
    :authorize_url => '/o/oauth2/auth',
    :token_url     => '/o/oauth2/token'
})

4) 然后是下一段代码:

4) Then there is the next bit of code:

response = OAuth2::AccessToken.new(
    client,
    STORED_TOKEN, {
    refresh_token: STORED_REFRESH_TOKEN,
    expires_at: STORED_EXPIRES_AT
})

5) 然后理论上连接:

5) and then in theory connect with:

Garb::Session.access_token = response

我的问题是我没有上面第 (4) 点中的令牌信息.在我看来,使用 oAuth2 我需要做一次握手"并打印出返回令牌值?也许通过 Rails 代码打印返回的值,然后将令牌值粘贴到 Rails 应用程序中的常量中,以便我可以在上面的代码中使用它们?我真的很困惑.正如我之前提到的,Web 应用程序使用用户登录身份验证可以正常工作.Web 应用程序所做的就是通过分析进行身份验证、提取一些数据并绘制图表.但是我坚持将其转换为 oAuth2,因为 我只是不知道如何获取 Garb Gem 正在寻找的访问令牌.我还应该注意,这是不是需要多个用户进行身份验证的公共网站,而是连接到我们自己的 Analytics 数据的 CMS 网站.

The problem I have is I don't have the token information in Point (4) above. It seems to me that with oAuth2 I need to do a "handshake" once and print out the return token values? Perhaps through Rails code which prints the values returned out and then paste the token values into a constant in the Rails app so that I can use them in the above code? I really am confused. As I mentioned earlier, the web app works fine using the user login authentication. All the web app is doing is authenticating with analytics, pulling down some data and drawing a chart. But I am stuck converting it over to oAuth2 as I just do not know how to get the Access Token that the Garb Gem is looking for. I should also note that this is not a public website with multiple users authenticating, this is a CMS website that is connecting to our own Analytics data.

我已经看到了这方面的一些部分片段,但没有完全解释或工作示例.我非常感谢您对此问题的任何指导和帮助.

I have seen some partial snippets of aspects of this but not a fully explained or working example. I would really appreciate any guidance and help with this question.

非常感谢,

JR

推荐答案

过去几周我一直在努力解决这个问题,所以让我分享一下有效的方法:

I've soldiered through this over the last few weeks, so let me share what worked:

要使用 Oauth2,您需要获得一个刷新令牌",每次进行 API 调用时,您都用它来重新验证"谷歌.其步骤如下:

To use Oauth2 you need to get a 'refresh token' that you use to 're-authenticate' with google each time you make an API call. The steps for this are as follows:

1) 在 API 控制台中设置您的帐户 - https://code.google.com/apis/console/b/0/(好像你做得很好)2) 在您的 API 帐户中,确保您有一个指向您的应用程序的重定向 URI:

1) Setup your account in the API console - https://code.google.com/apis/console/b/0/ (seems like you've done that well) 2) In your API account, make sure you have a redirect URI pointing back to your application:

http://some-url.com/auth/google_oauth2/callback
http://localhost:3000/auth/google_oauth2/callback

请注意,google 不会让您以 0.0.0.0:3000 的身份回拨到本地计算机...因此您需要明确使用 localhost

Note here that google won't let you call back to your local machine as 0.0.0.0:3000... so you'll need to use localhost explicitly

3) 在您的路由文件中,将该重定向 url 绑定到您要在其中创建项目或身份验证的控制器中的操作

3) In your route file, tie that redirect url to an action in the controller where you're going to create the project or authentication

match '/auth/:provider/callback' => 'authentications#create'

':provider' 只是让您匹配多种类型的 oauth,但您也可以将 'google_oauth2' 放在那里.

The ':provider' simply lets you match on multiple types of oauth, but you could just put 'google_oauth2' there as well.

4) 现在在您的控制器中创建该操作

4) Now create that action in your controller

def create
  auth = request.env["omniauth.auth"] 
  params = request.env["omniauth.params"]
  project = Project.find(params['project_id'])

  Authentication.create(:project_id => project.id, :provider => auth['provider'], :uid => auth['uid'], :access_token => auth['credentials']['refresh_token'])
  flash[:notice] = "Authentication successful."
  redirect_to owner_view_project_path(project)
end

5) 控制器动作应该从响应对象中检索相关字段(这里响应对象的详细信息:https://github.com/zquestz/omniauth-google-oauth2) - 特别是,您需要获取refresh_token"并将其保存到您的项目或身份验证对象中 - 如果您尚未添加'access_token' 属性到所需对象,现在通过迁移来做,然后开始将刷新令牌保存到该属性

5) The controller action should retrieve the relevant fields from the response object (details of response object here: https://github.com/zquestz/omniauth-google-oauth2) - in particular, you need to get the 'refresh_token' and save that to your project or authentication object - if you haven't added an 'access_token' attribute to the desired object, go do that now with a migration, then start saving the refresh token to that attribute

6) 现在,当您准备好调用该特定身份验证并为其获取 API 数据时,您可以加载保存访问令牌的对象,并使用它来获取与谷歌 API 的新会话,如下所示:

6) Now when you're ready to call that particular authentication and get API data for it, you can load up that object where you saved the access token, and use that to get a new session with the google API as follows:

  @authentication = Authentications.find(params[:id])

  client = OAuth2::Client.new GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET,
                                  {
                                    :site => 'https://accounts.google.com',
                                    :authorize_url => "/o/oauth2/auth",
                                    :token_url => "/o/oauth2/token",
                                  }
  response = OAuth2::AccessToken.from_hash(client, :refresh_token => @authentication.access_token).refresh!
  Garb::Session.access_token = response
  @profiles = Garb::Management::Profile.all

此代码所做的是通过指定客户端和 refresh_token,然后调用refresh!"来创建 OAuth2 访问令牌(响应).获取刷新的访问令牌...然后使用该访问令牌建立您的 Garb 会话,然后使用 Gard::Management::Profile.all 调用给定帐户的所有配置文件

What this code did was create an OAuth2 access token (response) by specifying the client and then a refresh_token, then calling 'refresh!' to get a refreshed access token... then use that access token to establish your Garb session, then call down all the profiles for a given account using the Gard::Management::Profile.all

希望这会有所帮助 - 如果您有任何问题,请告诉我!

Hope this helps - let me know if you have questions!

这篇关于无法获取 Google Analytics API 的 oAuth2 访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆