Category Archives: Azure

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
Share

ASP.NET Core Tips and Quick Setup Identity System

In this blog post we are going to setup a basic invoice system. It uses the ASP.NET Core identity system. Every step for creating the app is described and at the end you should have a working Invoicing system (being it a bit simple one).

For convenience install the sqlitebrowser

If you did not already installed the dotnet-aspnet-codegenerator already….

And also install the libman Client Side library manage

Create the intial WebApp project

A folder, WebApp, with the new web application is created

Add the required package for the aspnet-codegenerator tool

Optional; add the package below manually so you use the newest version (not the one installed default by the aspnet-codegenerator)

In Visual Studio you can install the package as a nuget package through the Package Manager console with

Scaffold the Identity pages you want to change later on, for now we are going to use a SqLite database and override the Register, Login and Logout pages.

Before we are going to add the migrations we change the name (and location) of the database to dbs/identity.db (we will have separate databases for users and data).

Start Visual Code in the root of the WebApp directory.

Wait a few seconds for the window below to appear and answer Yes. If the window below does not appear press F1 and type “.NET”, then select “.NET: Generate assets for build and debug”.

Open the file appsettings.json in the root of the project and change WebApp.db to dbs/identity.db. Also create the folder dbsin the root of WebApp.

Now we are going to create the Migrations for the initial Identity database and update the database with this migration.

Create the initial migration for the identity system

Create the database

Check the databastructure with SQLite browser

Because we did not use the --auth parameter on initial create of the project our Startup.cs is not prepared to use authentication. Add the line below right after app.UseCookiePolicy

We also have to add the _LoginPartial to _Layout.cshtml because of this. Add the partial _LogingPartial to /Pages/Shared/_Layout.cshtml right before the ul which contains the Home link. Add the line below:

To test authorization place the [Authorize] attribute on the PrivacyModel class and add the using Microsoft.AspNetCore.Authorisation

It is possible to configure password options in /Areas/Identity/IdentityHostingStartUp.cs. For example: do not require an uppercase character in the password:

Now we are going to add our first CRUD pages. We are going to store Invoices with our application. First create a directory Models and place a file Invoice.cs in it with the following code in it:  

Scaffold model CRUD pages   Execute the command below:

The following files will be generated or adjusted:

In /Startup.cs the InvoiceDbContext is added to the services configuration
A directory /Pages/Invoice is created and all files in there are also generated
A directory /Data is created in which a file InvoiceDbContext.cs is stored with the data context for the invoices
The file appsettings.json is modified. A connection string is added for the InvoiceDbContext (we will change this below)

In case you are on Linux. Default the DbContext is using SqlServer, that is not supported on the Linux platform. Goto the file Startup.cs and replace SqlServer with SqLite for the InvoiceDbContext.

Next edit the file appsettings.json and replace the connection string value with "DataSource=dbs/invoices.db"

Next create the initial migrations and update the invoice database for the InvoiceDbContext.

Start the sqlitebrowser to check the structure of your database (/WebApp/dbs/invoice.db)

Now to protect our Invoices folder for unauthorized access add the code below to your services configuration (ConfigureServices) in Startup.cs

References and handy URL’s

This url was very helpfull

Aantekeningen nav ContosoUniversity  tutorial

Some common errors

dotnet restore gives 401 error

Update your credentials for nuget, first download the nuget cli. Next execute the command:

nuget.exe sources update -name RDW -source [url] -username [user] -password [pwd]

Retrieve your name and url with the command:
nuget sources

When you get the error “Scheme already exists: Identity.Application” you probably generated the Identity pages with a different context then ApplicationDbContext.

Build the solution (Ctrl-Shift-B, Enter) en start debugging F5. Navigate to the Privacy page and verify that you have to login before you can continue to this page.

In case you get error “PlatformNotSupportedException: LocalDB is not supported on this platform.” you probably generated the Identity pages with a different context then ApplicationDbContext.

Share