Phoenix - Invalid CSRF (Cross Site Forgery Protection) token error

Paul B picture Paul B · Feb 18, 2015 · Viewed 10.4k times · Source

I am receiving an Invalid CSRF token error when trying to update (or create) a record. I am using Elixir v1.0.3, Erlang/OTP 17 [erts-6.3], and Phoenix v0.8.0 (I think, I am not sure how to check Phoenix's version). I am creating a web app mostly following the Phoenix guides and the Elixir Dose Jobsite Example resources. However, when I try to post information from an html form, I get the Invalid CSRF token error. Following the advice given in the error, I added 'x-csrf-token': csrf_token to the action.

edit.html.eex:

<h2>Edit Directory</h2>
<form class="form-horizontal" action="<%= directory_path @conn, :update, @directory.id, 'x-csrf-token': @csrf_token %>" method="post">
  <div class="form-group">
    <label for="directory" class="col-sm-2 control-label">Directory</label>
    <div class="col-sm-10">
      <input type="hidden" name="_method" value="PATCH">
      <input type="text" class="form-control" value="<%= @directory.directory %>" name="directory" placeholder="Directory" required="required">
    </div>
  </div>
...

but I receive the following error:

[error] #PID<0.579.0> running Ainur.Endpoint terminated
Server: localhost:4000 (http)
Request: POST /config/directories/2?x-csrf-token=
** (exit) an exception was raised:
    ** (Plug.CSRFProtection.InvalidCSRFTokenError) Invalid CSRF (Cross Site Forgery Protection) token. Make sure that all your non-HEAD and non-GET requests include the csrf_token as part of form params or as a value in your request's headers with the key 'x-csrf-token'
        (plug) lib/plug/csrf_protection.ex:54: Plug.CSRFProtection.call/2
        (ainur) web/router.ex:4: Ainur.Router.browser/2
        (ainur) lib/phoenix/router.ex:2: Ainur.Router.call/2
        (plug) lib/plug/debugger.ex:104: Plug.Debugger.wrap/3
        (phoenix) lib/phoenix/endpoint/error_handler.ex:43: Phoenix.Endpoint.ErrorHandler.wrap/3
        (ainur) lib/ainur/endpoint.ex:1: Ainur.Endpoint.phoenix_endpoint_pipeline/2
        (plug) lib/plug/debugger.ex:104: Plug.Debugger.wrap/3
        (phoenix) lib/phoenix/endpoint/error_handler.ex:43: Phoenix.Endpoint.ErrorHandler.wrap/3

As far as I can tell (being new to Elixir, Phoenix, and HTML), "action" is essentially a path and any parameters I place in it will find their way back to the application. And, indeed, I find that x-csrf-token = "" is passed back to the router, so @csrf_token must not be correct. I am not sure exactly where the csrf_token comes from, so I do not know how to reference it (or perhaps I am doing this completely wrong).

Any ideas would be greatly appreciated.

Answer

Tsuharesu picture Tsuharesu · May 12, 2015

On version 0.13 of Phoenix you can do

<input type="hidden" name="_csrf_token" value="<%= get_csrf_token() %>">

because on file web/web.ex there's an import of this function.