My Angular 11 app is making a POST request to a Nest.js backend for authentication.
In my Nest app running at http://localhost:3000
, I'm setting the CORS config as:
{
origin: 'http://localhost:4200',
methods: 'DELETE, GET, POST, PUT, OPTIONS',
allowedHeaders: 'Origin, X-Requested-With, Content-Type, Accept, Authorization',
credentials: true,
optionsSuccessStatus: 200
}
In my Angular app running at http://localhost:4200
, I have a custom interceptor to set withCredentials
to true:
@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {
intercept(httpRequest: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const clonedRequest = httpRequest.clone({
withCredentials: true
});
return next.handle(clonedRequest);
}
}
However, when my service method fires my authentication cookie is not set. My code to set the cookie in Nest is:
private setAuthCookie(response: ExpressResponse, accessToken: IAccessToken): void {
const production = process.env.PRODUCTION === 'true';
const cookieOptions = {
httpOnly: false,
secure: production,
};
if (production) {
cookieOptions['sameSite'] = 'none';
}
response
.status(200)
.cookie(AUTH_COOKIE_NAME, accessToken.accessToken, cookieOptions);
}
The exact same code works as expected in a different application using exactly the same architecture, ports, etc. I have poured over the answers here on S.O. and other articles regarding sameSite
and CORS, but so far nothing is helping.
The Set-Cookie header is in the response...
Set-Cookie: DZOutagesAuth=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFsc29pY29kZUBnbWFpbC5jb20iLCJzdWIiOiI1ZmYwYmIyYjc3YjQyMzFhNzJhYmZlZDciLCJpYXQiOjE2MTE3NTU0MzEsImV4cCI6MTYxMTc1OTAzMX0.rfdKoTxrJgG7_cco9PN_eqUQ7Q3FawiRV2swnqbvrKk; Path=/
...but it's never set. I have also tried adding an entry in my /etc/hosts
to access the site locally on a domain other than localhost
and writing the cookie specifically for that domain, but that doesn't work either.
Update
On my MacBook Pro running Big Sur, the cookie isn't set when using ANY browser, not just Chrome.
I have also checked my browser settings to allow all cookies.
I have disabled Do Not Track headers.
I have even tried all of the same code on a different computer running Windows 10 and cookies are not set in any browser.
Setting sameSite=None
and secure
, resulting in a header of:
Set-Cookie: DZOutagesAuth=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFsc29pY29kZUBnbWFpbC5jb20iLCJzdWIiOiI1ZmYwYmIyYjc3YjQyMzFhNzJhYmZlZDciLCJpYXQiOjE2MTE5NDY1NDUsImV4cCI6MTYxMTk1MDE0NX0.mN9ZobpMOe_xHIm2mSNSiabthjyTMBPvHTV3gooY2BQ; Path=/; HttpOnly; Secure; SameSite=None
doesn't work either. WTF.
question from:
https://stackoverflow.com/questions/65920825/chrome-will-not-set-cookie-from-angular-post-request