Cookie Authentication in .net core

Tuesday, October 16, 2018

By: Chris Dunn

Most web applications today, with personalization and integration, require authentication to access the site. One of the more basic and simplest forms of authentication is using cookies. If you have a history with .net, cookie authentication is what you will most be familiar with.

As with all things, .net core has a slightly different approach to implementing cookie authentication, so I thought I would walk through a basic implementation you can use as a starting point.

Setup Authentication

With authentication, we once again turn to the middle ware and the Startup.cs file.  We need to add authentication middle ware to the services in ConfigureServices method.  In the code below, we are specifying that the authentication should use cookies and then adding a cookie definition with options.  Those options include the LoginPath (containing the login page), AccessDeniedPath (containing unauthorized messaging), and the name of the cookie.  There are more CookieAuthenticationOptions that can be found here.

        public void ConfigureServices(IServiceCollection services)


            //Add cookie authentication configuration
                    options =>
                        options.LoginPath = new PathString("/auth/signin");
                        options.AccessDeniedPath = new PathString("/auth/denied");
                        options.Cookie.Name = "ClientCookieAuth";


Once the cookie authentication has been configured, we need to add it to the pipleline in the Configure method, so we can actually use it.

        public void Configure(IApplicationBuilder app)


Setup Authorization

After setting up Authentication, we need to mark our controllers or actions that require Authorization. Only those users that are authenticated can access authorized controllers and actions.

public class HomeController: Controller{}

Creating the Cookie on SignIn

We need a sign in page to allow the user to actually be authenticated. We do this in the method called when posting the sign in form. For our example we are going to use claims based security.

A Claim is basically making a statement about an certain entity, or a user. We can have a collection of claims which we collect into a ClaimsIdentity. We then create a ClaimsPrincipal or user with that ClaimsIdentity. All together, it allows us to create a authenticated user which contains information about itself.

var claims = new List
new Claim(ClaimTypes.Name, user.EmailAddress , ClaimValueTypes.String, "Site"),
new Claim("id", user.Id.ToString() , ClaimValueTypes.String, "Site")

var identity = new ClaimsIdentity(claims, "Password");
var principal = new ClaimsPrincipal(identity);

We then use the ClaimsPrincipal we just created to create the authentication cookie by calling HttpContext.SignInAsync along with the principal we also include a timeout (ExpiresUtc ) to tell the authentication cookie when to expire or auto-logout.

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                    new AuthenticationProperties
                        ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                        AllowRefresh = true,
                        IsPersistent = false

Clearing the Cookie on SignOut

To Sign Out and clear the authentication cookie we call HttpContext.SignOutAsync as in the following code example.

        public async Task SignOut()
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction(nameof(SignIn));

This was a pretty straight forward example but there are many different options and settings to help you configure your authentication to best fit your requirements.

Tags: c# cookies authentication

Copyright 2019 Cidean, LLC. All rights reserved.

Proudly running Umbraco 7. This site is responsive with the help of Foundation 5.