Skip to content

Commit 25519e2

Browse files
committed
Ensure that the form authenticity token is present
Assume two users visit an action that is setup for caching. If the page is not cached when the first user hits it, the page will be generated for them and token_tag creates a session['_csrf_token'] entry for the user. Because the session var exists, the substitution can be done for the first user. When the second user hits the action, it's already cached, so token_tag won't generate a csrf_token for them. Calling form_authenticity_token instead of manually accessing the session object ensures that the token is created for the user, regardless of whether token_tag/csrf_meta_tags was called
1 parent 2464380 commit 25519e2

File tree

1 file changed

+2
-3
lines changed

1 file changed

+2
-3
lines changed

lib/cacheable-csrf-token-rails.rb

+2-3
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ def self.included(base)
99

1010
private
1111
def inject_csrf_token
12-
if protect_against_forgery? && token = session['_csrf_token']
12+
if protect_against_forgery? && token = form_authenticity_token
1313
if body_with_token = response.body.gsub!(ApplicationController::TOKEN_PLACEHOLDER, token)
1414
response.body = body_with_token
1515
end
@@ -22,7 +22,6 @@ def inject_csrf_token
2222

2323
def token_tag(token=nil)
2424
if token != false && protect_against_forgery?
25-
token ||= form_authenticity_token
2625
tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => ApplicationController::TOKEN_PLACEHOLDER)
2726
else
2827
''
@@ -42,4 +41,4 @@ def csrf_meta_tags
4241
end
4342

4443
end # included
45-
end
44+
end

0 commit comments

Comments
 (0)