Skip to content
This repository has been archived by the owner on May 16, 2021. It is now read-only.

Commit

Permalink
Ensure that session contains a csrf token after "safe" requests
Browse files Browse the repository at this point in the history
Currently, `AuthenticityToken#accepts?` will only add an authenticity
token to the session if the request is "unsafe". By default, this means
that the first POST/PUT/DELETE request from every session is guaranteed
to fail. (see: #60)

This changeset rearranges a few lines in `AuthenticityToken#accepts?` to
do conditional assignment of `session[:csrf]` every time the method is
called--even for safe requests.
  • Loading branch information
pje committed Sep 10, 2013
1 parent 04335ec commit c415d50
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/rack/protection/authenticity_token.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ class AuthenticityToken < Base
default_options :authenticity_param => 'authenticity_token'

def accepts?(env)
return true if safe? env
session = session env
token = session[:csrf] ||= session['_csrf_token'] || random_string
env['HTTP_X_CSRF_TOKEN'] == token or
safe?(env) ||
env['HTTP_X_CSRF_TOKEN'] == token ||
Request.new(env).params[options[:authenticity_param]] == token
end
end
Expand Down
5 changes: 5 additions & 0 deletions spec/authenticity_token_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,9 @@
post('/', {"csrf_param" => "a"}, 'rack.session' => {:csrf => "a"})
last_response.should be_ok
end

it "sets a new csrf token for the session in env, even after a 'safe' request" do
get('/', {}, {})
env['rack.session'][:csrf].length.should == 32
end
end

0 comments on commit c415d50

Please sign in to comment.