Set-cookie 不适用于 Dot net Core 3.1 中的跨站点请求/响应和 React 设置同站点 cookie 和/或 CORS 问题

P.T*_*ads 1 c# cookies reactjs .net-core samesite

好吧,我难住了!我一直试图解决这个问题几个小时,但没有运气。我正在按照本指南在 Dot Net Core 3.1/React.js(打字稿)项目中使用 JWT 进行身份验证,我正在努力学习整个设置。我正在使用跨站点请求。我的 React 服务器在https://localhost:3000(使用 Visual Studio Code 开发)上进行通信,而我的 API/后端 API 服务器在https://localhost:44309 上运行,在 Visual Studio 中运行。

我正在尝试将刷新令牌发送回客户端,指南指出这需要在 HTTP Only cookie 中以减轻 XSS。无论我尝试什么,我都无法让浏览器在客户端执行“set-cookie”,因此我可以在 Google Chrome 的开发工具 > 应用程序 > Cookies 中看到它。这适用于我在响应中设置的任何 cookie。如果我使用 Google Chrome 的开发人员工具面板,在网络响应中我可以看到“set-cookie”标头在那里,但它们永远不会显示在“应用程序 > Cookies > LocalHost”中。我发送的响应发送有效载荷,可以毫无问题地使用/读取。它只是不会设置 cookie!

当我为客户端和服务器应用程序部分使用相同的服务器时,设置工作正常(只需在标准 Visual Studio 设置中的 IIS 中运行它);任何/所有 cookie 设置都没有问题,所以我猜我正在处理跨站点问题。我只是不知道如何解决它。

我的代码:

//setting up cors
services.AddCors(options =>
{
  options.AddPolicy("CORSAllowLocalHost3000",
    builder =>
    builder.WithOrigins("https://localhost:3000")
      .AllowAnyHeader()
      .AllowAnyMethod()
      .AllowCredentials()
   );
});

//using cors
app.UseCors("CORSAllowLocalHost3000");


//setting up auth
services
.AddDefaultIdentity<ApplicationUser>
  (
    options =>
    {
      options.SignIn.RequireConfirmedAccount = false;
      options.Password.RequiredLength = 6;
    }
  )
.AddEntityFrameworkStores<IdentityApplicationContext>();


services
.AddAuthentication(opts =>
{
  opts.DefaultAuthenticateScheme = "JwtBearer";
  opts.DefaultScheme = "JwtBearer";
  opts.DefaultChallengeScheme = "JwtBearer";

})

.AddJwtBearer("JwtBearer", opts =>
{
  opts.SaveToken = true;
  opts.TokenValidationParameters = tokenValParams;
});

//tokenValParams to validate the JWT
var tokenValParams = new TokenValidationParameters
{
  ValidateIssuerSigningKey = true,
  IssuerSigningKey = new SymmetricSecurityKey(key:  
Encoding.ASCII.GetBytes(configuration.GetSection("Authentication").GetSection("JwtBearer").GetSection("SecurityKey").Value)),
  ValidateIssuer = false,
  ValidateAudience = false,
  RequireExpirationTime = false,
  ValidateLifetime = true,
  ClockSkew = TimeSpan.Zero
};


//for API only dev env, start as API only service - no browser - client app runs 
app.UseStaticFiles();
if (!env.IsEnvironment("APIOnlyDevelopment")) 
  app.UseSpaStaticFiles();

app.UseSpa(spa =>
{
  spa.Options.SourcePath = "ClientApp";
  if (env.IsDevelopment())
    {
      spa.UseReactDevelopmentServer(npmScript: "start");
       //spa.UseProxyToSpaDevelopmentServer("https://localhost:3000");  
     });


//Test Cookie generated in client before async Ok() result is returned in controller
HttpContext.Response.Cookies.Append("JwtRefreshTokenn", resultOfSignin.RefreshToken, new CookieOptions() { Secure = true, HttpOnly = true, SameSite = SameSiteMode.None});

Response.Cookies.Append("JwtRefreshTokenn2", resultOfSignin.RefreshToken, new CookieOptions() { HttpOnly = true, Secure = true, SameSite = SameSiteMode.None});

Response.Cookies.Append("JwtRefreshTokenn3", resultOfSignin.RefreshToken, new CookieOptions() { });
Run Code Online (Sandbox Code Playgroud)

更多信息:

  • 我已将 Visual Studio 中的“App URL”更改为“Enable SSL”URL 的 URL,因为我遇到了正在发生的重定向的 CORS 问题。
  • 我正在使用内置的“HTTPS”设置运行服务器,并使用 npm 的 https 设置运行客户端应用程序
    (包括像这篇文章一样对证书错误进行排序)。
  • 我已经尝试了 cookie 选项的所有组合,包括添加域/路径(以及相同站点属性的所有变体)
  • 我在 CORS 政策中尝试了不同的东西(例如省略 .AllowCredentials)
  • 我尝试使用 http 而不是 https
  • Firefox 仍然存在 CORS 问题,而 Google Chrome 则没有
  • 问题反映在 MS Edge 中
  • 全部在 Windows 10 中运行
  • 我对此比较陌生,所以如果我错过了什么,请告诉我。

非常感谢任何帮助。非常感谢,保罗

P.T*_*ads 5

在为此投入了几个小时之后,这是客户端所需的简单修复。上面的设置是/很好并且有效,特别提到了这一点:

services.AddCors(options =>
{
  options.AddPolicy("CORSAllowLocalHost3000",
    builder =>
    builder.WithOrigins("https://localhost:3000")
      .AllowAnyHeader()
      .AllowAnyMethod()
      .AllowCredentials() // <<< this is required for cookies to be set on the client - sets the 'Access-Control-Allow-Credentials' to true
   );
});
Run Code Online (Sandbox Code Playgroud)

由于客户端使用 axios 从 React 内部进行 API 调用,因此需要设置全局默认值以匹配此 / 使用此标头。所以至少在程序中导入 axios 的地方,默认是这样设置的:

import axios from 'axios';
axios.defaults.withCredentials = true;
Run Code Online (Sandbox Code Playgroud)

我有一个自定义的 axios creator 文件设置,以便我可以使用例如拦截器等,这是我放置这段代码的地方。一旦添加并对齐这两件事,cookie 就被设置了。

希望能帮助到你。