Module: Hanami::Action::CSRFProtection Private

Defined in:
lib/hanami/action/csrf_protection.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

CSRF Protection

This security mechanism is enabled automatically if sessions are turned on.

It stores a “challenge” token in session. For each “state changing request” (eg. POST, PATCH etc..), we should send a special param: _csrf_token.

If the param matches with the challenge token, the flow can continue. Otherwise the application detects an attack attempt, it reset the session and Hanami::Action::InvalidCSRFTokenError is raised.

We can specify a custom handling strategy, by overriding #handle_invalid_csrf_token.

Form helper (#form_for) automatically sets a hidden field with the correct token. A special view method (#csrf_token) is available in case the form markup is manually crafted.

We can disable this check on action basis, by overriding #verify_csrf_token?.

Examples:

Custom Handling

module Web::Controllers::Books
  class Create < Web::Action
    def handl(*)
      # ...
    end

    private

    def handle_invalid_csrf_token
      Web::Logger.warn "CSRF attack: expected #{ session[:_csrf_token] }, was #{ params[:_csrf_token] }"
      # manual handling
    end
  end
end

Bypass Security Check

module Web::Controllers::Books
  class Create < Web::Action
    def handle(*)
      # ...
    end

    private

    def verify_csrf_token?(req, res)
      false
    end
  end
end

See Also:

Since:

  • 0.4.0

Constant Summary collapse

CSRF_TOKEN =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

Session and params key for CSRF token.

This key is shared with hanami-controller and hanami-helpers

Since:

  • 0.4.0

:_csrf_token
IDEMPOTENT_HTTP_METHODS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

Idempotent HTTP methods

By default, the check isn’t performed if the request method is included in this list.

Since:

  • 0.4.0

Hash[
  Action::GET => true,
  Action::HEAD => true,
  Action::TRACE => true,
  Action::OPTIONS => true
].freeze

Class Method Summary collapse

Class Method Details

.included(action) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Since:

  • 0.4.0



91
92
93
94
95
96
97
98
# File 'lib/hanami/action/csrf_protection.rb', line 91

def self.included(action)
  unless Hanami.respond_to?(:env?) && Hanami.env?(:test)
    action.include Hanami::Action::Session
    action.class_eval do
      before :set_csrf_token, :verify_csrf_token
    end
  end
end