Re: authenticity_token sent, still InvalidAuthenticityToken

Peter De Berdt
2008-11-20T08:59:08Z

On 19 Nov 2008, at 19:16, Anjan Tek wrote:

> Thanks. I''ll look closer into that. But I was testing on Safari
(Mac)
> and not Firefox.
>
> But lately, I''ve been having more problems with the authentication
/
> session ID stuff. More of my actions started giving me the same
> error. I
> ended up just switching off the verification authenticity globally. It
> seems to be such a pain to configure when you are not using plain
> erb/rhtml web apps.
>
> And surprisingly few people seem to know about these issues.

Issues that can be overcome very easily (see below). It is a very bad
idea to disable the authenticity token, it was put in place to protect
your site from malicious attacks.

> Thanks again. I just had quick scan over that post you linked to.
I''ll
> give it a closer look.

The solution is pretty simple to be honest:

In your view layout file, add this to the section:


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


In application.js, add the following:

Ajax.Base.prototype.initialize = Ajax.Base.prototype.initialize.wrap(
   function(p, options){
     p(options);
     this.options.parameters = this.options.parameters || {};
     this.options.parameters.authenticity_token = window._token ||
'''';
   }
);

It will automatically add the authenticity token to ALL ajax requests,
even those you invoke from custom code (graceful degrading and/or even
delegated events for example).

A similar solution for those swapping out Prototype with JQuery has
been posted at http://henrik.nyh.se/2008/05/rails-authenticity-token-with-jquery

As for file uploaders, a normal field within a form (multipart=true)
will be sent as part of the form (and isn''t an ajax request in the
first place) and shouldn''t be a problem. If you are using ANY other
"ajax" uploader, there''s more to it. I already posted several
times on
how to get SWFUpload to play nicely with Rails, an overview with links
to the appropriate posts can be found here:

http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/45f70281a5992fa7


Best regards

Peter De Berdt