将 cookie 会话存储添加回 Rails API 应用程序 [英] Adding cookie session store back to Rails API app
问题描述
我有一个 Rails-API 应用程序.或多或少开箱即用",但我想重新添加基于 cookie 的会话存储.这是我所做的:
I have a Rails-API app. More or less "out of the box" but I want to add back cookie-based session store. Here is what I've done:
app/controllers/application_controller.rb
app/controllers/application_controller.rb
+ include ::ActionController::Cookies
config/application.rb
config/application.rb
+ config.middleware.insert_after ActiveRecord::QueryCache, ActionDispatch::Cookies
+ config.middleware.insert_after ActionDispatch::Cookies, ActionDispatch::Session::CookieStore
创建的 config/initializers/secret_token.rb
created config/initializers/secret_token.rb
+ Namespace::Application.config.secret_token = 'token'
创建 config/initializers/session_store.rb
created config/initializers/session_store.rb
+ Namespace::Application.config.session_store :cookie_store, :key => '_namespace_key'
当我在控制器中检查会话时,结果:
When I inspect the session in a controller it results:
<Rack::Session::Abstract::SessionHash:0x3fdadc5daa24 not yet loaded>
然而,数据似乎正在被写入和使用.
However it does appear that data is being written to and used.
但是,在我的浏览器中,cookie 本身被命名为_session_id"而不是_namespace_key"
But, in my browser the cookie itself is being named as '_session_id' instead of '_namespace_key'
我以为我添加了基于 cookie 的会话存储所需的所有部分,但我似乎缺少其他内容.有什么想法吗?
I thought I added back every piece required for cookie based session storage, but I appear to be missing something else. Any ideas?
推荐答案
您需要从 application.rb
文件中删除这些中间件声明并添加:
You need to remove these middleware declarations from your application.rb
file and add this:
config.api_only = false
如果在您的初始化程序(您拥有)的某处配置了 session_store
,这将按照您想要的方式启用会话管理.这没有明确记录,但这就是你应该做的.
This will enable session management the way you want if there is a configured session_store
somewhere in your initialisers (which you have). This isn't clearly documented, but that's what you're supposed to do.
示例此处.
这篇关于将 cookie 会话存储添加回 Rails API 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!