Wednesday, February 25, 2009

Rails Authenticity Tokens

Rails uses authenticity tokens to verify that requests which modify data are coming from an authentic session with the requester.

When you use form_for in your view, a hidden authenticity_token is inserted for you, containing a long string used to validate your session. In certain conditions, notably AJAX, you may not use form_for and may get an InvalidAuthenticityToken exception, thrown from verify_authenticity_token.

Many articles suggest turning off protect_from_forgery where you need to, using a :only option. I would think twice before doing this. Instead, work to get a valid authenticity token into your request.

First, if you have a form handy, you have to put it into your prototype Ajax.Request as a parameter:
token = el.getAttribute('value')
new Ajax.Request('/lesson_plans/update/'+parent_id, {
method: 'put',
parameters: 'course_sequence=' + newval + "&authenticity_token=" + token
});

Here, the authenticity token is taken from element el, and added as a parameter to the Ajax.Request.

If you do not have a form handy, you can add your own, using the helper form_authenticity_token in your view:

<div token="<%= protect_against_forgery?() ? form_authenticity_token() : "" %>">


This will produce an authenticity token (identical to one which would appear in a form) and places it in a token attribute of a div if forgery protection is activated. Using a method similar to above, the attribute may be extracted and added to the request.

Happy coding

No comments: