zquestz / omniauth-google-oauth2

Oauth2 strategy for Google
1.45k stars 413 forks source link

Authentication failure! invalid_credentials: OAuth2::Error, invalid_grant: Bad Request #413

Closed nighttiger1990 closed 4 months ago

nighttiger1990 commented 2 years ago

When I develop local all work perfectly, but when deploy on docker I got this error. Can you help me resolved this

E, [2021-10-14T18:13:18.970657 #1] ERROR -- omniauth: (google_oauth2) Authentication failure! invalid_credentials: OAuth2::Error, invalid_grant: Bad Request
{
  "error": "invalid_grant",
  "error_description": "Bad Request"
}

This is docker file

FROM ruby:2.6.2-alpine
COPY Gemfile Gemfile.lock ./
RUN apk add --update npm tzdata openssl git openssh zlib-dev libxml2-dev redis \
    libxslt-dev yaml-dev bash ruby-dev build-base linux-headers && \
    npm install -g bower && \
    bundle config build.nokogiri --use-system-libraries && \
    bundle install --without development test --no-deployment --binstubs && \
    bundle clean && \
    rm -rf /var/cache/apk/* && \
    mkdir -p /home/rails/eros/tmp/pids && \
    touch /home/rails/eros/tmp/pids/sidekiq.pid
ADD . /home/rails/eros
WORKDIR /home/rails/eros
RUN redis-server & \
    bundle exec rake bower:install['--allow-root'] && \
    bundle exec rake assets:precompile
ENV RAILS_SERVE_STATIC_FILES true
ENV RAILS_LOG_TO_STDOUT true
CMD bundle exec rake assets:precompile && bundle exec puma -C config/puma.rb

My gem file

source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.2', '>= 5.0.0.1'
# Use sqlite3 as the database for Active Record
# gem 'sqlite3'
# Use Puma as the app server
gem 'puma'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
gem 'jquery-ui-rails', '~> 5.0.5'
gem 'jquery-turbolinks', '~> 2.0.2'

# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5.0.0'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
  gem "rack_session_access"
  gem 'pry-rails'
  # gem 'ruby-debug-ide'
  # gem 'debase'
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end
gem 'listen', '~> 3.0.5'
gem 'whenever', '~> 0.9.4', :require => false

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

#
gem 'mongoid', '6.0.0.rc0'

# Notifier Slack
gem 'slack-notifier'

gem 'bson_ext', '1.5.1'

gem 'rails_param', '0.9.0'

gem 'dotenv-rails', '2.0.1'

gem 'rubocop', '~> 0.58.2', require: false

gem 'bower-rails', '~> 0.10.0'

gem "font-awesome-rails"

gem 'bootstrap-sass', '~> 3.3.6'

gem 'haml-rails', '~> 0.9.0'

gem 'will_paginate_mongoid', '~> 2.0.1'

gem 'chosen-rails'
gem 'shoryuken'
gem 'rufus-scheduler'

gem 'rack-cors', :require => 'rack/cors'

gem 'momentjs-rails', '>= 2.9.0'
gem 'bootstrap3-datetimepicker-rails', '~> 4.17.47'

group :development do
  gem 'capistrano',         require: false
  gem 'capistrano-rvm',     require: false
  gem 'capistrano-rails',   require: false
  gem 'capistrano-bundler', require: false
  gem 'capistrano3-puma',   require: false
  gem 'rack-mini-profiler'
  gem 'capistrano-shoryuken'
end

group :test do
  gem 'capybara'
  gem 'poltergeist'
  gem 'selenium-webdriver', '~> 2.48.1'
  gem 'minitest-rails'
  gem 'minitest-rails-capybara'
  gem 'minitest-reporters'
  gem 'webmock'
  gem 'rails-controller-testing'
end

#load environment variables from .env into ENV in development.
gem "figaro"

# fix paginate rails 5
# gem 'kaminari', github: "amatsuda/kaminari", branch: '0-17-stable'
gem 'resque'
gem 'resque-web', require: 'resque_web'
gem 'redis', '~>3.2'
gem 'highcharts-rails', '~> 4.1', '>= 4.1.9'
gem 'devise'
gem 'omniauth'
gem 'omniauth-google-oauth2'
gem 'omniauth-rails_csrf_protection', '~> 1.0'
# gem 'lograge', '~> 0.4.1'
gem 'request_store', '~> 1.3.1'
gem 'rest-client', '~> 2.0.0.rc2'
gem 'jsonapi-resources'
#Do some browser detection with Ruby. Includes ActionController integration.

gem 'browser'

gem 'gelf'
gem 'lograge'
# Sentry-raven
gem 'sentry-raven'
gem 'aws-sdk-sqs'
gem 'aws-sdk-s3'
gem 'rubyzip', '~> 1.1.0'
gem 'axlsx', '2.1.0.pre'
gem 'axlsx_rails'

#queue
gem 'bunny', '>= 2.7.0'
gem 'colorize'

gem 'pureapi', '~> 0.5.1'
gem 'redis-rails'

gem 'sidekiq'
gem 'sidekiq-cron'
gem 'sinatra', :require => false
gem 'bitly', '~> 1.1', '>= 1.1.1'

gem 'chart-js-rails'
Warning: the running version of Bundler (1.17.2) is older than the version that created the lockfile (1.17.3). We suggest you upgrade to the latest version of Bundler by running `gem install bundler`.
The dependency tzinfo-data (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mingw32, x86-mswin32, x64-mingw32, java. To add those platforms to the bundle, run `bundle lock --add-platform x86-mingw32 x86-mswin32 x64-mingw32 java`.
Using rake 13.0.6
Using concurrent-ruby 1.1.9
Using i18n 1.8.10
Using minitest 5.14.4
Using thread_safe 0.3.6
Using tzinfo 1.2.9
Using activesupport 5.0.7.1
Using builder 3.2.4
Using erubis 2.7.0
Using mini_portile2 2.6.1
Using racc 1.5.2
Using nokogiri 1.12.5 (x86_64-linux)
Using rails-dom-testing 2.0.3
Using crass 1.0.6
Using loofah 2.12.0
Using rails-html-sanitizer 1.4.2
Using actionview 5.0.7.1
Using rack 2.2.3
Using rack-test 0.6.3
Using actionpack 5.0.7.1
Using nio4r 2.3.1
Using websocket-extensions 0.1.3
Using websocket-driver 0.6.5
Using actioncable 5.0.7.1
Using globalid 0.4.2
Using activejob 5.0.7.1
Using mini_mime 1.0.1
Using mail 2.7.1
Using actionmailer 5.0.7.1
Using activemodel 5.0.7.1
Using arel 7.1.4
Using activerecord 5.0.7.1
Using public_suffix 3.0.3
Using addressable 2.6.0
Using net-ssh 5.1.0
Using net-scp 1.2.1
Using sshkit 1.18.2
Using airbrussh 1.3.1
Using amq-protocol 2.3.0
Using ansi 1.5.0
Using ast 2.4.0
Using execjs 2.7.0
Using autoprefixer-rails 9.4.10
Using aws-eventstream 1.0.1
Using aws-partitions 1.141.0
Using aws-sigv4 1.0.3
Using jmespath 1.4.0
Using aws-sdk-core 3.46.2
Using aws-sdk-kms 1.13.0
Using aws-sdk-s3 1.30.1
Using aws-sdk-sqs 1.10.0
Using htmlentities 4.3.4
Using rubyzip 1.1.7
Using axlsx 2.1.0.pre
Using axlsx_rails 0.5.2
Using bcrypt 3.1.16
Using bindex 0.5.0
Using mime-types-data 3.2018.0812
Using mime-types 3.2.2
Using multi_xml 0.6.0
Using httparty 0.16.4
Using multi_json 1.15.0
Using multipart-post 2.1.1
Using faraday 0.17.4
Using jwt 2.3.0
Using oauth2 1.4.7
Using bitly 1.1.2
Using rb-fsevent 0.10.3
Using ffi 1.10.0
Using rb-inotify 0.10.0
Using sass-listen 4.0.0
Using sass 3.7.3
Using bootstrap-sass 3.3.7
Using method_source 0.9.2
Using thor 0.20.3
Using railties 5.0.7.1
Using momentjs-rails 2.20.1
Using bootstrap3-datetimepicker-rails 4.17.47
Using bower-rails 0.10.0
Using browser 2.5.3
Using bson 4.4.2
Using bson_ext 1.5.1
Using bundler 1.17.2
Using bunny 2.14.1
Using byebug 11.0.0
Using capistrano 3.11.0
Using capistrano-bundler 1.5.0
Using capistrano-rails 1.4.0
Using capistrano-rvm 0.1.2
Using capistrano-shoryuken 0.1.5
Using puma 3.12.0
Using capistrano3-puma 3.1.1
Using xpath 3.2.0
Using capybara 2.18.0
Using chart-js-rails 0.1.6
Using childprocess 0.9.0
Using coffee-script-source 1.12.2
Using coffee-script 2.4.1
Using coffee-rails 4.2.2
Using sprockets 3.7.2
Using sprockets-rails 3.2.1
Using tilt 2.0.9
Using sass-rails 5.0.7
Using chosen-rails 1.8.7
Using chronic 0.10.2
Using cliver 0.3.2
Using coderay 1.1.2
Using colorize 0.8.1
Using commonjs 0.2.7
Using connection_pool 2.2.2
Using safe_yaml 1.0.5
Using crack 0.4.3
Using orm_adapter 0.5.0
Using responders 3.0.1
Using warden 1.2.9
Using devise 4.8.0
Using unf_ext 0.0.7.5
Using unf 0.1.4
Using domain_name 0.5.20180417
Using dotenv 2.0.1
Using dotenv-rails 2.0.1
Using et-orbi 1.1.7
Using figaro 1.1.1
Using font-awesome-rails 4.7.0.4
Using sassc 2.0.1
Using font-awesome-sass 5.6.1
Using raabro 1.1.6
Using fugit 1.1.8
Using json 2.2.0
Using gelf 3.1.0
Using haml 4.0.7
Using sexp_processor 4.11.0
Using ruby_parser 3.12.0
Using html2haml 2.2.0
Using haml-rails 0.9.0
Using hashdiff 0.3.8
Using hashie 4.1.0
Using highcharts-rails 4.2.7
Using http-cookie 1.0.3
Using jaro_winkler 1.5.2
Using jbuilder 2.8.0
Using jquery-rails 4.3.3
Using turbolinks-source 5.2.0
Using turbolinks 5.0.1
Using jquery-turbolinks 2.0.2
Using jquery-ui-rails 5.0.5
Using jsonapi-resources 0.9.5
Using less 2.6.0
Using less-rails 2.8.0
Using listen 3.0.8
Using request_store 1.3.2
Using lograge 0.10.0
Using minitest-capybara 0.8.2
Using minitest-metadata 0.6.0
Using minitest-rails 3.0.0
Using minitest-rails-capybara 3.0.1
Using ruby-progressbar 1.10.0
Using minitest-reporters 1.3.6
Using mongo 2.7.1
Using mongoid 6.0.0.rc0
Using mono_logger 1.1.0
Using mustermann 1.0.3
Using netrc 0.11.0
Using rack-protection 2.0.5
Using omniauth 2.0.4
Using omniauth-oauth2 1.7.1
Using omniauth-google-oauth2 1.0.0
Using omniauth-rails_csrf_protection 1.0.0
Using parallel 1.14.0
Using parser 2.6.0.0
Using poltergeist 1.18.1
Using powerpack 0.1.2
Using pry 0.12.2
Using pry-rails 0.3.9
Using pureapi 0.5.1
Using rack-cors 1.0.2
Using rack-mini-profiler 1.0.2
Using rack_session_access 0.2.0
Using rails 5.0.7.1
Using rails-controller-testing 1.0.4
Using rails_param 0.9.0
Using rainbow 3.0.0
Using redis 3.3.5
Using redis-store 1.6.0
Using redis-rack 2.0.5
Using redis-actionpack 5.0.2
Using redis-activesupport 5.0.7
Using redis-namespace 1.6.0
Using redis-rails 5.0.2
Using sinatra 2.0.5
Using vegas 0.1.11
Using resque 2.0.0
Using twitter-bootstrap-rails 4.0.0
Using resque-web 0.0.12
Using rest-client 2.0.2
Using unicode-display_width 1.4.1
Using rubocop 0.58.2
Using rufus-scheduler 3.5.2
Using websocket 1.2.8
Using selenium-webdriver 2.48.1
Using sentry-raven 2.9.0
Using shoryuken 4.0.3
Using sidekiq 5.2.5
Using sidekiq-cron 1.1.0
Using slack-notifier 2.3.2
Using spring 2.0.2
Using spring-watcher-listen 2.0.1
Using uglifier 4.1.20
Using web-console 3.7.0
Using webmock 3.5.1
Using whenever 0.9.7
Using will_paginate 3.1.6
Using will_paginate_mongoid 2.0.1

This is config in devise.rb

config.omniauth :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'], {
    :scope => "email, profile",
    :prompt => "select_account",
    :image_aspect_ratio => "square",
    :image_size => 50,
  }

This my OmniauthCallbacksController

class Staffs::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  skip_before_action :auth_staff

  OMNIAUTH = 'omniauth.auth'
  GOOGLE = 'Google'
  OMNIAUTH_SUCCESS = 'devise.omniauth_callbacks.success'
  OMNIAUTH_FAILURE = 'devise.omniauth_callbacks.failure'
  MSG_EMAIL_NOT_OMNIAUTH = 'email chưa được xác thực'

  def google_oauth2
      # You need to implement the method below in your model (e.g. app/models/user.rb)
      @staff = Staff.from_omniauth(request.env[OMNIAUTH])
      puts "===================================>: #{@staff.to_json}"
      unless @staff.blank?
        flash[:notice] = I18n.t OMNIAUTH_SUCCESS, :kind => GOOGLE
        sign_in_and_redirect @staff, :event => :authentication
      else
        session["devise.google_data"] = request.env[OMNIAUTH].except('extra')
        @staff = Staff.create_or_sync_account_edumall(request.env[OMNIAUTH])
        unless @staff.blank?
          sign_in_and_redirect @staff, :event => :authentication
        else
          flash[:notice] = I18n.t OMNIAUTH_FAILURE, {:kind => GOOGLE, :reason => MSG_EMAIL_NOT_OMNIAUTH}
          redirect_to new_staff_session_path
        end
      end
  end
alejandrotoro commented 2 years ago

@nighttiger1990 we are having this same error, did you find a solution for it?

matthewford commented 2 years ago

We're seeing this randomly any one have a fix for this?

x8BitRain commented 1 year ago

Was experiencing this after updating to the newer Google Identity Services JS, our solution was to explicitly set the following scopes, which we were not specifying on the old JS client.

We were requesting access to the Analytics API and Search Console API but the old client would just send over whatever was needed while the new client we had to set the following scopes for it to work again.

await window.google.accounts.oauth2.initCodeClient({
        client_id: secret,
        scope:
          'email profile https://www.googleapis.com/auth/analytics.readonly https://www.googleapis.com/auth/webmasters.readonly openid https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email',
        callback: (response) => {
          ...
        },
      });
gabrielbaldao commented 1 year ago

did you find a solution for it?

johnnytomcat commented 7 months ago

This was happening to me, make sure you are returning your user in this case staff at the end of your from_omniauth function.

def self.from_omniauth(access_token)
    data = access_token.info

    Rails.logger.info "emails: #{data["email"]}"

    user = User.where(email: data["email"]).first

    unless user
      company = Company.create(name: "Default Company")
      # Uncomment the section below if you want users to be created if they don't exist
      user ||= User.create(
        name: data["name"],
        company_id: company.id,
        email: data["email"],
        password: Devise.friendly_token[0, 20],
      )
    end

    user # <------ LIKE THIS
  end
zquestz commented 4 months ago

Closing due to inactivity. Feel free to reopen if you are still having issues.