🌤

Securing ASP.NET Core MVC 6 App - add authentication to the application - Part 1

Loading...
 

Published on

June 15, 2022

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

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

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

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.

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

Image description

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

Image description

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

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

Add authentication to the project

Open the appsettings.json file and add the section Auth0 at the end of the file.

"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

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

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.

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.

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:

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:

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:

@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 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 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

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

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

React, comment and follow on