[英]Authenticate Devise User Before Accessing Omniauth Routes
我正在開發一個應用程序,它對我的用戶記錄使用設計,對用戶擁有的記錄使用 omniauth,而不是對用戶記錄使用典型的 omniauth + devise。 我正在嘗試將設計的用戶身份驗證添加到 omniauth 路由/auth/:provider
以便非注冊訪問者無法訪問這些路由並觸發特定提供商的身份驗證過程。
我已經能夠通過使用設備的authenticate_user!
用戶向回調添加身份authenticate_user!
Sessions 控制器中的 helper 方法,所以我至少阻止了非注冊訪問者能夠從 omniauth 流創建記錄,但我希望設計的用戶身份驗證在 omniauth 流的所有階段工作。
關於如何將設計的用戶身份驗證添加到初始 omniauth 路由的任何想法,無論是使用類似於我當前的解決方案還是通過我的 routes.rb 文件使用設計的authenticate :user do
?
這個解決方案對我有用。 它實際上創建了一個新路由,該路由檢查用戶當前是否已登錄,然后將其重定向到所請求提供者的授權路徑。
route.rb:
scope module: :authentication do
devise_scope :user do
# ...
get 'users/auth/:provider/setup', to: 'omniauth_callbacks#before_request_phase'
end
# ...
end
omniauth_callbacks_controller.rb:
def before_request_phase
authorize_path = send("user_#{params[:provider]}_omniauth_authorize_path".to_s)
if current_user.present?
redirect_to(authorize_path)
else
redirect_to login_path(return_to: authorize_path)
end
end
遇到相同問題的所有人的解決方案:
在request_phase中進行Devise身份驗證。 如果您使用的是策略工具,例如omniauth-facebook,則可以在初始化程序中(例如在config/initializers/omniauth.rb
猴子修補該特定策略:
module FacebookExtension
include Devise::Controllers::Helpers
def request_phase
# it might be 'admin_user_signed_in?' depends on what your user model is
if user_signed_in?
super
else
# redirect to any path you think is suitable once devise authentication fail
redirect Rails.application.routes.url_helpers.new_admin_user_session_path
end
end
end
OmniAuth::Strategies::Facebook.prepend FacebookExtension
我正在尋找一種解決方案,使我能夠在提供者的基礎上進行身份驗證。 以下示例對我有用。
在config/initializers/omniauth.rb
:
OmniAuth.config.before_request_phase = lambda do |env|
env['warden'].authenticate! if env['omniauth.strategy'].options.authenticate?
end
Rails.application.config.middleware.use OmniAuth::Builder do
provider :your_provider,
Rails.application.credentials.dig(:your_provider, :secret_id),
Rails.application.credentials.dig(:your_provider, :secret_key),
authenticate?: true
end
如果要對所有提供者進行身份驗證,只需刪除authenticate?
策略選項和before_request_phase
調用中的檢查。
添加設備autheticate_user!
在應用程序控制器中。 或使用before filter
在omniauth身份驗證方法之前調用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.