Techioz Blog

エラー – オムニ認証: (google_oauth2) 認証失敗

概要

Rails アプリにオムニ認証の Google、Facebook、Twitter によるログインを追加する必要があります 私は、github の公式ドキュメントのオムニ認証チュートリアルに従います。しかし、利用可能なリソースがありません API のみのアプリですが、私は初心者なので、バックエンドのみに関する有用なリソースが見つかりませんでした。この任務を達成するのを手伝ってください。 コードを提供して、正しい方法を案内します。 http://localhost:3000/users/auth/google_oauth2/callback で郵便配達員から API リクエストをヒットし、しばらく取得したときのサーバーのログです。

2023-09-12 18:49:21 +0530 ::1 の POST “/users/auth/google_oauth2” を開始しました D、[2023-09-12T18:49:21.941614 #38273] デバッグ –omniauth: (google_oauth2) リクエスト フェーズが開始されました。 E、[2023-09-12T18:49:21.943750 #38273] エラー –omniauth: (google_oauth2) 認証失敗! ActionController::InvalidAuthenticityToken: ActionController::InvalidAuthenticityToken、ActionController::InvalidAuthenticityToken Users::OmniauthCallbacksController#failure による処理 /

そしてしばらくして

2023-09-12 19:08:53 +0530 ::1 の GET “/users/auth/google_oauth2/callback” を開始しました D、[2023-09-12T19:08:53.125607 #39856] デバッグ –omniauth: (google_oauth2) コールバック フェーズが開始されました。 E、[2023-09-12T19:08:53.128328 #39856] エラー –omniauth: (google_oauth2) 認証失敗!未定義のメソッドの有効期限が切れましたか? nil:NilClass: NoMethodError の場合、未定義のメソッドの有効期限が切れていますか? nilの場合:NilClass Users::OmniauthCallbacksController#failure による処理 /

コントローラ

# frozen_string_literal: true
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  respond_to :json
  skip_before_action :verify_authenticity_token
  skip_before_action :authenticate_request
  protect_from_forgery with: :null_session

  def handle_omniauth(provider)
    @user = User.from_omniauth(request.env["omniauth.auth"])
    
    if @user.persisted?
      render json: { status: 'success', message: "Successfully authenticated via #{provider.capitalize}", user: @user }
    else
      render json: { status: 'error', message: 'Authentication failed', errors: @user.errors.full_messages }, status: :unprocessable_entity
    end
  end
  
  def google_oauth2
    handle_omniauth('Google')
  end

  def twitter
    handle_omniauth('Twitter')
  end

  def facebook
    handle_omniauth('Facebook')
  end
end

モデル

class User < ApplicationRecord
  # Devise modules
  devise :database_authenticatable, :registerable, :confirmable,
         :recoverable, :rememberable, :validatable, :trackable,
         :omniauthable, omniauth_providers: [:google_oauth2, :twitter, :facebook]

  # OmniAuth callback method to create or find a user
  def self.from_omniauth(auth)
    user = User.find_by(email: auth.info.email)

    if user
      user.update(provider: auth.provider, uid: auth.uid)
    else
      user = User.create(
        provider: auth.provider,
        uid: auth.uid,
        email: auth.info.email,
        password: Devise.friendly_token[0, 20]
      )
    end

    user
  end
end

Device.rb と credentials.yml で認証情報を設定しました デバッグしようとしましたが、デバッガで制御が届きません。

 devise_for :users, controllers: {
    omniauth_callbacks: 'users/omniauth_callbacks'
    registrations: 'users/registrations',
    sessions: 'users/sessions',
    passwords: 'users/passwords'
  }

ルートが明確に定義されており、 しかし、まだオムニ認証でログインできません。

**gems are **
# Authentication
gem 'devise'
gem 'omniauth'
gem 'omniauth-facebook'
gem 'omniauth-google-oauth2'
gem 'omniauth-twitter'
gem 'omniauth-rails_csrf_protection'

サードパーティのログインを追加したいのですが、エラーが発生します。

解決策

https://translate.google.com/translate?hl=ja&sl=en&tl=ja&u=https://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html

Rails のドキュメントには、protect_from_forgery によって次の行が追加されると記載されています。

    before_action :verify_authenticity_token, options

他の行と競合しています

skip_before_action :verify_authenticity_token

自分で生成したフォームではなく、サードパーティからのコールバックを期待しているため、このコンテキストでは信頼性トークンは意味がありません。

:null_session を使用して行 protected_from_forgery を削除する必要があります。 そして何が起こるか見てみましょう