尝试从RAILS 4

时间:2017-01-14 11:58:36

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

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

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

我的代码:

初始化/ 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,那么它无效?

我可能完全错了什么?

提前致谢。

1 个答案:

答案 0 :(得分:0)

发现我的代码出现问题:

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

@resbody = response@resbody = response.body

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