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:
Get JWT from API after login
Store JWT in HttpOnly cookie
Send cookie with API requests for auth
API checks for XMLHttpRequest header
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?
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.
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!