问题
I want to get oauth or xauth tokens from GMail to use with gmail-oauth. I'm thinking of using OmniAuth but it seems not to support GMail yet, which means that with stock OmniAuth is impossible. Is that correct? Am I missing something?
回答1:
Omniauth has support for both OAuth and OAuth2, which will both allow you to authenticate a google account.
Here are all of the strategies you can use via omniauth: https://github.com/intridea/omniauth/wiki/List-of-Strategies
Here are the two google OAuth gems:
- omniauth-google (OAuth1)
- omniauth-google-oauth2 (OAuth2)
As per the documentation of the first gem:
Add the middleware to a Rails app in config/initializers/omniauth.rb:
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google, CONSUMER_KEY, CONSUMER_SECRET
# plus any other strategies you would like to support
end
This is done in addition to setting up the main omniauth gem.
回答2:
I had trouble, like you, using existing gems with OAuth2 and Gmail since Google's OAuth1 protocol is now deprecated and many gems have not yet updated to use their OAuth2 protocol. I was finally able to get it to work using Net::IMAP
directly.
Here is a working example of fetching email from Google using the OAuth2 protocol. This example uses the mail, gmail_xoauth, omniauth, and omniauth-google-oauth2 gems.
You will also need to register your app in Google's API console in order to get your API tokens.
# 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
来源:https://stackoverflow.com/questions/6009637/is-it-possible-to-get-gmail-oauth-or-xauth-tokens-with-omniauth