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?
.
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
andhanami-helpers
:_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.
Hash[ Action::GET => true, Action::HEAD => true, Action::TRACE => true, Action::OPTIONS => true ].freeze
Class Method Summary collapse
- .included(action) ⇒ Object private
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.
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 |