views:

41

answers:

1

I recently switched to Google closure for a new project. I am having trouble adding the authenticity token to the headers in a ajax call. How do i go about it?

My Ajax snippet (using goog.net.XhrIo class):

var initialHTMLContent = superField[i].getCleanContents();

var data = goog.Uri.QueryData.createFromMap(new goog.structs.Map({
  body: initialHTMLContent
 }));

 goog.net.XhrIo.send('/blogs/create', function(e) {
    var xhr = /** @type {goog.net.XhrIo} */ (e.target);
    alert(xhr.getResponseXml());
 }, 'POST', data.toString(), {
    'Accept' : 'text/xml'
            });

Using rails in the backend.

UPDATE:

Log:

Processing BlogsController#create (for 127.0.0.1 at 2010-06-29 20:18:46) [PUT]
  Parameters: {"authenticity_token"=>""}

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):


Rendered rescues/_trace (272.4ms)
Rendered rescues/_request_and_response (1.2ms)
Rendering rescues/layout (unprocessable_entity)
+2  A: 

Somewhere in a rails view (.html.erb file) you can set a js variable like this:

window._token = '<%= form_authenticity_token %>';

And then append it in your call:

 goog.net.XhrIo.send('/blogs/create?authenticity_token=' + window._token, function(e) {
    var xhr = /** @type {goog.net.XhrIo} */ (e.target);
    alert(xhr.getResponseXml());
 }, 'POST', data.toString(), {
    'Accept' : 'text/xml'
            });
neutrino
I get a `#<Mongrel::HttpParserError: Invalid HTTP format, parsing fails.>`. Maybe its not taking the auth token into account? I have updated my question with the log.
Shripad K
I've updated the answer accordingly. Seems you have this call in a plain javascript file. You need generate the token on the server, so you need to do this in a view.
neutrino
I updated my question. Its not taking the auth token into account what so ever.
Shripad K
OK taking your queue i got to this point: I had to pass the `<%= form_authenticity_token %>` as a variable from a method i created in the html.erb file to the goog.net.XhrIo instance method in my complied js. But the authenticity token is visible when i view the source code in the browser. Is that not potentially dangerous? I give you a upvote for having shown me the right direction. But i will accept your answer if your solution does not have me worrying about security. :)
Shripad K
to calm your doubts, just observe the sources of any usual form generated by `form_for` helpers :) the main thing about authenticity token is that it's unique, there's nothing wrong with it being visible. refer to http://guides.rubyonrails.org/security.html, section 3.1
neutrino
Thank you :) Will accept your answer. Thanks also for that link. I have not looked into the security aspects in the rails guides. Have a reason to look into now.
Shripad K