简体   繁体   中英

Javascript Fetch not sending JWT httponly cookie to .Net Core 6 API

I've been working on implementing JWT and refresh_tokens. The latest attempt uses refresh_tokens stored in an httpOnly cookie. My API is a.Net Core 6 API, and using Swagger and Postman, things seem to work fine. I see the refresh_token cookie in the browser devtools Application Tab. In Swagger and Postman, when I run my refresh_token endpoint, which uses the httpContextAccessor to get the Request.Cookies, it's fine. I see in the Request Headers, a cookie with my refresh_token. Now, my attempts to replicate this work in VSCode running a live server is where I'm running into trouble. I'm using a vanilla JS front end and Fetch. My login code works fine:

fetch(loginUrl, {
   method: "POST",
   credentials: "include",
   body: JSON.stringify(authBody),
   headers: {
      "Content-Type": "application/json; charset=utf-8"
});

The Browser dev tools shows my cookie is fine. My attempts to call my refresh_token endpoint however does NOT send the cookie. I don't see a cookie in the Request Headers. I've been trying some variations of the above fetch code but the cookie won't go. Now the only thing I can think of is a cors issue... My API is running from VS2022 and is at https://localhost:7121 and my VSCode Live Server is http://localhost:5500.

On the API side, I've tried setting the cookie with:

HttpOnly = true,
Secure = true,
Expires = expireTime,

I've tried including some variations of SameSite too, but not much luck. Any suggestions or help is greatly appreciated!

OK, it looks like I got the cookie to work... it seems the "SameSite" property for the cookie was messing it up. I just noticed a checkbox in the Network tab in the Devtools that showed filtered out request cookies, and it indicated SameSite being strict was preventing the cookie from going. I set it to none in my API, and it looks like the cookie is sent now... the only issue now is the response I get back is opaque, so I don't get my new tokens from the API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM