DEV Community

Cover image for Securing ASP.NET Core MVC 6 App - add authentication to the application - Part 1
Emanuele Bartolesi
Emanuele Bartolesi

Posted on • Updated on

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

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"
  }


Enter fullscreen mode Exit fullscreen mode

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;


Enter fullscreen mode Exit fullscreen mode

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"];
    });


Enter fullscreen mode Exit fullscreen mode

And then, add the following line of code, above the app.UseAuthorization(); statement.



app.UseAuthentication();


Enter fullscreen mode Exit fullscreen mode

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;


Enter fullscreen mode Exit fullscreen mode

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);
  }
}


Enter fullscreen mode Exit fullscreen mode

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)
            {
                <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"navbar-collapse collapse d-sm-inline-flex justify-content-between"</span><span class="nt">&gt;</span>
                    <span class="nt">&lt;ul</span> <span class="na">class=</span><span class="s">"navbar-nav flex-grow-1"</span><span class="nt">&gt;</span>
                        <span class="nt">&lt;li</span> <span class="na">class=</span><span class="s">"nav-item"</span><span class="nt">&gt;</span>
                            <span class="nt">&lt;a</span> <span class="na">class=</span><span class="s">"nav-link text-dark"</span> <span class="na">asp-area=</span><span class="s">""</span> <span class="na">asp-controller=</span><span class="s">"Home"</span> <span class="na">asp-action=</span><span class="s">"Index"</span><span class="nt">&gt;</span>Home<span class="nt">&lt;/a&gt;</span>
                        <span class="nt">&lt;/li&gt;</span>
                        <span class="nt">&lt;li</span> <span class="na">class=</span><span class="s">"nav-item"</span><span class="nt">&gt;</span>
                            <span class="nt">&lt;a</span> <span class="na">class=</span><span class="s">"nav-link text-dark"</span> <span class="na">asp-area=</span><span class="s">""</span> <span class="na">asp-controller=</span><span class="s">"Home"</span> <span class="na">asp-action=</span><span class="s">"Privacy"</span><span class="nt">&gt;</span>Privacy<span class="nt">&lt;/a&gt;</span>
                        <span class="nt">&lt;/li&gt;</span>
                        <span class="nt">&lt;li</span> <span class="na">class=</span><span class="s">"nav-item"</span><span class="nt">&gt;</span>
                            <span class="nt">&lt;a</span> <span class="na">class=</span><span class="s">"nav-link text-dark"</span> <span class="na">asp-area=</span><span class="s">""</span> <span class="na">asp-controller=</span><span class="s">"Account"</span> <span class="na">asp-action=</span><span class="s">"Logout"</span><span class="nt">&gt;</span>Logout<span class="nt">&lt;/a&gt;</span>
                        <span class="nt">&lt;/li&gt;</span>
                    <span class="nt">&lt;/ul&gt;</span>
                <span class="nt">&lt;/div&gt;</span>
            }
            else
            {
                <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"navbar-collapse collapse d-sm-inline-flex justify-content-between"</span><span class="nt">&gt;</span>
                    <span class="nt">&lt;ul</span> <span class="na">class=</span><span class="s">"navbar-nav flex-grow-1"</span><span class="nt">&gt;</span>
                        <span class="nt">&lt;li</span> <span class="na">class=</span><span class="s">"nav-item"</span><span class="nt">&gt;</span>
                            <span class="nt">&lt;a</span> <span class="na">class=</span><span class="s">"nav-link text-dark"</span> <span class="na">asp-area=</span><span class="s">""</span> <span class="na">asp-controller=</span><span class="s">"Account"</span> <span class="na">asp-action=</span><span class="s">"Login"</span><span class="nt">&gt;</span>Login<span class="nt">&lt;/a&gt;</span>
                        <span class="nt">&lt;/li&gt;</span>
                    <span class="nt">&lt;/ul&gt;</span>
                <span class="nt">&lt;/div&gt;</span>
            }
Enter fullscreen mode Exit fullscreen mode
Enter fullscreen mode Exit fullscreen mode




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

Top comments (0)