我已經撰寫了一個用于登錄和注銷的 C# web api 端點。當有人登錄時,我會在他們的瀏覽器 cookie 中保存一個 jwt 令牌。但是當用戶注銷時我無法洗掉 cookie。cookie 僅在 POSTMAN 中被洗掉。這是我的登錄和注銷方法:
登錄
[Route("login")]
[HttpPost]
public async Task<IActionResult> login(PeiUser user)
{
var attemptedUser = await _db.PeiUsers.FirstOrDefaultAsync(u => u.UEmail == user.UEmail);
if (attemptedUser == null)
{
return BadRequest(new { message = "Invalid credentials" });
}
else
{
if (!BCrypt.Net.BCrypt.Verify(user.UPassword, attemptedUser.UPassword))
{
return BadRequest(new { message = "Invalid credentials" });
}
else
{
var jwt = _jwtService.Generate(attemptedUser.UId); // Generate the Access token that expires in one day
Response.Cookies.Append("jwt", jwt, new CookieOptions //Save the JWT in the browser cookies, Key is "jwt"
{
HttpOnly = true,
SameSite = SameSiteMode.None,
Secure = true
});
return Ok(new { message = "You are now logged in" });
}
}
}
登出
[Route("logout")]
[HttpGet]
public async Task<IActionResult> logout()
{
Response.Cookies.Delete("jwt");
return Ok(new { message = "Success" });
}
注意:注銷成功后在控制臺列印成功。但是餅干還在。
在 REACT 前端,我是這樣呼叫的:
const logout = async() => {
try{
const res = await fetch('https://localhost:44361/api/users/logout', {
headers: {"Content-Type": 'application/json'},
credentials: 'include'
})
var content = await res.json();
console.log(content);
}catch(err){
console.log(err);
}
}
注意: 我從中學到的教程也完美地添加了 cookie,沒有任何問題。但是我必須在Login端點的 Cookies.append 屬性中添加 SameSite = SameSiteMode.None, Secure = true才能使其作業。cookie 在 POSTMAN 中被清除。所以我想我缺少一些配置。我通過將方法更改為 GET 和 POST 來嘗試注銷端點
任何幫助表示贊賞。請向我詢問任何其他資訊
uj5u.com熱心網友回復:
我在閱讀檔案后找到了解決方案。Logout 端點中的 Cookies.Delete 中的一點變化已經完成了。我不知道它為什么起作用
Response.Cookies.Delete("jwt", new CookieOptions
{
HttpOnly = true,
SameSite = SameSiteMode.None,
Secure = true
});
uj5u.com熱心網友回復:
您需要將與最初用于創建此 cookie的方法相同CookieOptions的Delete方法傳遞給方法Append。這樣做的原因與洗掉 cookie的古怪方式有關:服務器發出一個新Set-Cookie命令,但它的值是空的,并且過去設定了到期時間。瀏覽器將此解釋為洗掉 cookie 的標志。但是為了使其發揮作用,它需要所有相同的選項,否則瀏覽器將無法理解服務器正在針對現有 cookie。
您可以查看的實作Response.Cookies.Delete以了解其作業原理:
Append(key, string.Empty, new CookieOptions
{
Path = options.Path,
Domain = options.Domain,
Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
Secure = options.Secure,
HttpOnly = options.HttpOnly,
SameSite = options.SameSite
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/367787.html
標籤:C# asp.net-web-api 饼干 jwt 网络接口
下一篇:線性規劃的變化?
