是否可以使用OmniAuth获取Gmail oauth或xauth令牌?

我想从GMail获取oauth或xauth令牌以与gmail-oauth一起使用。 我正在考虑使用OmniAuth,但它似乎还不支持GMail,这意味着有了OmniAuth库存是不可能的。 那是对的吗? 我错过了什么吗?

Omniauth支持OAuth和OAuth2,它们允许您validation谷歌帐户。

以下是您可以通过omniauth使用的所有策略: https : //github.com/intridea/omniauth/wiki/List-of-Strategies

以下是两个Google OAuthgem:

  • omn​​iauth-google(OAuth1)
  • omn​​iauth-google-oauth2(OAuth2)

根据第一个gem的文档:

将中间件添加到config / initializers / omniauth.rb中的Rails应用程序:

Rails.application.config.middleware.use OmniAuth::Builder do provider :google, CONSUMER_KEY, CONSUMER_SECRET # plus any other strategies you would like to support end 

除了设置主要的omn​​iauth gem 之外,还可以完成此操作。

我和你一样,在使用OAuth2和Gmail的现有gem时遇到了麻烦,因为Google的OAuth1协议现已弃用,许多gem尚未更新以使用其OAuth2协议。 我终于能够直接使用Net::IMAP了解它。

以下是使用OAuth2协议从Google获取电子邮件的工作示例。 此示例使用mailgmail_xoauthomniauthomniauth-google-oauth2 gems。

您还需要在Google的API控制台中注册您的应用,以获取您的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