【问题标题】:Web API saves JWT in cookies, but can not remove itWeb API 将 JWT 保存在 cookie 中,但无法删除
【发布时间】: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


【解决方案1】:

我在阅读文档后找到了解决方案。 Cookies.Delete 在注销端点中的一点变化就可以了。我不知道它为什么起作用

Response.Cookies.Delete("jwt", new CookieOptions 
            {
                HttpOnly = true,
                SameSite = SameSiteMode.None,
                Secure = true
            });

【讨论】:

    【解决方案2】:

    您需要将与最初用于创建此 cookie 的 Append 方法相同的 CookieOptions 传递给 Delete 方法。其原因与删除 cookie 的古怪方式有关:服务器发出一个新的Set-Cookie 命令,但它的值是空的,并且过去设置了过期时间。浏览器将此解释为删除 cookie 的标志。但为了让它发挥作用,它需要所有相同的选项,否则浏览器将无法理解服务器以现有 cookie 为目标。

    您可以查看the implementation of 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
                });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-02
      • 1970-01-01
      • 1970-01-01
      • 2020-11-22
      • 1970-01-01
      • 2012-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多