Problem

How to implement cookie authentication in ASP.NET Core 2.0

Solution

Create an empty project and update Startup to configure services and middleware for MVC and Authentication,

Create a model to receive login details,

Create a login page,

Create a controller for Login and Logout actions,

Finally add a controller to secure using [Authorize] attribute,

Discussion

Authentication middleware intercepts incoming requests and checks for the existence of a cookie holding encrypted user data.

Cookie Authentication Options

When setting up cookie services there are several options to tweak its behavior like,

Events

Cookie Authentication allows developers to hook into events at various lifecycle stages of authentication process. For instance you could log successful sign-ins using OnSignedIn or use OnValidatePrincipal (runs on every request) to invalidate the user (e.g. if you want to force sign-out).

Note
For some of the events (e.g. OnValidatePrincipal) the HttpContext.User is null, use the Principalproperty of event’s context parameter.

Sign Out

To delete the authentication cookie, and thus sign out the user, you call HttpContext.SignOutAsync() method with the authentication scheme name.

Cookie Expiration

In order to set an absolute expiry time for the identity/cookie (as opposed to sliding expiration), you could use AuthenticationProperties,

Migrating from ASP.NET Core 1.x

Prior to ASP.NET Core 2.0 the cookie authentication was setup little differently. It was setup in Configure() method and some of the property names were different too. Below is from the project I originally created using ASP.NET Core 1.x,

Also the sign-in and sign-out methods were accessed using Authentication property on HttpContext,

Source Code

GitHub