前提
フロントエンド:Vue(localhost:8080)
バックエンド:RailsAPI(localhost:3000)
以下の教材を使ってLineのようなチャットアプリを作成後、機能を追加中。
https://www.techpit.jp/courses/195/curriculums/198/sections/1313/parts/5296
APIでの認証には
deviseとdevise_token_authを使ってトークン認証を実装していました。
omniauthとomniauth-twitterを使ってTwitter認証を実装中にエラーが発生しました。
実現したいこと
- Twitter認証
発生している問題・エラーメッセージ
Access to XMLHttpRequest at 'https://api.twitter.com/oauth/authorize?oauth_token=-FolHQAAAAABhEN5AAABg452l40' (redirected from 'http://localhost:3000/auth/twitter?use_authorize=true') from origin 'http://localhost:8080' 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.
該当のソースコード
Gemfile
1# 認証部分など 2gem 'rack-cors' 3gem 'devise', '~> 4.8', '>= 4.8.1' 4gem 'devise_token_auth', '~> 1.2' 5gem 'omniauth', '1.9.1' 6gem 'omniauth-twitter'
Welcome.vue
1// Twitter認証のフロント部分 2async authTwitter () { 3 this.error = null 4 console.log("try!!!") 5 try { 6 // ここでAPIに通信を送る 7 const res = await axios.get('http://localhost:3000/auth/twitter', {}) 8 if (!res) { 9 throw new Error('Twitterアカウントを登録できませんでした') 10 } 11 if (!this.error) { 12 setItem(res.headers, res.data.data.name) 13 this.$emit('redirectToChatRoom') 14 } 15 console.log({ res }) 16 return res 17 } catch (error) { 18 this.error = 'アカウントを登録できませんでした' 19 } 20 }
omniauth_callbacks_controller.rb
1# フロントからのリクエストを受けるController 2class Auth::OmniauthCallbacksController < DeviseTokenAuth::OmniauthCallbacksController 3 skip_before_action :skip_session 4 5 def redirect_callbacks 6 super 7 end 8 9 def omniauth_success 10 super 11 update_auth_header 12 end 13 14 def omniauth_failure 15 super 16 end 17 #以下省略 18end
試したこと
https://qiita.com/ngron/items/7ff5a1114e8e3daaa243
この記事を見て発生しているエラーは、TwitterAPIのCORS設定によるものでこちら側ではどうしようもないものだと理解したものの、RailsAPIとVue環境下でのTwitter認証を実装する手段がよくわかりません。
いくつか記事を見てもバックエンド側の実装のみでフロントの実装方法は見当たりませんでした。
(https://qiita.com/natsukingdom-yamaguchi/items/15142bd4ad77679afb04
https://qiita.com/AQeNku/items/94485432184257799106 )
お力添えよろしくお願いします。
補足情報(FW/ツールのバージョンなど)
ruby '2.7.1'
rails (6.0.5.1)
あなたの回答
tips
プレビュー