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

后端 未结 2 634
时光取名叫无心
时光取名叫无心 2021-01-06 01:56

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 Om

相关标签:
2条回答
  • 2021-01-06 02:17

    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
    
    0 讨论(0)
  • 2021-01-06 02:28

    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.

    0 讨论(0)
提交回复
热议问题