Add Authentication to Your ASP.NET Core MVC Application
Tags: dotnet, programming, security
Published: 2021-12-20 11:54:47

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

### <br>

ASP.NET Core MVC is a popular framework for building web applications in .NET. It uses the well-known [Model-View-Controller design pattern](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller), 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](https://dotnet.microsoft.com/download/dotnet/6.0) 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](https://auth0.com/blog/dotnet6-whats-new/).

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:

```shell
git clone -b starter --single-branch https://github.com/auth0-blog/acme-aspnet-mvc.git
```

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

```shell
dotnet watch
```

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](https://devblogs.microsoft.com/dotnet/introducing-net-hot-reload/#supported-unsupported-changes-and-languages) to learn more.

Now, point your browser to [`https://localhost:7095`](https://localhost:7095). You should get the following page:

![ACME website home page](https://images.ctfassets.net/23aumh6u8s0i/2iq9O4t0D7KNYj2gqbhkWz/c47d25c5ff96c38fa6909db3f07c52ef/acme-website-homepage.png)

This is the home page of the fictional company [ACME Corporation](https://en.wikipedia.org/wiki/Acme_Corporation).

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

![ACME catalog](https://images.ctfassets.net/23aumh6u8s0i/4HFEvrezMulNWyEldb4Yjk/696b9018a58adfa7b4591da6a54161c5/acme-catalog.png)

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 <a href="https://auth0.com/signup" data-amp-replace="CLIENT_ID" data-amp-addparams="anonId=CLIENT_ID(cid-scope-cookie-fallback-name)">sign up for a free one</a>.

Once in the dashboard, move to the [Applications section](https://manage.auth0.com/#/applications) 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:

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

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](https://github.com/auth0/auth0-aspnetcore-authentication) by running the following command in your terminal window:

```shell
dotnet add package Auth0.AspNetCore.Authentication
```

The Auth0 ASP.NET Core SDK lets you easily integrate [OpenID Connect](https://auth0.com/docs/authorization/protocols/openid-connect-protocol)-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](https://auth0.com/blog/exploring-auth0-aspnet-core-authentication-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:

```csharp
// 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();
```

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...](https://auth0.com/blog/add-authentication-aspnet-core-mvc/?utm_source=content_synd&utm_medium=sc&utm_campaign=aspnet)