我已經在我的Rails 4應用程序中設置了Google授權,它按預期工作。現在我想要使用Gmail API檢索授權的用戶電子郵件,但我在瀏覽器中收到#<Net::HTTPUnauthorized:0x0055ed1f7f8d68>
錯誤,作爲對我的GET請求的響應。Net :: HTTPUnauthorized當試圖從RAILS訪問Gmail API 4
在開發控制檯中,我啓用了所有必需的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一起使用,則它不起作用?
怎麼可能是我做的完全錯了?
在此先感謝。
登錄到Gmail帳戶,然後點擊右上角的圖片。點擊我的帳戶,然後點擊登錄和安全,然後向下滾動,直到看到「允許安全性較低的應用程序:」,然後開啓該功能。您將可以繼續使用Rails應用程序。 – sahil
@sahil謝謝,但仍然是同樣的問題.. – Edgars