Froze rails gems
[depot.git] / vendor / rails / railties / doc / guides / source / actioncontroller_basics / csrf.txt
1 == Request Forgery Protection ==
2
3 Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying or deleting data on that site without the user's knowledge or permission. The first step to avoid this is to make sure all "destructive" actions (create, update and destroy) can only be accessed with non-GET requests. If you're following RESTful conventions you're already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that's where the request forgery protection comes in. As the name says, it protects from forged requests. The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access.
4
5 If you generate a form like this:
6
7 [source, ruby]
8 -----------------------------------------
9 <% form_for @user do |f| -%>
10 <%= f.text_field :username %>
11 <%= f.text_field :password -%>
12 <% end -%>
13 -----------------------------------------
14
15 You will see how the token gets added as a hidden field:
16
17 [source, html]
18 -----------------------------------------
19 <form action="/users/1" method="post">
20 <div><!-- ... --><input type="hidden" value="67250ab105eb5ad10851c00a5621854a23af5489" name="authenticity_token"/></div>
21 <!-- Fields -->
22 </form>
23 -----------------------------------------
24
25 Rails adds this token to every form that's generated using the link:../form_helpers.html[form helpers], so most of the time you don't have to worry about it. If you're writing a form manually or need to add the token for another reason, it's available through the method `form_authenticity_token`:
26
27 .Add a JavaScript variable containing the token for use with Ajax
28 -----------------------------------------
29 <%= javascript_tag "MyApp.authenticity_token = '#{form_authenticity_token}'" %>
30 -----------------------------------------
31
32 The link:../security.html[Security Guide] has more about this and a lot of other security-related issues that you should be aware of when developing a web application.