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

Only accepts unsafe HTTP requests if a given access token matches the token included in the session.

Compatible with rack-csrf.

Options:

authenticity_param: Defines the param’s name that should contain the token on a request.

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



30
31
32
# File 'lib/rack/protection/authenticity_token.rb', line 30

def self.random_token
  SecureRandom.base64(TOKEN_LENGTH)
end

.token(session) ⇒ Object



26
27
28
# File 'lib/rack/protection/authenticity_token.rb', line 26

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

Instance Method Details

#accepts?(env) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
37
38
39
40
41
42
# File 'lib/rack/protection/authenticity_token.rb', line 34

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



44
45
46
47
# File 'lib/rack/protection/authenticity_token.rb', line 44

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