Rails中Devise登录后无法重定向至用户子域名页面问题
问题:Rails集成Apartment+Devise登录后跨子域名重定向失败
我开发了一个基于Rails框架、集成Apartment和Devise的应用。除从www.lvh.me/...路径登录的场景外,其他功能均正常。登录后本应重定向至用户对应的子域名页面,系统虽尝试执行该操作,但最终仍停留在登录页。
请求日志
#尝试重定向至根路径 Started POST "/users/sign_in" for 127.0.0.1 at 2022-11-05 12:57:13 +0100 Processing by Users::SessionsController#create as TURBO_STREAM Parameters: {"authenticity_token"=>"[FILTERED]", "user"=>{"email"=>"chris@gmail.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"} User Load (0.3ms) SELECT "public"."users".* FROM "public"."users" WHERE "public"."users"."email" = $1 ORDER BY "public"."users"."id" ASC LIMIT $2 [["email", "christ@gmail.com"], ["LIMIT", 1]] ↳ app/controllers/Users/sessions_controller.rb:13:in `create' Redirected to http://chris.lvh.me:3000/ Completed 302 Found in 207ms (ActiveRecord: 0.3ms | Allocations: 1479) Started OPTIONS "/" for 127.0.0.1 at 2022-11-05 12:57:13 +0100 ActionController::RoutingError (No route matches [OPTIONS] "/"): #尝试重定向至members_path Started POST "/users/sign_in" for 127.0.0.1 at 2022-11-05 13:02:06 +0100 Processing by Users::SessionsController#create as TURBO_STREAM Parameters: {"authenticity_token"=>"[FILTERED]", "user"=>{"email"=>"christ@gmail.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"} User Load (0.2ms) SELECT "public"."users".* FROM "public"."users" WHERE "public"."users"."email" = $1 ORDER BY "public"."users"."id" ASC LIMIT $2 [["email", "chris@gmail.com"], ["LIMIT", 1]] ↳ app/controllers/Users/sessions_controller.rb:13:in `create' Redirected to http://chris.lvh.me:3000/members Completed 302 Found in 218ms (ActiveRecord: 3.2ms | Allocations: 5039) Started OPTIONS "/members" for 127.0.0.1 at 2022-11-05 13:02:06 +0100 ActionController::RoutingError (No route matches [OPTIONS] "/members"):
修改后的Sessions控制器代码
class Users::SessionsController < Devise::SessionsController # before_action :configure_sign_in_params, only: [:create] # POST /resource/sign_in def create self.resource = warden.authenticate!(auth_options) set_flash_message!(:notice, :signed_in) sign_in(resource_name, resource) yield resource if block_given? # respond_with resource, location: after_sign_in_path_for(resource) redirect_to(members_url(subdomain: resource.subdomain) , allow_other_host: true) end end
路由配置代码(routes.rb)
#routes.rb class SubdomainConstraint def self.matches?(request) subdomains = %w{ www admin } request.subdomain.present? && !subdomains.include?(request.subdomain) end end Rails.application.routes.draw do devise_for :users, controllers: {sessions: 'users/sessions', registrations: 'users/registrations'} # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html # Defines the root path route ("/") # root "articles#index" root "members#index" constraints SubdomainConstraint do resources :members end end
补充说明:手动在浏览器输入带子域名的URL时,路由功能正常。
内容的提问来源于stack exchange,提问作者marcellobonini
相关产品推荐
相关产品推荐

