Invalid csrf token even though it exists

Hello, I’m having a hard time understanding why I’m getting the error:

invalid CSRF (Cross Site Request Forgery) token, make sure all requests include a valid '_csrf_token' param or 'x-csrf-token' header

Even though the form has a _csrf_token field with the value of Plug.CSRFProtection.get_csrf_token().

I tried setting it directly in the form like:
<input type="hidden" name="_csrf_token" value="<%= @token %>">

And using the form_for function which auto generates the csrf token.

In both cases, the token is there, however, when I post the form, I always get the Plug.CSRFProtection.InvalidCSRFTokenError exception stating that a valid token should be present.

For extra context, my pipeline is:

pipeline :browser do
  plug :accepts, ["html"]
  plug :fetch_session
  plug :fetch_flash
  plug :protect_from_forgery
  plug :put_secure_browser_headers
  plug MyApp.Plugs.SubdomainPlug
end

Any help would be appreciated.

EDIT
I’m using the following:
phoenix 1.4.9
phoenix_html 2.13.3
plug 1.8.2

Solved weirdly enough almost immediately after posting the original post.

I had the following in endpoint.ex:

plug Plug.Session,
  domain: ".production-name.com",
  store: :cookie,
  key: "_kashout_key",
  signing_salt: "some_salt"

Changed the domain option to the local domain (e.g. .production-name.dev) and the csrf token was validated correctly.

Struggled with this for a few days until I removed the :protect_from_forgery plug from the pipeline to continue development.

It would be nice if phoenix could warn me about this while in dev environment. Either way I’m glad this is over now and hopefully it would help someone else down the road.

5 Likes