I am attempting to set up a basic sessions-based authentication strategy in a Rails 5 API.
I think I'm mostly running into a configuration confusion, because a new session is generated on each request.
I've added the cookies and cookie store middleware back into the application
config/application.rb
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Only loads a smaller set of middleware suitable for API only apps.
# Middleware like session, flash, cookies can be added back manually.
# Skip views, helpers and assets when generating a new resource.
config.middleware.use ActionDispatch::Cookies
config.middleware.use ActionDispatch::Session::CookieStore
config.api_only = false
end
It seems like I have to set api_only to false or I get #<ActionDispatch::Request::Session:0x7fd40b2eec80 not yet loaded>
I added the session_store initializer and the cookie_serializer:
config/initializers/session_store.rb
Rails.application.config.session_store :cookie_store, key: '_tunr_sol_json_api_session'
config/initializers/cookie_serializer.rb
Rails.application.config.action_dispatch.cookies_serializer = :json
I'm not storing sessions in the database.
I have a sessions controller that sets a current_user_id key to the sessions object when the user is successfully authenticated.
app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def create
user = User.find_by(username: params[:user][:username])
if user && user.authenticate(params[:user][:password])
session[:current_user_id] = user.id
render json: {status: 201, message: "session created", user: user}
else
render json: {status: 401, message: "unauthorized"}
end
end
def destroy
session[:current_user_id] = nil
render json: {status: 204, message: "no content"}
end
end
The behavior
The auth strategy I have set up with bcrypt and has_secure_password works. And in looking at the session in sessions#create it successfully sets the user id to the session.
But the session doesn't seem to persist or get stored in the browser. sessionStorage after login has a length of 0
When I log out and check the session, it creates a new session.
Question
Not sure what configuration I'm missing or have wrong to get this functionality set up with the api.