Skip to content

Instantly share code, notes, and snippets.

@tonytonyjan
Last active December 3, 2016 08:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonytonyjan/8a551a9808295287a8c3c43a6ecdaf0e to your computer and use it in GitHub Desktop.
Save tonytonyjan/8a551a9808295287a8c3c43a6ecdaf0e to your computer and use it in GitHub Desktop.
rack-protection minimal example

Usage

gem install 'rack-protection'
ruby server.rb

There's a page with 2 forms, the one without CSRF token field will get 403 Forbidden response.

Note

The middleware only accepts unsafe HTTP requests (exclude GET, HEAD, OPTIONS, TRACE) if a given access token matches the token included in the session.

It checks either X-CSRF-Token header or POST form data.

To customize the authenticity parameter for form data (default is "authenticity_token"):

use Rack::Protection::AuthenticityToken, authenticity_param: 'your_param_name'
require 'rack/protection'
csrf_param = 'token'
app = Rack::Builder.app do
use Rack::Session::Cookie, secret: 'secret'
use Rack::Protection::AuthenticityToken, authenticity_param: csrf_param
run -> (env) do
[200, {}, [
<<~EOS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>rack-protection minimal example</title>
<meta content="#{csrf_param}" name="csrf-param" />
<meta content="#{env['rack.session'][:csrf]}" name="csrf-token" />
</head>
<body>
<h1>Without Authenticity Token</h1>
<form action="" method="post">
<input type="text" name="foo">
<input type="submit">
</form>
<h1>With Authenticity Token</h1>
<form action="" method="post">
<input type="text" name="foo">
<input type="hidden" name="token" value="#{env['rack.session'][:csrf]}">
<input type="submit">
</form>
</body>
</html>
EOS
]]
end
end
Rack::Handler::WEBrick.run app
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment