Class: Rack::Protection::AuthenticityToken

Inherits:
Base
  • Object
show all
Defined in:
lib/rack/protection/authenticity_token.rb

Overview

Prevented attack

CSRF

Supported browsers

all

More infos

en.wikipedia.org/wiki/Cross-site_request_forgery

This middleware only accepts requests other than GET, HEAD, OPTIONS, TRACE if their given access token matches the token included in the session.

It checks the X-CSRF-Token header and the POST form data.

Compatible with the rack-csrf gem.

Options

:authenticity_param

the name of the param that should contain the token on a request. Default value: "authenticity_token"

Example: Forms application

To show what the AuthenticityToken does, this section includes a sample program which shows two forms. One with, and one without a CSRF token The one without CSRF token field will get a 403 Forbidden response.

Install the gem, then run the program:

gem install 'rack-protection'
ruby server.rb

Here is server.rb:

require 'rack/protection'

app = Rack::Builder.app do
  use Rack::Session::Cookie, secret: 'secret'
  use Rack::Protection::AuthenticityToken

  run -> (env) do
    [200, {}, [
      <<~EOS
        <!DOCTYPE html>
        <html lang="en">
        <head>
          <meta charset="UTF-8" />
          <title>rack-protection minimal example</title>
        </head>
        <body>
          <h1>Without Authenticity Token</h1>
          <p>This takes you to <tt>Forbidden</tt></p>
          <form action="" method="post">
            <input type="text" name="foo" />
            <input type="submit" />
          </form>

          <h1>With Authenticity Token</h1>
          <p>This successfully takes you to back to this form.</p>
          <form action="" method="post">
            <input type="hidden" name="authenticity_token" value="#{env['rack.session'][:csrf]}" />
            <input type="text" name="foo" />
            <input type="submit" />
          </form>
        </body>
        </html>
      EOS
    ]]
  end
end

Rack::Handler::WEBrick.run app

Example: Customize which POST parameter holds the token

To customize the authenticity parameter for form data, use the :authenticity_param option:

use Rack::Protection::AuthenticityToken, authenticity_param: 'your_token_param_name'

Direct Known Subclasses

FormToken, RemoteToken

Constant Summary collapse

TOKEN_LENGTH =
32

Constants inherited from Base

Base::DEFAULT_OPTIONS

Instance Attribute Summary

Attributes inherited from Base

#app, #options

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#call, #default_options, default_options, default_reaction, #deny, #drop_session, #encrypt, #html?, #initialize, #instrument, #origin, #random_string, #react, #referrer, #report, #safe?, #secure_compare, #session, #session?, #warn

Constructor Details

This class inherits a constructor from Rack::Protection::Base

Class Method Details

.random_tokenObject



94
95
96
# File 'lib/rack/protection/authenticity_token.rb', line 94

def self.random_token
  SecureRandom.base64(TOKEN_LENGTH)
end

.token(session) ⇒ Object



90
91
92
# File 'lib/rack/protection/authenticity_token.rb', line 90

def self.token(session)
  self.new(nil).mask_authenticity_token(session)
end

Instance Method Details

#accepts?(env) ⇒ Boolean

Returns:

  • (Boolean)


98
99
100
101
102
103
104
105
106
# File 'lib/rack/protection/authenticity_token.rb', line 98

def accepts?(env)
  session = session env
  set_token(session)

  safe?(env) ||
    valid_token?(session, env['HTTP_X_CSRF_TOKEN']) ||
    valid_token?(session, Request.new(env).params[options[:authenticity_param]]) ||
    ( options[:allow_if] && options[:allow_if].call(env) )
end

#mask_authenticity_token(session) ⇒ Object



108
109
110
111
# File 'lib/rack/protection/authenticity_token.rb', line 108

def mask_authenticity_token(session)
  token = set_token(session)
  mask_token(token)
end