0

我有一个 ASP.NET Core 6 MVC Razor pages 应用程序,它使用 Microsoft Identity 进行 AzureAD 集成身份验证,在 Azure Linux AppService 计划上运行(使用强制 HTTPS)。

身份验证集成就像一个魅力。再开心不过了。

但在我的日志中,我看到如下警告:

cookie '".AspNetCore.Correlation.[...]"' 已设置 'SameSite=None' 并且还必须设置 'Secure'。

(以及 .AspNetCore.OpenIdConnect.Nonce cookie)。

我尝试添加 cookie 策略:

app.UseCookiePolicy(new CookiePolicyOptions
{
    HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always,
    MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None,
    Secure = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always
});

但没有喜悦。

我尝试了位于“var app = builder.Build();”之后的代码 在“app.UseAuthentication(); app.UseAuthorization();”之后 (就在 app.MapRazorPages().RequireAuthorization("MyRoleId") 之前)。

关于如何将这些 cookie 设置为安全的任何想法?

4

1 回答 1

0

一般来说,cookie策略会在之前添加,app.UseAuthentication();因为这会写入cookie。这是代码:-

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

// Add this before any other middleware that might write cookies
app.UseCookiePolicy(new CookiePolicyOptions
{
    HttpOnly = HttpOnlyPolicy.Always,
    MinimumSameSitePolicy = SameSiteMode.None,
    Secure = CookieSecurePolicy.Always
});

// This will write cookies, so make sure it's after the cookie policy
app.UseAuthorization();
app.MapRazorPages();
app.Run();
于 2022-01-18T10:29:16.903 回答