【发布时间】:2021-03-27 07:53:08
【问题描述】:
我创建了一个 Rails 应用程序,我将其用作 api 应用程序(带有角度前端)。当我尝试在SessionsController#create 上创建会话时,我正在设置session[:user_id] 并返回一个用户对象。我的前端应用程序已成功获取此对象并将浏览器重定向到 #/dashboard。 DashboardComponent 有一个守卫,它调用我的SessionsController#logged_in,它检查我的 Rails 应用程序中的会话。当我在本地运行时,这没有问题。但是,当部署到 Heroku 时,session[:user_id] 是空的。我不确定我做错了什么。我知道这不是 CORS 或 CSRF 问题,因为我的客户端应用程序获取了用户对象(我正在将其记录到控制台)。
这是我的initializers/session_store.rb
if Rails.env == "production"
Rails.application.config.session_store :cookie_store, key: "_myapp", domain: "api-app.herokuapp.com"
else
Rails.application.config.session_store :cookie_store, key: "_myapp"
end
只是为了好玩,这是我的initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins "http://localhost:4200", "https://angular-app.herokuapp.com"
resource "*",
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head],
credentials: true
end
end
SessionsController.rb
class SessionsController < ApplicationController
include CurrentUserConcern
def create
user = User
.find_by(email: params["email"])
.try(:authenticate, params["password"])
if user
session[:user_id] = user.id
render json: user, status: :created
else
head :unauthorized
end
end
def logged_in
if @current_user
render json: @current_user, status: :ok
else
head :no_content
end
end
def logout
reset_session
head :no_content
end
end
current_user_concern.rb
module CurrentUserConcern
extend ActiveSupport::Concern
included do
before_action :set_current_user, only: [:logged_in]
end
def set_current_user
puts session[:user_id]
if session[:user_id]
@current_user = User.find(session[:user_id])
end
end
end
我可以提供任何其他可能有帮助的代码
【问题讨论】:
-
cookie 没有在 api 域 (api-app.herokuapp.com) 和 angular 域 (angular-app.herokuapp.com) 之间共享。它总是看起来像 api 应用程序的新会话。需要更新 Rails.application.config.session_store 以跨子域工作。 stackoverflow.com/questions/10402777/… 一些提示,可能需要设置 tld_length。
-
我将
session_store.rb上的生产配置修改为:Rails.application.config.session_store :cookie_store, key: "_myapp", domain: :all, tld_length: 2,但这并没有解决我的问题。 -
未添加 cookie。我还尝试将我的客户端应用程序域添加到 session_store,如下所示:
Rails.application.config.session_store :cookie_store, key: "_myapp", domain: "thawing-river-95379.herokuapp.com", tld_length: 2,但它也没有效果 -
调用 api 登录的 Angular 代码是什么样的?猜测它对cookie没有任何作用,打赌你需要设置它。
标签: ruby-on-rails heroku