Sunday, November 18, 2018

ASP.NET Core: Important Things to Consider When Configuring Cookie Authentication

In this post, let’s go through two of the important things to consider when configuring Cookie Authentication in an ASP.NET Core Application.
services
     .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
     .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, x =>
     {
          // other configuration
          x.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
          x.Cookie.SameSite = SameSiteMode.None;
     })
Cookie.SecurePolicy and Cookie.SameSite plays a major role in Cookie authentication.

Cookie.SecurePolicy

This is an enum of type CookieSecurePolicy.
  • SameAsRequest: This is the default. If the server has provided the cookie to the client over HTTP, then all subsequent HTTP and HTTPS requests can return the cookie to the server. If it was over HTTPS, only HTTPS requests can take the cookie back.
  • Always: When this is set, your cookie will only sent in HTTPS requests.
  • None: When this is set, even the cookie is sent to the client in HTTPS, all your HTTP and HTTPS requests can take the cookie back to the server.

Cookie.SameSite

This is an enum of type SameSiteMode. This specifies how the cookie will be sent in cross-site requests.
  • None: No mode is specified.
  • Lax: The cookie will be sent with "same-site" requests, and with "cross-site" top-level navigation.
  • Strict: When the value is Strict, or if the value is invalid, the cookie will only be sent along with "same-site" requests.
An important thing to note is, the Cookie Policy Middleware setting for MinimumSameSitePolicy will override your setting of Cookie.SameSite as the matrix below. (Reference: Cookie Policy Middleware)
image
Matrix
Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment