DEV Community

Robertino
Robertino

Posted on

Add Authentication to Your ASP.NET Core MVC Application

Learn how to add authentication to your ASP.NET Core MVC Application by using Auth0.


ASP.NET Core MVC is a popular framework for building web applications in .NET. It uses the well-known Model-View-Controller design pattern, which helps you achieve separation of concerns for your application UI. In this article, you will learn how to integrate authentication in an ASP.NET Core MVC application by using the Auth0 ASP.NET Core Authentication SDK.

The Sample Application

To focus adding authentication, you will use an existing ASP.NET Core MVC application, which will be described in a moment.

Prerequisites

Before starting, make sure you have the .NET 6 SDK installed on your machine. In fact, the application you are going to modify uses some features of C# 10. To get a quick overview of what's new with .NET 6, check out this article.

Also, this article will use the .NET CLI to build and run the application, but you can use Visual Studio 2022 if you prefer.

Get and run the sample application

You can get the sample application by running the following command in a terminal window:

git clone -b starter --single-branch https://github.com/auth0-blog/acme-aspnet-mvc.git
Enter fullscreen mode Exit fullscreen mode

Once you download it, move to the acme-aspnet-mvc folder and type the following command to launch the application:

dotnet watch
Enter fullscreen mode Exit fullscreen mode

This command will run the sample application and wait for possible changes to the code. If you change the application code, it will be automatically rebuilt.

Note that some specific changes to your code, known as rude edits, may require restarting your application. Read this to learn more.

Now, point your browser to https://localhost:7095. You should get the following page:

ACME website home page

This is the home page of the fictional company ACME Corporation.

By clicking the Catalog link in the header, you can navigate their catalog, which will look as shown below:

ACME catalog

Actually, the Buy now! button is not working. This page is just a placeholder for a page that users would expect to be protected. In other words, only authenticated users should access the catalog page. This is what you are going to implement in the next few sections.

Register with Auth0

Before making any changes, you must register the application with Auth0. You need an Auth0 account, of course. If you don't yet have it, you can sign up for a free one.

Once in the dashboard, move to the Applications section and follow these steps:

  1. Click on Create Application.
  2. Provide a friendly name for your application (for example, ACME Web App) and choose Regular Web Applications as the application type.
  3. Finally, click the Create button.

These steps make Auth0 aware of your ASP.NET Core MVC application and will allow you to control access.

After the application has been created, move to the Settings tab and take note of your Auth0 domain and your client id. Then, in the same form, assign the value https://localhost:7095/callback to the Allowed Callback URLs field and the value https://localhost:7095/ to the Allowed Logout URLs field.

The first value tells Auth0 which URL to call back after the user authentication. The second value tells Auth0 which URL a user should be redirected to after their logout.

Click the Save Changes button to apply them.

Now, head back to the root folder of the sample application project, open the appsettings.json configuration file, and replace its content with the following:

// appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Auth0": {
    "Domain": "YOUR_DOMAIN",
    "ClientId": "YOUR_CLIENT_ID"
  }
}
Enter fullscreen mode Exit fullscreen mode

Replace the placeholders YOUR_DOMAIN and YOUR_CLIENT_ID with the respective values taken from the Auth0 dashboard.

Add Authentication

At this point, the basic settings for connecting your application to Auth0 are in place. To add authentication, you need to apply some changes to your application and use those settings. Let's go one step at a time.

Install the Auth0 SDK

As your first step, install the Auth0 ASP.NET Core Authentication SDK by running the following command in your terminal window:

dotnet add package Auth0.AspNetCore.Authentication
Enter fullscreen mode Exit fullscreen mode

The Auth0 ASP.NET Core SDK lets you easily integrate OpenID Connect-based authentication in your app without dealing with all its low-level details.

If you want to learn a bit more, this blog post provides you with an overview of the Auth0 ASP.NET Core SDK.

Set up authentication

Now, let's modify the application code to support authentication. Open the Program.cs file and change its content as follows:

// Program.cs

using Auth0.AspNetCore.Authentication; // ๐Ÿ‘ˆ new code

var builder = WebApplication.CreateBuilder(args);

// ๐Ÿ‘‡ new code
builder.Services
    .AddAuth0WebAppAuthentication(options => {
      options.Domain = builder.Configuration["Auth0:Domain"];
      options.ClientId = builder.Configuration["Auth0:ClientId"];
    });
// ๐Ÿ‘† new code

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication(); // ๐Ÿ‘ˆ new code
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
Enter fullscreen mode Exit fullscreen mode

Following the highlighted code, you added a reference to the Auth0.AspNetCore.Authentication namespace at the beginning of the file. Then you invoked the AddAuth0WebAppAuthentication() method with the Auth0 domain and client id as arguments. Finally, you called the UseAuthentication() method to enable the authentication middleware.

These changes lay the groundwork for supporting authentication via Auth0.

Read more...

Top comments (0)