Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

Adding cookie session store back to Rails API app

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

+ include ::ActionController::Cookies

config/application.rb

+ config.middleware.insert_after ActiveRecord::QueryCache, ActionDispatch::Cookies
+ config.middleware.insert_after ActionDispatch::Cookies, ActionDispatch::Session::CookieStore

created config/initializers/secret_token.rb

+ Namespace::Application.config.secret_token = 'token'

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.

But, in my browser the cookie itself is being named as '_session_id' instead of '_namespace_key'

I thought I added back every piece required for cookie based session storage, but I appear to be missing something else. Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're on Rails 5, and want to preserve config.api_only = true you could extend the middleware to add the sessions layer, adding this code after class Application < Rails::Application in config/application.rb

config.middleware.use ActionDispatch::Cookies
config.middleware.use ActionDispatch::Session::CookieStore, key: '_namespace_key'

This could come in handy when you want to have a rails api-only enabled app but have to manage user sessions with an administration panel like ActiveAdmin or Rails_Admin.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...