1

Is there a way to get the rails session cookie from the client via Java Script and then send it over an AJAX request to prove identity?

I'm trying to implement an edit to a rails model via Javascript and JQuery. I'm concerned about malicious users sending post requests to the rails app and editing models so I want to check the current_user stored in the rails session. Is it possible to send this session over AJAX and use it on the rails side?

Deekor
  • 9,144
  • 16
  • 69
  • 121
  • 1
    Cookies should already be sent in AJAX requests, unless the AJAX request is calling a different domain? – Stryner Nov 10 '15 at 18:49
  • @Stryner looks like you're right! Thanks. Do you want to post an answer? – Deekor Nov 10 '15 at 18:58
  • Not really since I just googled and regurgitated what I found at http://stackoverflow.com/questions/2870371/why-is-jquerys-ajax-method-not-sending-my-session-cookie. I would feel dirty. – Stryner Nov 10 '15 at 18:59

2 Answers2

1

You can get the CRFS token and put as a header:

JQuery

var token = $( 'meta[name="csrf-token"]' ).attr( 'content' );

$.ajaxSetup( {
  beforeSend: function ( xhr ) {
    xhr.setRequestHeader( 'X-CSRF-Token', token );
  }
}); 

Hope this helps!

Ele
  • 33,468
  • 7
  • 37
  • 75
1

It seems Rails actually handles this for you.

Deekor
  • 9,144
  • 16
  • 69
  • 121