Plug v1.4.0 Plug.CSRFProtection View Source
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 to determine
the validity of the request. For an invalid request the action
taken is based on the
The token may be sent by the request either via the params with key “_csrf_token” or a header with name “x-csrf-token”.
Note that it is recommended to enable CSRFProtection whenever a session is used, even for JSON requests. For example, Chrome had a bug that allowed POST requests to be triggered with arbitrary content-type, making JSON exploitable. More info: https://bugs.chromium.org/p/chromium/issues/detail?id=490015
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 the process dictionary allows them to be generated as a side-effect, becoming one of those rare situations where using the process dictionary is useful.
:session_key- the name of the key in session to store the token under
:with- should be one of
:clear_session. Defaults to
:exception- for invalid requests, this plug will raise
:clear_session- for invalid requests, this plug will set an empty session for only this request. Also any changes to the session during this request will be ignored.
You may disable this plug by doing
Plug.Conn.put_private(:plug_skip_csrf_protection, true). This was made
available for disabling
Plug.CSRFProtection in tests and not for dynamically
Plug.CSRFProtection in production code. If you want specific routes to
Plug.CSRFProtection, then use a different stack of plugs for that route that
does not include
plug Plug.Session, ... plug :fetch_session plug Plug.CSRFProtection
Link to this section Summary
Link to this section Functions
Deletes the CSRF token from the process dictionary.
This will force the token to be deleted once the response is sent.
Gets the CSRF token.
Generates a token and stores it in the process dictionary if one does not exist.