module Marten::Handlers::RequestForgeryProtection

Overview

Provides protection against Cross-Site Request Forgeries.

This module provides protection against Cross-Site Request Forgeries (CSRF) attacks. CSRF attacks generally involve a malicious website trying to perform actions on a web application on behalf of an already authenticated user.

The protection provided by this module works as follows: a CSRF token cookie (generated from a random secret value) is automatically prepared by a before_dispatch callback. This token cookie is then sent as part of every HTTP response if the token value was explicitly requested through the use of the #get_csrf_token method (otherwise no cookie is set). For each unsafe HTTP method (ie. methods that are not GET, HEAD, OPTIONS or TRACE), the module will verify that the CSRF token cookie is available and that a csrftoken field is present in the POST data hash, or that a X-CSRF-Token header is defined. These two token will be verified and they must match; otherwise a 403 error is returned to the user. In addition to that, the module will also verify that the HTTP request host is either part of the allowed hosts (Marten.settins.allowed_hosts setting) or that the value of the Origin header matches the configured trusted origins (Marten.settings.csrf.trusted_origins setting) - in order to protect against cross-subdomain attacks. The Referer header will also be checked for HTTPS request (if the Origin header is not set) in order to prevent subdomains to perform unsafe HTTP requests on the protected web applications (unless those subdomains are explicitly allowed as part of the Marten.settings.csrf.trusted_origins setting).

By default, handlers will use the CSRF protection by complying with what is defined as part of the Marten.settins.csrf.protection_enabled setting (whose value is true by default). It is also possible to override whether or not CSRF protection is used on a per-handler basis by using the #protect_from_forgery method.

Direct including types

Defined in:

marten/handlers/concerns/request_forgery_protection.cr

Instance Method Summary

Instance Method Detail

def get_csrf_token #

Returns a valid CSRF token to use in the context of the current handler instance.

Calling this method will force the CSRF token to be generated if it wasn't set already. It will also result in the token cookie to be set as part of the HTTP response returned by the handler.


[View source]
def referer_trusted? #

[View source]