2008年3月24日 星期一

AJAX in Rails with Authenticity Token

这是一篇很重要的转载文章。

如何从Rails框架中全部去掉Authenticity Token 功能:

注释掉Application Controller中的protect_from_forgery语句。

When you use active_record_store instead of the cookie-based default, you need to uncomment the line in controllers/application.rb that says protect_from_forgery :secret => ‘blah’. This makes sure all your HTML and JavaScript requests are coming from your web application. It essentially protects you from something called “Cross-site request forgery” by embedding a token into your web forms.

As a side note, it’s really not giving you much security at all, but that might be better left for another blog post.


I was banging my head against the wall yesterday trying to figure out why a custom Ajax.Updater wasn’t working and I kept getting an ActionController::InvalidAuthenticityToken exception. I decided to dig into the request_forgery_protection.rb file in actionpack-*/lib/action_controller and found that for custom requests, you need to include the authenticity_token yourself by taking advantage of the form_authenticity_token helper. When building the updater’s request url I just added “&authenticity_token=<%= form_authenticity_token %>” to the end and everything was fine.

Another way would be to not use the forgery protection at all for that action by including this in your controller: protect_from_forgery :except => :updater

You can also completely remove forgery protection from a controller by doing skip_before_filter :verify_authenticity_token

Back to the vulnerability of your web forms: I imagine this does protect your web application from someone hosting a form on their site that posts to your site. However, if someone really wants to spam some stuff they’ll scrape your page with cookies enabled on their scraping software, scrape your form’s fields (which include the authenticity_token hidden field) and POST to their heart’s desire.

0 评论:

 
(L)1984 - 2007 TONY CHEUNG