Module: Hanami::Action::CSRFProtection

Defined in:
gems/gems/hanami-1.3.3/lib/hanami/action/csrf_protection.rb

Overview

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
    include Web::Action

    def call(params)
      # ...
    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
    include Web::Action

    def call(params)
      # ...
    end

    private

    def verify_csrf_token?
      false
    end
  end
end

See Also:

Since:

  • 0.4.0