我正在嘗試在 Angular 應用程式中保存帶有 jwt 令牌的 ASP.NET Core API 回傳的 httpOnly cookie,但據了解(我可以通過一些測驗驗證),無法通過Javascript,所以我不能做這樣的事情:
this.httpClient.get("https://localhost:5001/token", {withCredendials: true}).subscribe(result => {
//logic to extract cookie from result
document.cookie = cookie;
});
這是我的控制器代碼:
[HttpGet("token")]
public HttpResponseMessage Token()
{
//some logic to get the token
var cookie = new CookieHeaderValue("token", token);
cookie.HttpOnly = true; //Without that line the JS code works and I can see the cookie in Chrome DevTools
cookie.Secure = true;
var response = new HttpResponseMessage();
response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return response;
}
我的 Angular 應用程式在 https://localhost:4200 上運行,我的 API 在 https://localhost:5001 上運行
那么,我該怎么做呢?
uj5u.com熱心網友回復:
我在 API 端做錯了,我需要在 HttpContext 的回應中添加 cookie,而不是在 HttpResponseMessage 中回傳 cookie:
HttpContext.Response.Cookies.Append("token", token, new CookieOptions { HttpOnly = true, Secure = true })
以這種方式設定回應的 Set-Cookie 標頭,現在它作業正常。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/490309.html
標籤:有角度的 asp.net 核心 饼干 jwt asp.net-core-webapi
