Cookie和ASP.NET核心

Jak*_*ond 10 cookies http .net-core asp.net-core

这可能是一个简单的问题,我希望至少是这样.

我开始寻找到ASP.NET核心的候选发布版,我可以看到,很多的配置已经搬出旧web.config文件,并到JSON结构的文件(以及XML和其它的中间件你可能想写自己).
我还没有弄清楚如何做的一件事是在旧的web.config方法中这么简单,保护你的网站的一些基本组件,如cookie.

以前我们会设定secure,httpOnly等里面的web.config以及当它来部署一个不错的转换文件将修改的值,我们和吐在年底前把新文件.在阅读了一下后,似乎web.config现在几乎已经死了,那么我们如何才能实现相同的结果呢?

我知道我们可以根据是否某些变量,如环境,设置为DEV,分期,生产等加载不同的配置文件,但这似乎与东西是一个变换的所有意图和目的,除了在如何更换只是变换它真的装了吗?

我在这里错过了一些东西,还是让自己陷入了困境?

Mar*_*hes 14

对于在应用程序中手动创建的常规cookie,您可以在创建时控制安全标志 - 例如:

Response.Cookies.Append(
    "COOKIE_NAME",
    "COOKIE_VALUE",
    new CookieOptions()
    {
        Path = "/",
        HttpOnly = false,
        Secure = false
    }
);
Run Code Online (Sandbox Code Playgroud)

在这里,将HttpOnly设置为true将阻止客户端JS访问cookie vlaue,并将Secure设置为true将仅允许通过HTTPS提供/接收cookie.

向响应添加cookie时不会应用默认值,如ResponseCookies类的源代码中所示.

对于创建和使用自己的cookie的各种中间件(比如你在答案中提到的Session中间件),他们可能有自己的配置选项来控制他们自己创建的cookie的这些标志,但这没什么区别到你在应用程序的其他地方创建的cookie.


小智 9

It's an old question, but I didn't see this answer anywhere so here goes.

As for configuring the behavior of cookies globally you can do it in the Startup.

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
        options.HttpOnly = HttpOnlyPolicy.Always;
        options.Secure = CookieSecurePolicy.Always;
        // you can add more options here and they will be applied to all cookies (middleware and manually created cookies)
    });

    ...
}
Run Code Online (Sandbox Code Playgroud)

As for doing this in a manner that you have different configurations per environment I still haven't found a way of doing it myself.