Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save robertsosinski/945445 to your computer and use it in GitHub Desktop.
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
# 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
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