#httponly cookie containing jwt is not being send with requests in Angular (despite all efforts)

9 messages · Page 1 of 1 (latest)

ionic grotto
#

Hello.
I'm interested in fixing this and enhance my knowledge. But after hours of investigating the issue I wasn't able to solve it on my own.

I have a nestjs backend running on localhost:3000 that sets a httponly cookie in this way:

   const accessToken = await this.signinService.signin(credentialsDto);
    res
      .cookie('access_token', accessToken, {
        httpOnly: true,
        secure: false, //set it to true in production
        sameSite: 'lax', //set it to strict or lax in production
        expires: new Date(Date.now() + 3600),
      })
      .send({ status: 'ok' });

I also have an Angular app running on localhost:4200 that has a proxy configured in this way:

{
  "/api": {
    "target": "http://localhost:3000",
    "secure": false,
    "pathRewrite": {
      "^/api": ""
    }
  }
}

I successfully sign in and can see the cookie containing jwt being in the response cookies in Firefox devtools. But a subsequent GET request doesn't send the cookie to the server (investigated in the same devtools), thus, the server returning 401.
Here's my angular code:
user.service.ts:

signin(credentials: {username: string, password:string}){
    return this.http.post<{ status: string }>(this.backendSignInPath, credentials)  ;
}
me(){
  return this.http.get<{username: string}>(backendRootUrl+"users/me", {withCredentials: true});
}

nav.component.ts:

ngOnInit(): void {
    this.userService.me().pipe( catchError((err, caught) => {
      if(err.status === 0)  this.networkError = true;
      else if(err.status === 401) this.router.navigate(['/sign-in']);
      else this.unknownError = true;
      return of();
    })).subscribe( data => {
      this.username = data.username;
      this.router.navigate(['/main']);
    })

}

Note that I assume CORS is not needed to be set on the server since because of the proxy configured in Angular requests are sent to localhost:4200 which is the same site.

modest juniper
#

Can you first check if the cookie is visible on the back-end?

#

Maybe the 401 error is returned from another reason

#

If the cookie isn't visible on the back-end, maybe it's something with the proxy.

silent wharf
#

Also check the path in the cookie.

ionic grotto
#

The issue was sameSite: 'lax' I changed it to 'none' and it worked. I know in production lax is a better option security-wise.
Thanks community for trying to help.

runic ferry
#

Just be aware of the CSRF vulnerability samesite=none introduces.

#

So I dont think none is ever the solution.

#

I guess you can set it like that on local only, but yeah even then.