These three are different protections, and with cookie authentication all three matter. CORS — who may read your API responses from another origin - Browsers block JavaScript on one origin from reading responses from another unless the server allows it. - Spring Boot configuration: a CorsConfigurationSource bean (used by http.cors()) with exact allowed origins such as https://app.example.com, allowed methods and headers, and setAllowCredentials(true) when cookies are used. Never combine credentials with a wildcard origin. - If React is served from the same origin as the API (through a reverse proxy), CORS may not be needed at all. - CORS is not authentication or authorization; the API must still check every request. CSRF — stopping other sites from making the user's browser perform actions - With cookie-based sessions, the browser automatically sends cookies on requests triggered by a malicious page. - Defences: - SameSite=Lax or Strict on the session cookie (plus Secure and HttpOnly). - Spring Security CSRF protection (enabled by default): for SPAs, use CookieCsrfTokenRepository.withHttpOnlyFalse() so React can read the XSRF-TOKEN cookie and send it in the X-XSRF-TOKEN header on state-changing requests (Spring Security 6 has specific SPA configuration guidance for the token request handler). - Never change state on GET requests. - Disabling CSRF is only appropriate for purely token-based APIs that do not use cookies for authentication. XSS — attackers running script inside your own pages - React escapes values in JSX by default. Risks come from dangerouslySetInnerHTML, user-controlled URLs (javascript: links), unsafe third-party scripts and older libraries manipulating the DOM. - Sanitise any HTML you must render (DOMPurify), validate URLs, and avoid injecting user content into scripts. - Add a Content-Security-Policy header (Spring Security's headers() configuration can add it) to restrict script sources. - HttpOnly cookies stop scripts from reading the session cookie, but XSS can still send requests as the user, so preventing XSS remains essential. How they fit together CORS limits which sites can read your API, CSRF protection stops other sites from triggering actions with the user's cookies, and XSS prevention stops attackers executing code inside your own site, where CORS and CSRF defences no longer help.
Ravindra Wadile · · 0 likes