4

We are building a Angular 2 web app based on a Symfony 3 REST API (with FosRestBundle). We are using statefull JWTs to authenticate users between the backend and the frontend.

We are now currently thinking about CSRF and we're wondering if it's right to use CSRF token in addition to JWT. We read that in the FosRestBundle documentation :

When building a single application that should handle forms both via HTML forms as well as via a REST API, one runs into a problem with CSRF token validation. In most cases it is necessary to enable them for HTML forms, but it makes no sense to use them for a REST API. For this reason there is a form extension to disable CSRF validation for users with a specific role. This of course requires that REST API users authenticate themselves and get a special role assigned.

And we read some other StackOverflow questions about that too (see here and here for example).

My question is quite simple: why is it not recommended to use CSRF tokens with REST APIs? We do not understand how the JWTs can protect for CSRF attacks.

Thanks :-)

Community
  • 1
  • 1
arnaud-k
  • 110
  • 8

1 Answers1

5

First of all, "stateful JWT" is an oxymoron. To quote the introduction to JWT:

Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization header using the Bearer schema. The content of the header should look like the following:

Authorization: Bearer <token>

This is a stateless authentication mechanism as the user state is never saved in server memory. The server's protected routes will check for a valid JWT in the Authorization header, and if it's present, the user will be allowed to access protected resources.

Authentication with JWT, if done properly, renders CSRF tokens obsolete. This is because CSRF attacks rely on browsers storing your cookies, and sending them with each request to the server. However, when clicking a button in a forged form that triggers a POST request, this request will never contain the Authorization header, so it will be treated by the server as unauthorized.

Community
  • 1
  • 1
Bartosz Zasada
  • 3,762
  • 2
  • 19
  • 25