Skip to content

Commit 9b5bc5b

Browse files
authored
add option for per-session CSRF token (#105)
1 parent 120bee3 commit 9b5bc5b

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

spec/csrf_spec.cr

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,22 @@ describe "CSRF" do
112112
client_response.status_code.should eq 403
113113
client_response.body.should eq "Error from handler"
114114
end
115+
116+
it "does not change the token when per_session is set" do
117+
handler = Kemal::Session::CSRF.new(per_session: true)
118+
request = HTTP::Request.new("POST", "/first",
119+
body: "foo=bar",
120+
headers: HTTP::Headers{"Content-Type" => "application/x-www-form-urlencoded"})
121+
io, context = process_request(handler, request)
122+
first_response = HTTP::Client::Response.from_io(io, decompress: false)
123+
first_token = context.session.string("csrf")
124+
request = HTTP::Request.new("POST", "/second",
125+
body: "authenticity_token=#{first_token}",
126+
headers: HTTP::Headers{"Content-Type" => "application/x-www-form-urlencoded",
127+
"Cookie" => first_response.headers["Set-Cookie"]})
128+
io, context = process_request(handler, request)
129+
context.session.string("csrf").should eq first_token
130+
end
115131
end
116132

117133
def create_request_and_return_io(handler, request)

src/kemal-session/csrf.cr

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ module Kemal
1616
@allowed_routes = [] of String,
1717
@http_only : Bool = false,
1818
@samesite : HTTP::Cookie::SameSite? = nil,
19+
@per_session : Bool = false,
1920
)
2021
setup
2122
end
@@ -54,7 +55,7 @@ module Kemal
5455
end
5556
current_token = context.session.string("csrf")
5657
if current_token == submitted
57-
context.session.string("csrf", Random::Secure.hex(16))
58+
context.session.string("csrf", Random::Secure.hex(16)) unless @per_session
5859

5960
return call_next(context)
6061
else

0 commit comments

Comments
 (0)