How do I set a cookie when responding to a request of type application/json in Rails?
The controller action works as expected but there is no cookie being set and there is no Set-Cookie header in the response. Any help will be greatly appreciated.
Controller:
class SessionsController < ApplicationController
def create
@user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in(user)
.
.
cookies[:test] = 'Test cookie'
render json: @user
#render json: @user, set_cookie: 'test' #Also tried this
else
render text: 'Wrong username and/or password', status: 401
end
end
end
Route:
Rails.application.routes.draw do
.
.
resources :sessions, :defaults => { :format => :json }
end
Can you set cookie in GET request? To add cookies to a request for authentication, use the header object that is passed to the get/sendRequest functions. Only the cookie name and value should be set this way.
To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons.
set() The set() method of the cookies API sets a cookie containing the specified cookie data. This method is equivalent to issuing an HTTP Set-Cookie header during a request to a given URL. The call succeeds only if you include the "cookies" API permission in your manifest.
I am encountering the same problem. Here is how I solved:
response.set_cookie "name", "nic"
I also came up with the cause of the problem. It is the forgery protection that null the session just before the response is composed.
To use the cookies
methods, you need to skip the auth validation of the token:
skip_before_action :verify_authenticity_token
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With