【问题标题】:How to set Cookie HTTP Only with .NET Core in client (Browser)如何在客户端(浏览器)中仅使用 .NET Core 设置 Cookie HTTP
【发布时间】:2022-01-19 19:11:28
【问题描述】:

我正在尝试将 Cookie HTTP Only 设置为使用 .NET Core 和 NextJS 作为前端的客户端(浏览器)

问题是当我在邮递员中发出请求时,cookie 就在那里 Postman Token HTTP Only successful

所以我不需要通过 Authorization Bearer 令牌发送令牌,我可以向需要有效令牌的 APIs 发出请求。

但我试图在前端处理,但我不能只在浏览器中设置 Cookie Http Client(Browser Image)

您可以看到令牌在那里,但在 Cookie 部分中 cookie 不可用 Browser Cookie Not Appear

这是启动中的代码

    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddCookie()
            .AddJwtBearer(options =>
            {
                options.Events = new  JwtBearerEvents(){
                       OnMessageReceived = context =>
                    {
                        var request = context.HttpContext.Request;
                        var cookies = request.Cookies;
                        if (cookies.TryGetValue("token", out var accessTokenValue))
                        {
                            context.Token = accessTokenValue;
                        }
                        Console.WriteLine(context.Token);
                        return Task.CompletedTask;
                    }
                };                  
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = builder.Configuration["Jwt:Issuer"],
                    ValidAudience = builder.Configuration["Jwt:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])),
                    ClockSkew = TimeSpan.Zero
                };
            });
 builder.Services.AddCors(options =>
    {
        options.AddPolicy("myCors", builder =>
        {
            builder.WithOrigins("http://localhost:3000");
            //builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");
            builder.AllowAnyMethod();
            builder.AllowAnyHeader();
            builder.AllowCredentials();
        });

这是验证用户并返回令牌和设置cookie的方法中的配置

这是前端的请求

     const handleSubmit = async (e) => {
      e.preventDefault();
      try {
         const result = await fetch(URL + 'Auth/Login', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(formValues)});
         console.log(result.status);
         if (result.status === 200) {
            const data = await result.json();
            console.log(data);
         }
      } catch (e) {}
   };

【问题讨论】:

标签: asp.net-core cookies next.js jwt


【解决方案1】:

AddJwtBearer 从不处理 cookie,在此示例中添加 .AddCookie() 没有任何意义。

AddCookie() 要发出 cookie,则需要有人签署用户,而 AddJwtBearer 从不这样做。

但有点不清楚您实际上尝试使用该代码实现什么。

【讨论】:

    猜你喜欢
    • 2014-01-04
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 2012-08-17
    • 2016-02-23
    • 2021-07-20
    • 1970-01-01
    相关资源
    最近更新 更多