Securing ASP.NET Core MVC 6 App - add authentication to the application - Part 1
Published: 2022-06-15 15:00:02

Even though everyone around is always talking about about applications written in React, Angular, Vue, ASP.NET Core is alive and enjoying a lot adoption, especially in the enterprise applications.

In this series, I will show you how to use Auth0 in a ASP.NET MVC 6 application.

Let's start.

## Create an empty ASP.NET Core MVC 6 Application with VS2022
Open Visual Studio 2022 and search for the template ASP.NET MVC.
Select the right template and click on "Next".

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sxaalfuw34uznopwx71o.png)

Choose a name of the application and the path to save the source code.
Then select the Framework .NET 6 and keep all the default values in the additional information form of the wizard.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wz1to3uf4fe6mibp5v14.png)

When the project is created, open the file "launchSettings.json" and save the application url value into a temporary notepad file.
We need it in the following steps.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/94j8lh6rbrvqrfcvk44m.png)

## Register an app with Auth0
Before making changes in our ASP.NET MVC Application, we must register an app with Auth0.
If you don't have an account, you can create a free one [here](https://a0.to/signup-for-auth0).

Once you are in the Dashboard, navigate to the Applications section and click on "Create Application".

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f24d8z13bm256pxwt8j5.png)

In the new screen provide the name of your application and select "Regular Web Applications" in the application type section.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p6iqawivr9yrndiebl8r.png)

After that, click on the "Settings" tab and take note in the notepad file of the Auth0 domain and the ClientID.
For the moment we don't need the Client Secret value.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/suqr1rumebcw9m7zwofi.png)

Scroll down a little bit the page and insert the value of the application url that you took a note before inside the Allowed Callback URLs and Allowed Logout URLs.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4q4zz5lm4mzh7uh1fxfd.png)

## Add authentication to the project
Open the appsettings.json file and add the section Auth0 at the end of the file.

```json
 "Auth0": {
    "Domain": "DOMAIN",
    "ClientId": "CLIENT_ID"
  }
```
Replace the placeholders with the values from your notepad.

From the NuGet package manager, add the package called Auth0.AspNetCore.Authentication.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dka2qxl2375vftjiq907.png)

In the root of the project add a file called "GlobalUsing.cs" and add the following line of code:

```csharp
global using Auth0.AspNetCore.Authentication;
```
We will add other using later.

In the Program.cs file add the code below, after the builder creation at the top.

```csharp
builder.Services
    .AddAuth0WebAppAuthentication(options => {
        options.Domain = builder.Configuration["Auth0:Domain"];
        options.ClientId = builder.Configuration["Auth0:ClientId"];
    });
```
And then, add the following line of code, above the app.UseAuthorization(); statement.

```csharp
app.UseAuthentication();
```
Now we are ready to implement the real login flow.

## Implement the login and logout flows
First of all, add the GlobalUsing file, the following using statements:

```csharp
global using Microsoft.AspNetCore.Authentication;
global using Auth0.AspNetCore.Authentication;
global using Microsoft.AspNetCore.Mvc;
global using Microsoft.AspNetCore.Authorization;
global using Microsoft.AspNetCore.Authentication.Cookies;
```

Now, you can create a new controller in the Controllers folder, called AccountController.
You can copy and paste the following code:

```csharp
public class AccountController : Controller
{
    public async Task Login(string returnUrl = "/")
    {
        var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
            .WithRedirectUri(returnUrl)
            .Build();

        await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties);
    }

  [Authorize]
  public async Task Logout()
  {
    var authenticationProperties = new LogoutAuthenticationPropertiesBuilder()
        .WithRedirectUri(Url.Action("Index", "Home"))
        .Build();

    await HttpContext.SignOutAsync(Auth0Constants.AuthenticationScheme, authenticationProperties);
    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
  }
}
```
Now it's time to change the UI based on the authentication state.
Open the layout file located in Views/Shared/_Layout.cshml and change the following section as below:

```html
                @if (User.Identity.IsAuthenticated)
                {
                    <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                        <ul class="navbar-nav flex-grow-1">
                            <li class="nav-item">
                                <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-dark" asp-area="" asp-controller="Account" asp-action="Logout">Logout</a>
                            </li>
                        </ul>
                    </div>
                }
                else
                {
                    <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                        <ul class="navbar-nav flex-grow-1">
                            <li class="nav-item">
                                <a class="nav-link text-dark" asp-area="" asp-controller="Account" asp-action="Login">Login</a>
                            </li>
                        </ul>
                    </div>
                }
```

## Run the application
Now we are ready to test the entire login and logout flows.
Launch a debug session from Visual Studio by pressing F5 or manually with the debug button.
You should see a web page like this:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7xyem0prtxrlqow2q7pk.png)
If you click on the Login link, the application redirects you to the Auht0 login page.
Click on Signup to create a new user account.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ixyht5u9tpc9ne7b2h1d.png)
As you can see in the image below, out-of-the-box you have a password complexity summary. It's very useful and you can also configure that from the Auth0 Dashboard.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xctpjzlqbts6p9hre5s2.png)

If you register a new account or if you login with an existing one, you can see the application up&running with the logout button displayed in the main menu.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bggnrfhpgjmw0kliuf9a.png)

## Conclusion
In this first part of the series we have learned how to implement the basic authorization flow with Auth0.
In the next parts we will learn how to add a profile page, how to use the roles and other cool stuff related to Auth0 and ASP.NET MVC.

You can find the source code at this [link](https://github.com/kasuken/Auth0-Samples)