Is it possible to get Gmail oauth or xauth tokens with OmniAuth?
Asked Answered
L

2

5

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?

Latanya answered 15/5, 2011 at 16:18 Comment(0)
B
2

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:

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.

Brahmana answered 1/2, 2012 at 20:15 Comment(2)
I think the question is about getting the access_token, not only authenticating. This access_token is useful to use google apis.Ethos
Ah, I read it more that the OP felt they couldn't do auth with omniauth via google so they were wondering if they needed to roll their own. Omniauth has extensions to auth via google, but it's a step above the basic implementation.Brahmana
V
1

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
Valorie answered 11/10, 2012 at 23:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.