Search code examples
springspring-bootspring-securitysingle-page-applicationspring-session

Single Page Application Session Managment and Spring Security Backend


I have a SPA webapp and spring boot backend. I am using spring security for login ldap authentication and csrf enabled. Now I am a little confuse on how I can implement session management on SPA and make it secured.

Questions:

  1. I store the user's first name, last name and login name in a cookie after a successful login in ldap. Is this ok?login name and user's name since they are not credentials.
  2. Is CSRF token enough for secured SPA? I am a little stuck on decision.

Hope to give me some light/path to take. Thanks


Solution

  • Yes, session cookie + (cookie-based) protection against CSRF are enough to authorize a SPA on a Spring backend.

    Spring session cookies are flagged with SameSite (as it should). So the only thing to do for an SPA to be authorized on a session-based backend it to serve both with the same origin: the browser will attach the session cookie to each REST request from the SPA to the backend. A few options:

    • serve both through the same reverse proxy (a nginx Docker container, k8s ingres, ...)
    • in the case where the backend entry point is Spring Cloud Gateway, use a route to serve the SPA assets
    • in the case where the backend is seen as a single service (monolith or single facade), serve the SPA assets from the static resources of this service (use WebPack proxy or whatever similar feature for your SPA framework during dev)

    If you switch to OAuth2 and follow current recommendations for SPAs, you'll need protection against CSRF too. @j-asgarov is right in his comment: CSRF protection is needed as soon as sessions are used (and requests between an SPA and a Spring app with oauth2Login are authorized with sessions). This article I wrote can be useful for such a transition (but you probably don't need OAuth2 if all identities are held in your LDAP, and you don't need features like SSO).