Merge pull request #38098 from mltsy/patch-1

Document how to add session middleware to an API app
This commit is contained in:
Rafael França 2019-12-27 11:08:45 -03:00 committed by GitHub
commit 0105fd4a1e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 21 additions and 4 deletions

View File

@ -331,6 +331,27 @@ will be:
{ :person => { :firstName => "Yehuda", :lastName => "Katz" } }
```
### Using Session Middlewares
The following middlewares, used for session management, are excluded from API apps since they normally don't need sessions. If one of your API clients is a browser, you might want to add one of these back in:
- `ActionDispatch::Session::CacheStore`
- `ActionDispatch::Session::CookieStore`
- `ActionDispatch::Session::MemCacheStore`
The trick to adding these back in is that, by default, they are passed `session_options`
when added (including the session key), so you can't just add a `session_store.rb` initializer, add
`use ActionDispatch::Session::CookieStore` and have sessions functioning as usual. (To be clear: sessions
may work, but your session options will be ignored - i.e the session key will default to `_session_id`)
Instead of the initializer, you'll have to set the relevant options somewhere before your middleware is
built (like `application.rb`) and pass them to your prefered middleware, like this:
**application.rb:**
```ruby
config.session_store :cookie_store, key: '_interslice_session' # <-- this also configures session_options for use below
config.middleware.use ActionDispatch::Cookies # Required for all session management (regardless of session_store)
config.middleware.use config.session_store, config.session_options
```
### Other Middleware
Rails ships with a number of other middleware that you might want to use in an
@ -339,10 +360,6 @@ API application, especially if one of your API clients is the browser:
- `Rack::MethodOverride`
- `ActionDispatch::Cookies`
- `ActionDispatch::Flash`
- For session management
* `ActionDispatch::Session::CacheStore`
* `ActionDispatch::Session::CookieStore`
* `ActionDispatch::Session::MemCacheStore`
Any of these middleware can be added via: