Cookie Based Authentication In ASP.net Core MVC with any existing user table.
In any modern web app, we can authenticate our targeted users in multiple ways. In old .net there is a dedicated authentication framework named as ASP.net Identity. In the newest open source .net has the same framework built into itself. In this article we are going to learn how we can implement cookie based authentication (the easy way) without using identity framework from scratch.
For this demo I have choose a empty Model-Controller-View template project to start with. You can choose any editor or IDE as long as you have dotnet core SDK installed in your desired platform. (I guess you know that already)

Basic Configuration:
In the Startup.cs class create a authentication middleware and add cookie extention method to it.

In this authentication method we have passed authentication scheme and add a AddCookie() method to it in order to work correctly. AuthenticationScheme is useful when there are multiple instance of cookie auth and we want to authorize with a specific scheme. In our case we have passed the default scheme which is a static property built into the app itself and its value is -“Cookies”. Allthough you can set any string value that can differentiate the scheme.
Now in startup.cs add UseAuthentication() before Routing() method to set HttpContext.User property and run the auth middleware successfully.
N.B: The method ordering is very sensitive.

Cookie Policy Configuration:
To enable cookie policy capabilities, we have to add this middleware to the app processing pipeline.

The default MinimumSameSitePolicy value is SameSiteMode.Lax to permit OAuth2 authentication
Login Action:
In Controller:

In View:

Authentication Cookie Creation:
In the post Login method , I haven’t done any validation for demo purpose. You can do what ever validation suits your application. But just checking for null or empty value.

So to create a cookie holding all the neccesary information about user, we have to construct a ClaimsPrinciple. The user information is automatically serialized and stored in the cookie.

Create a ClaimsIdentity with required Claim object and call HttpContext.SignInAsync method to sign in to the system.
finally the logout method

And at last one more key changes to work this thing is add some configuration to the ConfigureService method in startup.cs class. Make sure you add service.AddMvc() to this method.

Now testing time ;)


Everything is in this github repository ! Hope this guideline helps :)
