Monthly Archives: March 2020

NET CORE 3.1 Cookie Authentication

In this short post I will show you how to implement Cookie authentication with Visual Studio 2019 and ASP.NET CORE 3.1.

Create a new project

In Visual Studio create a new .NET CORE Web Application project. Press Next

Configure the project

Give it a name, “BasicCookies” for example. Press Create.

Select Empty web application

Create a empty web application, press Create. This will create the solution structure as shown below.

In the generated startup.cs replace the entire Configure function with the code below.

Also replace the entire ConfigureServices function with the code below.

Now create a new folder “Controllers” and add a new class “HomeController” to it. Replace the entire generated contents with the code shown below. The code below shows that a user ClaimsPrincipal can have multiple identities coming from different sources.

As you can see we have three actions. Two action return the view for the given action and the third, Authenticate, returns to the Index view.

Create the Index view and the ProtectedPage view. As you can see the ProtectedPage view has an Authorize attribute. This means that we first have to authorize before we can access the view.

Create a new folder Views and within the Views folder create a folder Home. Right click on the new Home folder and select Add -> View.

Create a new razor view

Replace the entire file contents with the contents below. Do the same for the ProtectedPage view, replace the contents with something you will recognize as the protected page…

Now you can start debugging the site. When you start the web application the home page will show up. Once you navigate to https://localhost:[port]/home/protectedpage you will be redirected to the home page. The Authenticate method has authenticated you and a cookie is stored in the browser.

Your Homepage after pressing the Login link

Using Moq for testing

Install the nuget Moq package. Below is a simple example to create a mock for a database implementation (which is also a mock :-)).