If you step into the land of raw Ajax, however, you will need to take care of passing this value yourself (unless you are sending GET requests, you don't need to send the token with a GET request). So where do you get the value? You use the helper form_authenticity_token of course. But I don't recommend using this value directly as it can throw and exception if you call it with forgery protection turned off (in tests for example). Instead, write your own helper in app/helpers/application_helper.rb, something like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def form_auth_token | |
(protect_against_forgery?) ? form_authenticity_token : '' | |
end |
Now in your view you can write the value where you need it or you can store the value in a javascript variable for later use:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%= javascript_tag "var FORM_AUTH_TOKEN = '#{form_auth_token}';" %> |
Now when you make an Ajax request you just need to make sure you provide this value under the name "authenticity_token". For prototype.js, you can stuff this along in the options to the family of Ajax request functions:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
new Ajax.Request(url, {parameters: 'authenticity_token=' + FORM_AUTH_TOKEN}); |
If you are using the amazing Ext JS, you might send it along with something like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var store = new Ext.data.Store({ | |
baseParams: { | |
authenticity_token: FORM_AUTH_TOKEN | |
}, | |
... |
Oh, also, if you want to turn off this forgery protection you can remove it entirely by commenting out protect_from_forgery in your main application.rb controller or disable / enable it on an action by action basis in a controller with:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MondoController < ApplicationController | |
protect_from_forgery :except => [:action_one, :action_two] | |
# ... |
And of course that takes either an :except or :only value.