InvalidAuthenticityToken Error in Rails

Working with a RESTful API in Rails can be a bit challenging at times.  One such problem is the ActionController::InvalidAuthenticityToken error.  This error is thrown when authenticity token is not present or invalid.  (This is how Rails protects itself from CSRF.) This token should only be checked with HTML and AJAX requests.  XML requests do not need this check.  However, if the following code is run:

$ curl -d "<status>...</status>" -X POST http://localhost:3000/statuses.xml

the InvalidAuthenticityToken error is raised.  The problem stems from an incorrect content type.  If you force the content type in the header:

$ curl -H "Content-Type: application/xml" -d "<status>...</status>" -X POST http://localhost:3000/statuses.xml

everything works as expected. This turns out to be a gotcha since GET requests don’t need the header.

This entry was posted in Technology and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">