What's the best way to implement JWT authentication for a DRF API serving both mobile and web clients?

I’m building an API with Django REST Framework and I want to use JWT for user authentication. The challenge is to support both mobile apps and web SPAs at the same time.

Here’s my plan for the API:

  • /login: a POST endpoint that accepts a username and password and returns JWT tokens
  • /refresh: a POST endpoint that takes a refresh token to issue a new access token
  • /secure-endpoint: an endpoint that requires a valid access token

I’m unsure about handling CSRF because web apps need CSRF protection (due to cookies) and mobile apps do not. Should I consider separate endpoints for web and mobile? For example, /web/login and /mobile/login. But then, CSRF protection might be bypassed by targeting the mobile endpoint.

Other questions on my mind:

  • Is it possible to avoid using cookies in web apps and still maintain a secure session?
  • How can I properly store and handle CSRF tokens in this context?
  • What is the best approach to setting up CSRF with DRF?
  • Can CORS settings help resolve these conflicts?

I also thought about allowing CSRF checks to be bypassed when there is an Authorization header present. Does that sound like a good solution?

Any guidance on ensuring secure JWT handling for both types of clients would be greatly appreciated.

From my experience working with DRF and JWT authentication, I’d recommend using a single set of endpoints for both mobile and web clients. Instead of creating separate endpoints, you can leverage the flexibility of JWT tokens.

For web apps, store the JWT in HttpOnly cookies and implement CSRF protection. For mobile, use the Authorization header. Your API can check for the presence of a JWT in both places.

To handle CSRF, use Django’s built-in CSRF protection for cookie-based auth, but exempt API endpoints that use header-based auth. This approach maintains security while accommodating both client types.

For web apps, consider using a combination of short-lived access tokens and secure HttpOnly cookies for refresh tokens. This balances security and user experience.

Remember to implement proper token revocation and rotation strategies. Also, ensure your CORS settings are correctly configured to allow requests from your web app’s domain.

hey there! have u considered using a token-based approach for both mobile and web? it could simplify things. maybe store tokens in localstorage for web apps? curious about ur thoughts on that. also, how bout implementing rate limiting to prevent abuse? what security measures are u planning besides JWT?

yo, i’ve dealt with this before. instead of separate endpoints, use a middleware to check for JWT in both headers and cookies. That way, you can handle mobile and web with one setup. For CSRF, enable it for cookie auth but skip for header auth. Just make sure ur CORS is tight. good luck!