1

I'm using 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?

Sheharyar
  • 73,588
  • 21
  • 168
  • 215
HelloWorld
  • 973
  • 2
  • 9
  • 23

3 Answers3

5

Use 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 instead). This can usually get a bit complicated in frontend SPAs, but the basic process is to:

  1. Render the CSRF token (usually in a hidden field or JS variable) using get_csrf_token/0 on your webpage on the initial request

  2. Read the value and send it back to the server in the X-CSRF-TOKEN request header in your subsequent calls

  3. 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

  4. 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:

Sheharyar
  • 73,588
  • 21
  • 168
  • 215
  • I'm using cookie-session, doesn't cookie-session offer enough security? – HelloWorld Dec 12 '18 at 11:21
  • Depends on your use-case, but the short answer is 'No'. To make things easier for SPAs, I would personally recommend to disable CSRF, and instead use auth tokens. You should explicitly send the auth token in request header for each ajax call you make. – Sheharyar Dec 12 '18 at 23:17
  • Two ways to go: a) If it's a completely separate SPA, auth token would be the better choice. b) If the frontend is server-rendered with a few Nuxt/Vue components sprinkled at different places, then stick with CSRF. – Sheharyar Dec 12 '18 at 23:26
  • Thanks for the tip! – HelloWorld Dec 13 '18 at 10:03
0

Disable CSRF

If you aren't using sessions in your 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

Sheharyar
  • 73,588
  • 21
  • 168
  • 215
0

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.

Tobias Fünke
  • 2,034
  • 3
  • 24
  • 38