Securing React frontend with RESTful API: JWT and CSRF concerns

I’m working on a React app that uses a RESTful API backend. I’m worried about security, especially with JWT tokens and CSRF protection. Here’s what I’m thinking:

  1. Get JWT from API after login
  2. Store JWT in HttpOnly cookie
  3. Send cookie with API requests for auth
  4. API checks for XMLHttpRequest header
  5. API reads JWT from cookie and does its thing

Is this safe? I’m not sure if I’m missing anything. Can you store JWTs in localStorage instead? What about XSS risks?

Also, how do you handle CSRF with a REST backend? I heard you can’t use CSRF tokens with REST.

I want to make sure my users’ data is safe. Should I change my whole setup? Or is there a way to make React + REST work securely?

Thanks for any advice!

Your approach is generally sound, but there are a few additional considerations. Implementing refresh tokens alongside your JWTs can enhance security by allowing shorter lifetimes for access tokens. Consider using the SameSite attribute on your cookies to mitigate CSRF risks further.

For CSRF protection with REST APIs, custom headers like ‘X-Requested-With’ can be effective. Ensure your backend validates these headers on sensitive operations.

Regarding XSS, while HttpOnly cookies help, also implement Content Security Policy (CSP) headers and sanitize user inputs thoroughly.

Lastly, don’t overlook the importance of regular security audits and staying updated on best practices. Security is an ongoing process, not a one-time implementation.

hm, interesting setup! have u considered using SameSite cookie attribute? it can help with CSRF. also, wat about rate limiting on the API side?

curious, how r u handling token expiration? refreshing JWTs can be tricky.

ever thought bout using an auth library like Auth0? might simplify things. wats ur take on that?

hey there! ur approach sounds pretty solid. storing JWTs in httpOnly cookies is def safer than localStorage. for CSRF, u could use the double submit cookie pattern or custom headers.

don’t forget about HTTPS and proper JWT validation on the server! maybe consider short-lived tokens + refresh mechanism too.

REST can be secure, just gotta be careful with implementation details. keep up the good work!