【发布时间】:2022-01-04 21:12:49
【问题描述】:
我编写了一个用于登录和注销的 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" });
}
注意:登出后,成功信息在控制台中完美打印出来。但是cookie还在。
在 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 来尝试了 logout 端点
感谢任何帮助。请向我询问任何其他信息
【问题讨论】:
-
如何检查 cookie 是否被删除?注销后你检查cookie的过期时间吗?注销后是否检查了 cookie 的值?理想情况下,API 不应该处理 cookie,因为 API 也可以被称为服务器到服务器。调用 API 的客户端(在你的情况下为 React 客户端)应该负责存储和使用令牌。
-
@Chetan 我正在检查检查->应用程序-> cookie,看看它何时被删除。 cookie 的名称是“jwt”。我从一个教程中了解到,当他从后端调用注销时,名为“jwt”的 cookie 会消失。我的不会消失。它还在那里。
-
你在注销后检查cookie的过期时间吗?注销后是否检查了 cookie 的值? stackoverflow.com/questions/48918820/…
-
@Chetan 你如何检查cookie的过期时间?
-
无论如何改变现在都在起作用,Response.Cookies.Delete("jwt", new CookieOptions { HttpOnly = true, SameSite = SameSiteMode.None, Secure = true });
标签: c# asp.net-web-api cookies jwt webapi