Using Cookie Middleware without ASP.NET Core Identity

Leslie Ramírez
2 min readFeb 7, 2021

Hi everyone! At this time I want to share with you an awesome feature that we can take advantage of, Cookie middleware in .NET Core with core identity. In the beginning, could be harsh to get into it, but we are gonna make it simple as pie.

.NET Core provides the cookie middleware which serializes the user in an encrypted cookie then for the next request, the cookie is validated keeping the session and sets the value into HttpContext.

For getting started you should install the NuGet package Microsoft.AspNeTCore.Authentication.Cookies and make the initial configuration into your Startup class as follow:

Startup.cs

The following table shows the description of a few of the properties you can use with CookieAuthenticationOptions:

The cookies could be created by calling the method SignInAsync of AuthenticationManager. Now I’ll show you a Login method(HTTP Post) that can be called when the user logs in to the web app.

From this code we can extract the following:

  1. The use of claims, by specifying the key values pair, that were added into the list.
  2. The setting of some properties of our authentication and the time expiration of the cookie.
  3. Once the user is authenticated, then is made the authorization process depending on the defined role for the use,
  4. Also, It handles the authentication errors from the authentication process.

SignInAsync uses the notifications that are transmitted by claims identity and set the cookie. The Claims properties can be called by User.Claims as follows:

Finally, if you want to perform the SignOut, this is the way you can do it:

I hope this article has been useful to you, if you liked it, do not forget to comment, hand up, like, and share. 💛 💚 💙 💜

References:

ASP.NET Core Middleware | Microsoft Docs

--

--

Leslie Ramírez
Leslie Ramírez

Written by Leslie Ramírez

I am Microsoft MVP in the award category: Developers technologies, a professional with several years in software development specifically in .NET technology.

No responses yet