我正在尝试将 cookie 与前端一起使用,该前端的域与后端的域不同。后端是用.net core实现的,前端是Angular。
我研究过,在进行 http 调用时需要设置 withCredentials: true 。但是当我将其设置为 true 时,我收到此错误:
对预检请求的响应未通过访问控制检查:当请求的凭据模式为“include”时,响应中“Access-Control-Allow-Origin”标头的值不得为通配符“*”。
我一直在尝试设置 CORS 和 Cookie 设置来应对这种情况。这是我来自 StartUp.cs 的相关代码。
科尔斯设置:
services.AddCors(options =>
{
options.AddPolicy("AllowDomainOrigin",
builder =>
{
builder
.WithOrigins("http://some.domain.net")
.AllowAnyHeader()
.AllowAnyMethod();
});
options.AddPolicy("AllowForLocalhost",
builder =>
{
builder
.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
services.AddSession(options =>
{
options.Cookie.SameSite = SameSiteMode.None;
});
...
app.UseCors("AllowDomainOrigin");
app.UseCors("AllowForLocalhost");
Cookie 设置:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.Cookie.Domain = "some.domain.net";
options.Cookie.Name = "access_token";
options.Cookie.SameSite = SameSiteMode.None;
options.LoginPath = "/login";
options.LogoutPath = "/login";
})
.AddCookie("localhost", options =>
{
options.Cookie.Domain = "localhost";
options.Cookie.Name = "localhost_access_token";
options.Cookie.SameSite = SameSiteMode.None;
options.LoginPath = "/login";
options.LogoutPath = "/login";
})
.AddCookie("othercloud", options =>
{
options.Cookie.Domain = "domain.com";
options.Cookie.Name = "musiple_access_token";
options.Cookie.SameSite = SameSiteMode.None;
options.LoginPath = "/login";
options.LogoutPath = "/login";
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = tokenValidationParameters;
});
以下是我在登录控制器中登录 HttpContext 的方法:
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignOutAsync("localhost");
await HttpContext.SignOutAsync("othercloud");
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(identity),
authProperties);
await HttpContext.SignInAsync("localhost",
new ClaimsPrincipal(identity),
authProperties);
await HttpContext.SignInAsync("othercloud",
new ClaimsPrincipal(identity),
authProperties);
这是我的音频文件端点:
[HttpGet("{id}")]
[Authorize(AuthenticationSchemes= CookieAuthenticationDefaults.AuthenticationScheme +", localhost, othercloud")]
public async Task<FileStreamResult> Get(int id)
如您所见,我还使用 JWT 令牌进行身份验证。我需要 cookie,因为我使用音频元素从 REST API 下载 mp3 文件,并且我将音频元素 src 直接设置为我的 REST API 地址。因此,在使用音频元素时,我无法将 JWT 设置为标头。当我的前端与后端位于同一域时,Cookie 在这种情况下运行良好,但现在我也尝试将前端移动到其他服务器和域。
我需要如何配置后端才能从不同域获取cookie?
我的后端在 Azure 上。还有一些 CORS 设置,我删除了 * 并将其替换为特定地址。这和这个有关系吗?
EDIT:
我找到Azure CORS设置后,异常更改为:
对预检请求的响应未通过访问控制检查:响应中“Access-Control-Allow-Credentials”标头的值为“”,当请求的凭据模式为“include”时,该值必须为“true”
EDIT 2:
您需要从 Azure 中删除所有 CORS 设置,才能让 .net core cors 设置获得 cors 控制。仍然没有成功,但也许更接近解决方案。