Cookies and ASP.NET Core

后端 未结 3 422
刺人心
刺人心 2020-12-06 05:54

This might be a simple question, I\'m hoping it is at least.

I\'ve started to look into the Release Candidate of ASP.NET Core and I can see that a lot of the configu

相关标签:
3条回答
  • 2020-12-06 06:34

    For a general cookie manually created within your application, you control the flags for security when creating it - for example:

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

    Here, setting HttpOnly to true would prevent client-side JS from accessing the cookie vlaue, and setting Secure to true would only allow the cookie to be served/received over HTTPS.

    No defaults are applied when you add cookies to the response, as can be seen in the source code for the ResponseCookies class.

    For the various middlewares that create and consume their own cookies (like the Session middleware that you have mentioned in your answer), they may have their own configuration options that will control these flags for those cookies they create themselves, but this will make no difference to cookies you create elsewhere in your application.

    0 讨论(0)
  • 2020-12-06 06:44

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

    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.

    0 讨论(0)
  • 2020-12-06 06:44

    Ok, figured it out, seems I still need to remind myself that most things in .NET5 are now opt in, including things like Session which is where cookies now live, reading through the docs, I eventually found what I needed to enable cookies and configure them.

    0 讨论(0)
提交回复
热议问题