2011-04-11 60 views
8

我試圖獲得一個oauth令牌,我可以使用它與gmail_xauth(ruby gem) 來查看用戶的郵件。我第一次註冊我與谷歌的應用程序和 然後設置色器件請求訪問郵箱:針對Gmail的omniauth oauth令牌無效

config.omniauth :google, 'key', 'secret', :scope => 'https://mail.google.com/mail/feed/atom/' 

然後我經過OUTH/OpenID的流量和谷歌提示我 批准訪問Gmail,重定向我回該應用程序與一個令牌 和祕密omniuth憑據&我的Google帳戶列出我的應用程序 被授權訪問我的數據。到現在爲止還挺好。

現在,當我把這些憑據,並嘗試以 gmail_xoauth使用它們像這樣:

require 'gmail_xoauth' 
    imap = Net::IMAP.new('imap.gmail.com', 993, usessl = true, certs = 
nil, verify = false) 
    imap.authenticate('XOAUTH', '[email protected]', 
    :consumer_key => 'key, 
    :consumer_secret => 'secret', 
    :token => 'omniauth_returned_token', 
    :token_secret => 'omniauth_returned_secret' 
) 

我得到一個錯誤 「的Net :: IMAP :: NoResponseError:無效的憑證 (失敗)」。

有趣的是,使用gmail_xoauth README生成一個令牌 與使用python腳本的消費者使用同一個工具。

+1

你有解決這個問題的方法嗎? – Pablo 2011-05-16 05:51:08

+0

同樣在這裏。你找到解決方案嗎? – Pasta 2011-05-16 14:01:45

+0

我有類似的問題,但找到了解決方案。請參閱下面的答案。 – Andrew 2012-10-24 20:05:35

回答

5

這個工作對我來說:

config.omniauth :google, 'anonymous', 'anonymous', :scope => 'https://mail.google.com/' 

我使用Gmail的寶石,所以連接它看起來像這樣:

gmail = Gmail.connect(:xoauth, auth.uid, 
    :token   => auth.token, 
    :secret   => auth.secret, 
    :consumer_key => 'anonymous', 
    :consumer_secret => 'anonymous' 
) 

我傳遞一個認證對象,但你將從env變量env [「omniauth.auth」]中得到它。我使用匿名/匿名作爲密鑰/祕密,因爲我還沒有用谷歌註冊我的域名,但我相信你可以here。它仍然可以匿名/匿名方式工作,但Google只會提醒用戶。

+0

匿名作品。謝謝......只是想知道如何獲取聯繫人 – kgpdeveloper 2011-06-10 15:36:01

+0

這似乎不再有效 - 當我訪問omniauth對象時,祕密是零。有一個單獨的鏈接可以在http://blog.asif.in/blog/2012/03/03/google-oauth-and-rails/上找到,但我無法使其工作。 – David 2012-04-19 07:20:11

+0

這不起作用 – tommybond 2016-07-05 23:58:10

3

Google的OAuth1協議現在已被棄用,許多寶石尚未更新爲使用其OAuth2協議。這是一個使用他們的OAuth2協議從Google獲取電子郵件的實例。本示例使用mailgmail_xoauth,omniauthomniauth-google-oauth2寶石。

您還需要在Google's API console註冊您的應用程序才能獲取您的API令牌。

# in an initializer: 
ENV['GOOGLE_KEY'] = 'yourkey' 
ENV['GOOGLE_SECRET'] = 'yoursecret' 
Rails.application.config.middleware.use OmniAuth::Builder do 
    provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], { 
    scope: 'https://mail.google.com/,https://www.googleapis.com/auth/userinfo.email' 
    } 

end 

# ...after handling login with OmniAuth... 

# in your script 
email = auth_hash[:info][:email] 
access_token = auth_hash[:credentials][:token] 

imap = Net::IMAP.new('imap.gmail.com', 993, usessl = true, certs = nil, verify = false) 
imap.authenticate('XOAUTH2', email, access_token) 
imap.select('INBOX') 
imap.search(['ALL']).each do |message_id| 

    msg = imap.fetch(message_id,'RFC822')[0].attr['RFC822'] 
    mail = Mail.read_from_string msg 

    puts mail.subject 
    puts mail.text_part.body.to_s 
    puts mail.html_part.body.to_s 

end 
+1

我仍然在這裏得到一個錯誤,我有無效的憑據。 – locoboy 2015-07-16 01:02:31

+1

我得到無效的憑據仍與此答案。 – tommybond 2016-07-05 23:57:31