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

问题描述

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

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

当我为客户端和服务器应用程序部分使用相同的服务器时,设置工作正常(只需在标准 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() { });

更多信息:

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

标签: c#reactjscookies.net-coresamesite

解决方案


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

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
   );
});

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

import axios from 'axios';
axios.defaults.withCredentials = true;

我有一个自定义的 axios 创建者文件设置,以便我可以使用例如拦截器等,这是我放置此代码的地方。一旦这两个东西被添加并对齐,cookies 就被设置好了。

希望能帮助到你。


推荐阅读