sajad torkamani

Preamble

Let’s assume you have a React SPA that works with a Symfony REST API and you need to implement authentication for your SPA.

This post documents how you can implement a cookie-based authentication.

Pre-requisites

The flow

1. User submits credentials (email & password) via a login form on a web page.

2. SPA calls an API endpoint to submit the credentials and obtain a session cookie (e.g., POST /api/sessions):

curl --location 'http://localhost:8080/api/sessions' \
--header 'Content-Type: application/json' \
--data-raw '{
    "email": "sajad@hey.com",
    "password": "Password$123"
}'

3. API verifies credentials are correct, generates a unique session ID, and returns a response:

HTTP/1.1 201 Created
Set-Cookie: sessionId=<some-unique-session-id>; expires=Fri, 02 May 2025 18:14:22 GMT; Max-Age=7200; path=/; httponly; samesite=lax

Credentials correct!

4. Browser containing the SPA knows how to speak HTTP so it respects the protocol by storing the sessionId cookie in the browser for the specified time (it will remove the cookie on 02 May 2025 at 18:14:22 GMT as configured by the expires attribute in the Set-Cookie header response from above).

5. On subsequent requests to the same server, the browser will send the sessionId cookie. The API will have code in place that checks incoming requests for valid session IDs. If they have valid session IDs, it can safely trust that the incoming request is for the user associated with that session ID because it’s almost impossible to provide a valid session ID unless the user had successfully authenticated in a previous request.