いつもお世話になっております。
Ruby on Rails APIモードにて、Google認証を実装したいと考えているのですがエラーで苦戦しております。
OmniAuth::Strategies::OAuth2::CallbackError csrf_detected | CSRF detected
このエラーは、Googleのログイン画面に飛んでからログインしようとすると生じてしまいます。
開発環境
rails 5.2.1
omniauth-google-oauth2
(deviseは使っていません)
ソースコードは下記となります
omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do provider :google_oauth2, Rails.application.credentials.google[:google_client_id], Rails.application.credentials.google[:google_client_secret] end
user.rb
class User < ApplicationRecord def self.from_omniauth(auth) where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user| user.provider = auth.provider user.uid = auth.uid user.name = auth.info.name user.email = auth.info.email user.image = auth.info.image user.oauth_token = auth.credentials.token user.oauth_expires_at = Time.at(auth.credentials.expires_at) return user end end end
sessions_controller.rb
class SessionsController < ApplicationController def new end def create @user = User.from_omniauth(request.env["omniauth.auth"]) if @user.save session[:user_id] = user.id render json: "succesfully login.\n", status: 200 else render json: "fail to login.\n", status: 500 end end def destroy session[:user_id] = nil render json: "succesfully logout.\n", status: 200 end end
application.rb
・・・ config.api_only = true config.middleware.use ActionDispatch::Flash config.middleware.use ActionDispatch::Cookies config.middleware.use ActionDispatch::Session::CookieStore config.middleware.insert_before 0, Rack::Cors do allow do origins 'http://localhost:3000' resource '*', :headers => :any, :methods => [:get, :post, :patch, :delete, :options] end end end end
routes.rb
Rails.application.routes.draw do get 'auth/:provider/callback', to: 'sessions#create' get 'auth/failure', to: redirect('/') get 'signout', to: 'sessions#destroy', as: 'signout' resources :sessions, only: [:new, :create, :destroy] end

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。