Skip to content

Instantly share code, notes, and snippets.

@cmer
Forked from jamesbebbington/application_controller.rb
Created September 13, 2012 19:13
Show Gist options
  • Save cmer/3716862 to your computer and use it in GitHub Desktop.
Save cmer/3716862 to your computer and use it in GitHub Desktop.
Rack middleware and form tag patch to insert csrf tokens into cached pages
# Originally from http://www.jarrodspillers.com/2010/02/06/trying-to-use-rails-csrf-protection-on-cached-actions-rack-middleware-to-the-rescue/
# Updated for rails 3
#
# 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
TOKEN_PLACEHOLDER = "__CROSS_SITE_REQUEST_FORGERY_PROTECTION_TOKEN__"
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(TOKEN_PLACEHOLDER, env["rack.session"][:_csrf_token])
headers["Content-Length"] = response.body.length.to_s
end
[status, headers, response]
end
end
# From http://www.jarrodspillers.com/2010/02/06/trying-to-use-rails-csrf-protection-on-cached-actions-rack-middleware-to-the-rescue/
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
if protect_against_forgery?
tag(
:input, :type => "hidden",
:name => request_forgery_protection_token.to_s,
:value => CachingWithRequestForgeryProtection::TOKEN_PLACEHOLDER
)
else
''
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment