Search code examples
ruby-on-railsajaxcookiestomcat8

Not able to store cookie in browser from controller


I am using in server side rails and front end only html and accessing ruby controller by ajax from html pages.

and my html files are deployed on tomcat and i am doing cross domain ajax request

my Response in browser have complete header with all details. Still not setting cookie in Browser.

Access-Control-Allow-Credentials:true
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS 
Access-Control-Allow-Origin:  localhost:8080  
Access-Control-Max-Age:1728000 
Cache-Control:max-age=0, private, must-revalidate 
Connection:close  
Content-Type:application/json; charset=utf-8
ETag:"08499f242d03267cf0777a855aacf33e" 
Server:thin 1.6.2 codename Doc Brown
Set-Cookie:request_method=POST; path=/
Set-Cookie:remember_token=oKk0zsjd4BpyXC_39k0rUA; path=/; expires=Wed, 26 Jul 2034 15:05:51 -0000
Vary:Origin
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Request-Id:111f78ff-0dc8-4926-b301-a7e58f655619
X-Runtime:0.280800
X-UA-Compatible:chrome=1
X-XSS-Protection:1; mode=block

if some one is aware about this scenario please suggest me ..

Thanks in advance


Solution

  • You have an interesting setup. I'm wondering what is preventing you from hosting your entire site on top of the rails instance. There will be some browser security settings that your users need to enable that are off by default. This would cause me discomfort if I were using the site. Be that as it may, it sounds like you have CORS enabled on your rails app already. I'm assuming that you're using at least jQuery 1.5+. The two settings you need in your ajax call are crossDomain: true and xhrFields : { withCredentials : true }. Your ajax should look something like this:

    $.ajax({
      'url' : 'your_cross_domain_url',
      'data' : {},
      'type' : 'POST',
      'crossDomain : true,
      'xhrFields' : {
        'withCredentials' : true
      },
      success: function(data){
        //do stuff
      },
      error: function(data) {
        // do other stuff
      }
    });
    

    Additionally, your users will probably need to enable this setting:

    Chrome > Settings > Advanced Settings > Privacy > Content Settings > Block third-party cookies and site data

    Safari > Preferences > Privacy > Block cookies and other website data > Never

    Other browsers > not sure