Net::HTTPUnauthorized 尝试从 RAILS 访问 Gmail API 时 4

Net::HTTPUnauthorized when trying to access Gmail API from RAILS 4

我已经在我的 Rails 4 应用程序中设置了 Google 授权,它按预期工作。现在我想使用 Gmail API 检索授权用户的电子邮件,但我在浏览器中收到 #<Net::HTTPUnauthorized:0x0055ed1f7f8d68> 错误作为对我的 GET 请求的响应。

在开发者控制台中,我启用了所有必需的 APIs。

我的代码:

initializers/omniauth.rb

OmniAuth.config.logger = Rails.logger

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, Rails.application.secrets.client_id, Rails.application.secrets.client_secret, {scope: ['email',
    'https://www.googleapis.com/auth/gmail.modify'],
    access_type: 'offline', client_options: {ssl: {ca_file: Rails.root.join("cacert.pem").to_s}}}
end

User.rb

  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.name = auth.info.name
      user.email = auth.info.email
      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.save!
    end
  end

在我的控制器中:

 def mail
   require 'net/http'
   access_token =  current_user.oauth_token
   e = current_user.email
   u = "https://www.googleapis.com/gmail/v1/users/#{e}/messages? maxResults=50&key=#{access_token}"
   url = URI.parse(u)
   req = Net::HTTP::Post.new(url.request_uri)
   http = Net::HTTP.new(url.host, url.port)
   http.use_ssl = (url.scheme == "https")
   response = http.request(req)
   @resbody = response
end

在我看来

<%= @resbody %>

已安装的宝石:

gem "omniauth-google-oauth2", "~> 0.2.1"
gem "google-api-client"

当我尝试执行时

curl https://www.googleapis.com/gmail/v1/users/my-email/messages&access_token=ya29.Ci .... A
[1] 6687

我收到了这样的信息:

 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Login Required",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Login Required"
 }
}

问题:我不明白。如果我被授权使用 Google 帐户并将我的访问令牌保存在数据库中,然后检索它以用于 Gmail API 它不起作用?

我做错了什么?

提前致谢。

发现我的代码有问题:

req = Net::HTTP::Post.new(url.request_uri) 改为 req = Net::HTTP::Get.new(url.request_uri)

@resbody = response@resbody = response.body

现在我可以看到检索到的邮件:)