I have my frontend running on "https://example.com" and backend running on "https://api.example.com".
From backend, the login endpoint "https://api.example.com/auth/login" is returning refresh token in response headers as below (i can see it in browser network tab):
Access-Control-Allow-Origin:https://example.com
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Set-Cookie: refreshToken=eyJhbGciOiJIUzI1NiJ9...; Path=/auth/refresh; Domain=example.com; Max-Age=31536000000; Expires=3023年10月23日 00:57:41 GMT; Secure; HttpOnly; SameSite=Lax
other headers....
But when frontend makes the call to refresh access-token then request doesn't contain the refresh token. Browser doesn't append the token in the request and server rejects it with 403. Below are the request details for refresh token:
Request URL:https://api.example.com/auth/refresh
Request Method:POST
Status Code:403 Forbidden
Remote Address:xxxxx
Referrer Policy:strict-origin-when-cross-origin
Request Headers:
:authority:api.example.com
:method:POST
:path:/auth/refresh
:scheme:https
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br, zstd
Accept-Language:en-GB,en-US;q=0.9,en;q=0.8
Content-Length:0
Origin:https://example.com
Priority:u=1, i
Referer:https://example.com
Why browser is not appending or storing the refresh token when it is coming from same sub-domain and domain attribute is also set in refresh-token cookie?
The cookie is also not visible in browser's dev tool.
1 Answer 1
Finally with "J Asgarov" answer, i was able to solve the issue. The cookie setup was ok as i was already setting domain "example.com" in it (there is no need of leading . in it anymore, browser allows for sub-domains as well if root matches).
The real issue was that i was setting withCredentials true only for refresh token request whereas it needed to be true for login request as well. After enabling it for login then browser was able to read the refresh token cookie otherwise it was getting ignored from login response.
As per web docs withCredentials flag is required for both outgoing request and incoming response. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
Comments
Explore related questions
See similar questions with these tags.
.before domain => Cookie Domain:.example.com