JWT auth in cookies with stateless server and no server side rendering

Viewed 780

I am trying to implement jwt in cookies for auth on a single page application react front end which communicates with various node microservices running express.

I am doing this as it appears storing the jwt in sessionstorage makes the app vulnerable to XSS.

However, by using cookies, the apis are now vulnerable to csrf attacks.

Traditionally, csrf attacks are mitigated by creating a csrf token, storing it in a server session, then rendering it in a hidden form field. Then, upon submitting the form, the value of the csrf token is checked against the server session value to check they match.

I cannot use this approach as: - servers are stateless - have no server side rendering.

So I am confused as to which csrf method I should employ. I have read about double submit method, where you submit a csrf token on every ajax request, and have the same value stored in a cookie, then the server checks both for a match.

However, I cannot get the intial csrf token into the html in the first place as there is no server side rendering.

What is the best practice for achieving jwt in cookies with csrf protection in a stateless architecture with no server side rendering?

1 Answers

Simply don't store the JWT token in a cookie

CSRF attacks are possible because browsers will send cookies with HTTP requests, even if they are initiated by a script running on a 3rd party site. Thus evilsite.com might send a DELETE http://yoursite.com/items/1 request to your web service. This endpoint requires you to be logged in, but because the browser will send any cookies stored for yoursite.com, if authentication is cookie based then evilsite.com can piggy back on your authentication method and call authenticated methods that your user didn't intend to call on their behalf.

However, authentication doesn't have to be cookie based. If you are creating a client-rendered JavaScript app, then it is simple to send the authentication token as an HTTP header rather than in a cookie. If you do this then it is impossible for evilsite.com to make use of your token (they can only use tokens stored in cookies), and you never have the problem in the first place.

Related