aesmail
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
Marked As Solved
aesmail
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.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








