【问题标题】:Net::HTTPUnauthorized when trying to access Gmail API from RAILS 4尝试从 RAILS 4 访问 Gmail API 时 Net::HTTPUnauthorized
【发布时间】:2017-05-29 17:14:01
【问题描述】:

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

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

我的代码:

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

用户.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:

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 一起使用,它不起作用?

我做错了什么?

提前致谢。

【问题讨论】:

  • 登录您的 gmail 帐户,然后点击右上角的图片。单击我的帐户,然后单击登录和安全并向下滚动,直到看到Allow less secure apps:,将其打开。您将能够继续使用您的 Rails 应用程序。
  • @sahil 谢谢,但还是同样的问题..

标签: ruby-on-rails omniauth gmail-api google-api-client net-http


【解决方案1】:

发现我的代码有问题:

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

@resbody = response@resbody = response.body

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

【讨论】:

    猜你喜欢
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 2015-07-31
    • 2023-02-08
    • 2021-05-03
    • 2015-01-12
    • 2021-08-10
    • 1970-01-01
    相关资源
    最近更新 更多