c# - 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() { });
更多信息:
- 我已将 Visual Studio 中的“应用程序 URL”更改为“启用 SSL”URL,因为我遇到了正在发生的重定向的 CORS 问题。
- 我正在使用内置的“HTTPS”设置运行服务器,而客户端应用程序使用 npm 的 https 设置
(包括与本文一样对证书错误进行排序)。 - 我已经尝试了 cookie 选项的所有组合,包括添加域/路径(以及相同站点属性的所有变体)
- 我在 CORS 政策中尝试了不同的东西(例如省略 .AllowCredentials)
- 我尝试使用 http 而不是 https
- Firefox 仍然存在与 Google Chrome 不存在的请求有关的 CORS 问题
- 该问题反映在 MS Edge 中
- 全部在 Windows 10 中运行
- 我对此比较陌生,所以如果我错过了什么,请告诉我。
非常感谢任何帮助。非常感谢,保罗
解决方案
在为此投入了好几个小时后,这是客户端需要的一个简单修复。上面的设置是/很好并且工作正常,特别提到了这一点:
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 就被设置好了。
希望能帮助到你。
推荐阅读
- maven - 为什么maven会忽略测试依赖项中定义的编译传递依赖项的版本
- python - 替换熊猫中的多个列值
- sql - 如何在 SQL Server 表行中拆分数据
- unity3d - 如何在 Vuforia Unity 中获取 ImageTarget 的 4 个角的 3D 空间坐标?
- apache-poi - SlideShowExtractor NoSuchMethodError org.apache.poi.sl.usermodel.Sheet.getPlaceholderDetails
- reactjs - ReactJS 根据道具文本匹配设置选定选项
- c++ - 无法通过 cpp 文件中的 Visual stduio 构建 yuvlib 库函数
- php - 找不到驱动程序(SQL:选择 user_id
- javascript - 如何在选择文本的位置显示对象?
- mysql - MySQL LIKE 性能与增加的通配符