I'm using nuxt for front-end, phoenix/elixir for API server, and nginx for reverse-proxy.
I've hit the wall when I tried to make a form for uploading files.
How do I work with the csrf
?
I'm using nuxt for front-end, phoenix/elixir for API server, and nginx for reverse-proxy.
I've hit the wall when I tried to make a form for uploading files.
How do I work with the csrf
?
CSRF provides a lot of security benefits, especially for session-based web applications, so it might make sense for you to keep using it (if you aren't using something like auth-token instead). This can usually get a bit complicated in frontend SPAs, but the basic process is to:
Render the CSRF token (usually in a hidden field or JS variable) using get_csrf_token/0
on your webpage on the initial request
Read the value and send it back to the server in the X-CSRF-TOKEN
request header in your subsequent ajax calls
Regenerate a new CSRF token on the server after sometime and send it back in the response headers of an existing request or in the response of a dedicated request just for the token
Save it in your webapp for the next non-GET
request
(Assuming that your SPA isn't a completely separate frontend project and is atleast partially server-rendered)
Here are some other resources:
If you aren't using sessions in your phoenix-framework API server (and using something like auth tokens, for example), the simplest option would be to disable CSRF. You can do that by removing the :protect_from_forgery
plug from your Router pipeline:
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
# plug :protect_from_forgery ## REMOVE THIS
end
Note: SPAs generally use the :api
pipeline, where this is excluded by default
If you're only interacting with your backend via AJAX, you can disable CSRF protection in favour of requiring a custom request header, per OWASP's advice.