Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: Set a cookie in a request/response if type is JSON?

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
like image 337
Corey Quillen Avatar asked Feb 19 '15 23:02

Corey Quillen


People also ask

Can you set cookie in GET request?

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.

How do I send a cookie in a post request?

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.

How do I set cookies in API?

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.


1 Answers

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
like image 61
ciaoben Avatar answered Oct 01 '22 01:10

ciaoben