Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions spec/csrf_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,22 @@ describe "CSRF" do
client_response.status_code.should eq 403
client_response.body.should eq "Error from handler"
end

it "does not change the token when per_session is set" do
handler = Kemal::Session::CSRF.new(per_session: true)
request = HTTP::Request.new("POST", "/first",
body: "foo=bar",
headers: HTTP::Headers{"Content-Type" => "application/x-www-form-urlencoded"})
io, context = process_request(handler, request)
first_response = HTTP::Client::Response.from_io(io, decompress: false)
first_token = context.session.string("csrf")
request = HTTP::Request.new("POST", "/second",
body: "authenticity_token=#{first_token}",
headers: HTTP::Headers{"Content-Type" => "application/x-www-form-urlencoded",
"Cookie" => first_response.headers["Set-Cookie"]})
io, context = process_request(handler, request)
context.session.string("csrf").should eq first_token
end
end

def create_request_and_return_io(handler, request)
Expand Down
3 changes: 2 additions & 1 deletion src/kemal-session/csrf.cr
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ module Kemal
@allowed_routes = [] of String,
@http_only : Bool = false,
@samesite : HTTP::Cookie::SameSite? = nil,
@per_session : Bool = false,
)
setup
end
Expand Down Expand Up @@ -54,7 +55,7 @@ module Kemal
end
current_token = context.session.string("csrf")
if current_token == submitted
context.session.string("csrf", Random::Secure.hex(16))
context.session.string("csrf", Random::Secure.hex(16)) unless @per_session

return call_next(context)
else
Expand Down