2011-04-11 192 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