Rails with Google Omniauth, cannot contact with google because of CORS error

Viewed 453

So I'm trying to configure Rails with Google oauth via devise, i have followed official docs described here. After everything i get this error when clicking the google signup button

Access to fetch at 'url' (redirected from 'http://localhost:3000/users/auth/google_oauth2') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Googling around i found you need to enable CORS, naturally i did just that

in my application.rb in added this

    Rails.application.config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', headers: :any, methods: [:get, :post, :patch, :put]
      end
    end

I have also added the url to google console

This is my callbacks controller


class Users::CallbacksController < Devise::OmniauthCallbacksController
  skip_before_action :verify_authenticity_token

  def google_oauth2
    admin = User.from_omniauth(from_google_params)

    redirect_to root_path
  end
  
  private 

  def from_google_params
    @from_google_params ||= {
        uid: auth.uid,
        email: auth.info.email,
        full_name: auth.info.name,
        avatar_url: auth.info.image,
    is_member: false
    }
  end

  def auth
    @auth ||= request.env['omniauth.auth']
  end
end


EDIT So after alot of trial n errors i have it working, kinda. So when i click the signup with google it still throws an error, enter image description here

But, when clicking the link in the google console it successfully goes there, any ideas ?

1 Answers

Try this setup with devise at master branch and gem omniauth-rails_csrf_protection

devise.rb

config.omniauth :google_oauth2, "API_KEY", "API_SECRET"

routes.rb

devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }

user.rb

devise :omniauthable, omniauth_providers: [:google_oauth2]

app/controllers/users/omniauth_callbacks_controller.rb:

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def google_oauth2
      @user = User.from_omniauth(request.env['omniauth.auth'])
      if @user.persisted?
        flash[:notice] = I18n.t 'devise.omniauth_callbacks.success', kind: 'Google'
        sign_in_and_redirect @user, event: :authentication
      else
        session['devise.google_data'] = request.env['omniauth.auth'].except('extra') # Removing extra as it can overflow some session stores
        redirect_to new_user_registration_url, alert: @user.errors.full_messages.join("\n")
      end
  end
end

user.rb

def self.from_omniauth(access_token)
    data = access_token.info
    user = User.where(email: data['email']).first
    unless user
      user = User.create(
        email: data['email'],
        password: Devise.friendly_token[0,20])
    end
    user
end

gemfile:

gem "devise", github: "heartcombo/devise", branch: "master"
gem "omniauth-rails_csrf_protection"
gem "omniauth-google-oauth2"

view:

<%= link_to "Sign in with Google", user_omniauth_authorize_path(:google_oauth2), method: :post %>
Related