Kemal::Session::CSRF::Handler
Inherits HTTP::Handler < Reference < Object
Verifies every unsafe request, raising InvalidAuthenticityToken when
verification fails. Protecting the whole app by default, and exempting
deliberately, is what Rails does — the route you forget to protect is the
one that gets abused.
use Kemal::Session::CSRF::Handler.new
Register an error handler for the response, or Kemal renders its generic 500 (the dev exception page outside production). Rails answers 422:
error Kemal::Session::InvalidAuthenticityToken do |env|
env.response.status_code = 422
"Invalid authenticity token"
end
Exempt the routes that cannot carry a token — a webhook, or an API
authenticated by a header rather than the session cookie (except entries
are matched against the request path: strings exactly, regexes by pattern):
use Kemal::Session::CSRF::Handler.new(except: ["/webhooks/stripe", /\A\/api\//])
skip covers what a path can't express; returning true bypasses the check:
handler = Kemal::Session::CSRF::Handler.new
handler.skip = ->(env : HTTP::Server::Context) do
!!env.request.headers["Authorization"]?.try(&.starts_with?("Bearer "))
end
use handler
Constructors
Instance methods
Extra bypass predicate, consulted when except doesn't match.