CSRFToken error when using a form

I get this error when trying to post a message:

Plug.CSRFProtection.InvalidCSRFTokenError at POST /message
invalid CSRF (Cross Site Request Forgery) token, please make sure that:

  * The session cookie is being sent and session is loaded
  * The request include a valid '_csrf_token' param or 'x-csrf-token' header

my html looks like this:

<form action="/message" method="POST">
  <label for="name">message</label>
  <input type="text" id="text" name="mess" value="fdfas"><br><br>
</form>

my plugs:

pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_live_flash
    plug :put_root_layout, {AllnumWeb.LayoutView, :root}
    plug :protect_from_forgery
    plug :put_secure_browser_headers
  end

I’ve tried this;

<%= form_for @conn, Routes.message_path(@conn, :create), fn f -> %>
  <!-- Form fields -->
  <%= text_input f, :content %>
  <%= submit "Submit" %>
<% end %>

but then I get a strange error:

expected closing " for attribute value

any suggestions?

Do you not have <%= csrf_meta_tag() %> in your layout file(s)? Or anywhere in your templates? If not, then the CSRF token error you are getting is very normal.

What does your calculated HTML source show in the browser?

I put <%= csrf_meta_tag() %> on top of my index.html.ex file where the input form is, but the error message is still the same

Is it inside the form?

yes:

<form action="/message" method="POST">
  <label for="name">message</label>
  <%= csrf_meta_tag() %>
  <input type="hidden" name="_csrf_token" value="<%= get_csrf_token() %>">
  <input type="text" id="text" name="mess" value="fdfas"><br><br>
</form>

Do not put the csrf_meta_tag() inside the form.

Either you need to use the <.form> (dot form) tag (that would automatically put the csrf field in your form). Or you would need to have an input field with name _csrf_token and value = Phoenix.Controller.get_csrf_token().

<input type="hidden" name="_csrf_token" value={Phoenix.Controller.get_csrf_token()}>

thanks, that removed the csr token error

You could also use Phoenix.Component.form, which automatically adds the csrf token in such a hidden input.

1 Like