Skip to content

Commit

Permalink
Add option to configure token session key
Browse files Browse the repository at this point in the history
  • Loading branch information
jkowens committed Jan 5, 2021
1 parent 9f397eb commit e511500
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
12 changes: 10 additions & 2 deletions rack-protection/lib/rack/protection/authenticity_token.rb
Expand Up @@ -24,6 +24,13 @@ module Protection
# the token on a request. Default value:
# <tt>"authenticity_token"</tt>
#
# [<tt>:key</tt>] the name of the param that should contain
# the token in the session. Default value:
# <tt>:csrf</tt>
#
# [<tt>:allow_if</tt>] a proc for custom allow/deny logic. Default value:
# <tt>nil</tt>
#
# == Example: Forms application
#
# To show what the AuthenticityToken does, this section includes a sample
Expand Down Expand Up @@ -85,6 +92,7 @@ class AuthenticityToken < Base
TOKEN_LENGTH = 32

default_options :authenticity_param => 'authenticity_token',
:key => :csrf,
:allow_if => nil

def self.token(session)
Expand Down Expand Up @@ -113,7 +121,7 @@ def mask_authenticity_token(session)
private

def set_token(session)
session[:csrf] ||= self.class.random_token
session[options[:key]] ||= self.class.random_token
end

# Checks the client's masked token to see if it matches the
Expand Down Expand Up @@ -177,7 +185,7 @@ def compare_with_real_token(token, session)
end

def real_token(session)
decode_token(session[:csrf])
decode_token(session[options[:key]])
end

def encode_token(token)
Expand Down
Expand Up @@ -59,6 +59,17 @@
expect(env['rack.session'][:csrf]).not_to be_nil
end

it "allows for a custom token session key" do
mock_app do
use Rack::Session::Cookie, :key => 'rack.session'
use Rack::Protection::AuthenticityToken, :key => :_csrf
run DummyApp
end

get '/'
expect(env['rack.session'][:_csrf]).not_to be_nil
end

describe ".token" do
it "returns a unique masked version of the authenticity token" do
expect(Rack::Protection::AuthenticityToken.token(session)).not_to eq(masked_token)
Expand Down

0 comments on commit e511500

Please sign in to comment.