Created
April 27, 2011 23:14
-
-
Save robertsosinski/945445 to your computer and use it in GitHub Desktop.
Rack middleware and form tag patch to insert csrf tokens into cached pages
This file contains hidden or 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
# NOTE: Remember to add "before_filter :form_authenticity_token" to ApplicationController | |
# and patch ActionView::ActionView::FormTagHelper#token_tag in form_tag_helper.rb | |
class CachingWithRequestForgeryProtection | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
status, headers, response = @app.call(env) | |
if response.is_a? ActionController::Response | |
response.body = response.body.gsub("__CROSS_SITE_REQUEST_FORGERY_PROTECTION_TOKEN__", response.instance_variable_get(:@session)[:_csrf_token]) | |
headers["Content-Length"] = response.body.length.to_s | |
end | |
[status, headers, response] | |
end | |
end |
This file contains hidden or 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
module ActionView | |
module Helpers | |
module FormTagHelper | |
alias_method :token_tag_RAILS, :token_tag | |
# Make all forms generate the same forgery_protection_token so that | |
# they can be replaced by Rack before being sent back to the user. | |
def token_tag | |
unless protect_against_forgery? | |
'' | |
else | |
tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => "__CROSS_SITE_REQUEST_FORGERY_PROTECTION_TOKEN__") | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment