mateusmaso mateusmaso - 2 years ago 96
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) =>

  • Web App =>

I can only access my API via
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
flash[:error] = I18n.t('devise.failure.invalid')
render "api/v1/base/error", :handlers => :rabl, :status => :unprocessable_entity

Answer Source

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:

  type: "POST"
  url: ""
    withCredentials: true

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download