Plug.CSRFProtection

Plug to protect from cross-site request forgery.

For this plug to work, it expects a session to have been previously fetched. It will then compare the plug stored in the session with the one sent by the request, when they do not match, an Plug.CSRFProtection.InvalidCSRFTokenError error is raised.

The token may be sent by the request either via the params with key “_csrf_token” or a header with name “x-csrf-token”.

GET requests are not protected, as they should not have any side-effect or change your application state. JavaScript requests are an exception: by using a script tag, external websites can embed server-side generated JavaScript, which can leak information. For this reason, this plug also forbids any GET JavaScript request that is not XHR (or AJAX).

Token generation

This plug won’t generate tokens automatically. Instead, tokens will be generated only when required by calling Plug.CSRFProtection.get_csrf_token/0. The token is then stored in the process dictionary to be set in the request.

One may wonder: why the process dictionary?

The CSRF token is usually generated inside forms which may be isolated from the connection. Storing them in process dictionary allow them to be generated as a side-effect, becoming one of those rare situations where using the process dictionary is useful.

Disabling

You may disable this plug by doing Plug.Conn.put_private(:plug_skip_csrf_protection, true).

Examples

plug Plug.Session, ...
plug :fetch_session
plug Plug.CSRFProtection
Source

Summary

call(conn, opts)

Callback implementation for Plug.call/2

delete_csrf_token()

Deletes the CSRF token from the process dictionary

get_csrf_token()

Gets the CSRF token

init(opts)

Callback implementation for Plug.init/1

Functions

call(conn, opts)

Callback implementation for Plug.call/2.

Source
delete_csrf_token()

Deletes the CSRF token from the process dictionary.

This will force the token to be deleted once the response is sent.

Source
get_csrf_token()

Gets the CSRF token.

Generates a token and stores it in the process dictionary if one does not exists.

Source
init(opts)

Callback implementation for Plug.init/1.

Source