環境
- Rails ver6.1.5
- Ruby ver2.7.5
事象
deviseならびにomniauthを使用したTwitterログインを実装したいが
403認証エラーが発生しログインページにアクセスできない。
(twitter) Request phase initiated.
(twitter) Authentication failure! 403 Forbidden: OAuth::Unauthorized, 403 Forbidden
omniauth用各種設定を済ませ、localhost:4000/api/v1/auth/twitter
もしくはhttp://127.0.0.1:4000/api/v1/auth/twitter
へアクセスした際に上記エラーが発生し
Twitterのログインページへのアクセスができない状態。
コード
Gemfile
gem 'devise_token_auth'
gem 'omniauth'
gem 'omniauth-twitter'
Routes
namespace :api do
namespace :v1 do
devise_scope :user_authentication do
get 'sign_in', :to => 'devise/sessions#new', :as => :new_user_session
get 'sign_out', :to => 'devise/sessions#destroy', :as => :destroy_user_session
end
mount_devise_token_auth_for 'UserAuthentication', at: 'auth', controllers: {
omniauth_callbacks: 'api/v1/auth/omniauth_callbacks'
}
end
end
config/initializers/omniauth.rb
# 開発用にGETリクエストを許可しています
OmniAuth.config.allowed_request_methods = [:post, :get]
OmniAuth.config.logger = Rails.logger
Rails.application.config.middleware.use OmniAuth::Builder do
provider :twitter,
Rails.application.credentials.authentication[:twitter_key],
Rails.application.credentials.authentication[:twitter_key_secret],
callback_url: "http://127.0.0.1:4000/api/v1/auth/twitter/callback"
end
application_controller.rb
...
include DeviseTokenAuth::Concerns::SetUserByToken
...
# APIでページがない場合は必要とのことなので追加
def new_session_path(scope)
new_user_session_path
end
user_authentication.rb
# schema
#
# Table name: user_authentications
#
# id :bigint not null, primary key
# user_id :bigint not null
# provider :string(191) default("email"), not null
# uid :string(191) default(""), not null
# remember_created_at :datetime
# sign_in_count :integer default(0), not null
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string(255)
# last_sign_in_ip :string(255)
# tokens :text(65535)
#
class UserAuthentication < ApplicationRecord
acts_as_paranoid
extend Devise::Models
devise :rememberable, :trackable, :omniauthable, omniauth_providers: [:twitter]
include DeviseTokenAuth::Concerns::User
belongs_to :user
end
api/v1/auth/omniauth_callbacks_controller.rb
class Api::V1::Auth::OmniauthCallbacksController < DeviseTokenAuth::OmniauthCallbacksController
def twitter
callback_from :twitter
end
def failure
redirect_to root_path
end
private
def callback_from(provider)
# ここでuser_authenticationレコードを作成したい
end
end
config/initializers/devise_token_auth.rb
DeviseTokenAuth.setup do |config|
# By default the authorization headers will change after each request. The
# client is responsible for keeping track of the changing tokens. Change
# this to false to prevent the Authorization header from changing after
# each request.
config.change_headers_on_each_request = false
# By default, users will need to re-authenticate after 2 weeks. This setting
# determines how long tokens will remain valid after they are issued.
config.token_lifespan = 2.weeks
# Limiting the token_cost to just 4 in testing will increase the performance of
# your test suite dramatically. The possible cost value is within range from 4
# to 31. It is recommended to not use a value more than 10 in other environments.
config.token_cost = Rails.env.test? ? 4 : 10
...
# Makes it possible to change the headers names
config.headers_names = {
:'access-token' => 'access-token',
:'client' => 'client',
:'expiry' => 'expiry',
:'uid' => 'uid',
:'token-type' => 'token-type'
}
...
end
実装方針
twitterでのログイン方法を調べたところ、userテーブルに情報を集約する方法が多く紹介されていますが
apiが返すテーブルからログイン情報を切り離したいため、userテーブルには名前程度の情報のみを持たせ
user_authenticationテーブルにログイン情報を持たせたい。
そのためuser_authenticationに対してdeviseオプションを適応し
そちらでコールバック等を設計しておきたい。
メールアドレス・パスワードでのログインは必要なし
試したこと
api_key等の確認
- 入力内容に違いはなし
- 念の為再発行したものを設定しても変化なし
- コンソールから直接credentialsを参照すると問題なく値が取得できる
callback_urlの設定
- omniauth.rbにprovider情報とともにcallback_urlを設定
- localhost:4000ならびにhttp://127.0.0.1:4000どちらでも変化なし
- twitterAPI側の設定も双方を設定済み
routesの修正
- namespaceが良くないとの情報もあったので、scopeへ変更
scope :api do
scope :v1 do
...
end
end
- この場合もエラーが発生しアクセスできない
- さらに他の単にレコードを返すエンドポイントへも.../api/v1/hogehogeでアクセスできなくなる
このような状況でtwitterでのログイン実装がうまく行かず困っています。
その他必要な情報があれば追記しますので、よろしくお願いします。