djangodjango-rest-frameworkjwtcorsdjango-csrf

How to secure JWT tokens with a DRF backend supporting both mobile and SPA clients?


I am developing an application that uses the Django REST Framework to provide a REST API.

I intend to protect it using token authentication, with the help of simple_jwt.

Example API overview:

From reading on CSRF I have gathered:

So far so good, however, this would mean that my REST API needs to both require CSRF tokens for requests coming from the SPA and not require/ignore CSRF tokens for requests coming from mobile app clients.

Since this is logically impossible I was first thinking of implementing 2 separate APIs. I.e.:

But doing this just means that my CSRF protection is useless, since a malicious actor can just target my mobile API instead of my SPA API.

I also read about a bit about CORS but I am not sure how it fits into all of this.

Questions:

EDIT:

I've thought about this more - what if I subclass the CSRF middleware and allow it to be bypassed if there is an Authorization header present? Then the request can be granted or denied by the authentication middleware directly (effectively I am assuming that if there is an Authorization header I am dealing with a mobile client, which does not need CSRF protection).

Is that a bad idea?

In case it isn't, then how should the LoginView look like? It should still be protected against CSRF but neither the mobile, nor the SPA clients will have a token to set as the Authorizaton header...


Solution

  • I wasn't aiming for a self-answer, but after more research and a lack of useful responses from people here I have settled on the following approach:

    Additionally:

    Token storage:

    Rationale