mateusmaso mateusmaso - 7 months ago 24
Javascript Question

Set-Cookie session not being set after sign_in with cross-domain

I have a rails app that has 2 subdomains:


  • API (CORS) =>
    api.myapp.dev

  • Web App =>
    myapp.dev



I can only access my API via
auth_token
which is returned right after user's authentication using Devise. However, my client (web app) is not setting these cookies. Am I missing something?

class Api::V1::SessionsController < Api::V1::BaseController

def create
@user = User.find_for_database_authentication(:email => params[:user][:email])

if @user and @user.valid_password?(params[:user][:password])
sign_in @user # Set-Cookie header response with the session
render "api/v1/users/preview", :handlers => :rabl # return auth_token here
else
flash[:error] = I18n.t('devise.failure.invalid')
render "api/v1/base/error", :handlers => :rabl, :status => :unprocessable_entity
end
end
end

Answer

Well, I found the problem. For security reasons, you can't set cookies from Cross-Domain websites. So, you have to make sure to configure withCredentials options on jquery ajax:

$.ajax
  type: "POST"
  url: "api.mydomain.com/login"
  xhrFields:
    withCredentials: true

Also, make sure to return headers['Access-Control-Allow-Credentials'] = "true" on your response.