【问题标题】:Cannot create httponly cookie containing jwt in ASP.NET Core and React无法在 ASP.NET Core 和 React 中创建包含 jwt 的 httponly cookie
【发布时间】:2023-03-28 08:56:02
【问题描述】:

我正在尝试在我的应用中实施身份验证方案。控制器,更具体地说是方法,负责检查用户的凭据并生成 jwt,然后将其放入 httponly cookie 中,如下所示

    [HttpPost]
    [Route("authenticate")]
    public async Task<IActionResult> Authenticate([FromBody] User user)
    {
        var response = await _repository.User.Authenticate(user.Login, user.Password);
        if (!response) return Forbid();

        var claims = new List<Claim>
        {
            new Claim("value1", user.Login)
        };
        string token = _jwtService.GenerateJwt(claims);

        HttpContext.Response.Cookies.Append(
            "SESSION_TOKEN",
            "Bearer " + token,
            new CookieOptions
            {
                Expires = DateTime.Now.AddDays(7),
                HttpOnly = true,
                Secure = false
            });

        return Ok();
    }

我在 Postman 中测试了这种方法 - 在那里一切正常且正常。 cookie 也正在创建中。此外,最近我使用 Angular 创建了一个应用程序,我使用了相同的身份验证方法,但是使用 Angular 的 HTTP 模块,cookie 一直在创建。这是使用 Axios 在我的 React 应用程序中该方法的样子

export const authenticate = async (login, password) => {
 return await axiosLocal.post('/api/auth/authenticate',
    {login, password}).then(response => {
    return response.status === 200;
 }, () => {
    return false;
});

我在尝试登录时收到的所有响应都是响应代码 200。我很确定这与 Axios 的设置有关。 此外,如果有人的古玩,变量“axiosLocal”包含 API 的 baseURL。

- 更新 1 好的。如果我没有弄错,为了从响应中设置 cookie,我必须使用 { withCredentials: true } 选项发送所有请求。但是当我尝试这样做时,请求被 CORS 阻止,尽管我已经设置了一个 cors 策略,它必须允许处理来自任何来源的请求

app.UseCors(builder => builder.AllowAnyHeader()
            .AllowAnyMethod()
            .AllowAnyOrigin()
            .AllowCredentials());

【问题讨论】:

    标签: javascript asp.net asp.net-core


    【解决方案1】:

    终于解决了。将 .SetIsOriginAllowed(host =&gt; true) 而不是 .AllowAnyOrigin() 传递给 CORS 设置并在 Axios 请求中使用 { withCredentials: true } 作为选项对我有帮助。

    【讨论】:

      【解决方案2】:

      我也遇到了同样的问题。我修好了。

      问题:

      • 在浏览器中,httpOnly cookie 被接收到并且没有返回到服务器

      • 在邮递员工作

      // Problemable server code for settings httpOnly cookie
      Response.Cookies.Append("refreshToken", refreshToken.Token, new CookieOptions
      {
         HttpOnly = true,
         Expires = DateTime.UtcNow.AddDays(7),             
      });
      

      解决方案:

      • 在服务器 .AllowCredentials().SetOriginAllowed(host =&gt; true).WithOrigins("https://localhost:3000")

      • 在客户端 (react, axios) withCredentials:true 在标题中

      如果还是不行在 Chrome(当前 v.91.0.4472.124)中打开 DevTools 中的 Network 选项卡,选择失败的请求,当您将鼠标放在黄色三角形上时,您可以看到非常详细Cookie 被阻止的原因的信息。

      
       // End server code for setting httpOnly cookie after following the DevTools warnings
      Response.Cookies.Append("refreshToken", refreshToken.Token, new CookieOptions
      {
            HttpOnly = true,
            Expires = DateTime.UtcNow.AddDays(7),
            IsEssential=true,
            SameSite=SameSiteMode.None,
            Secure=true,
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-07
        • 2019-02-04
        • 2021-08-22
        • 2020-06-19
        • 1970-01-01
        • 2021-01-31
        • 2021-10-10
        • 1970-01-01
        相关资源
        最近更新 更多