Build app authentication with .NET Core, Auth0 and Twilio SendGrid

August 20, 2024
Written by
Eman Hassan
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by

Build app authentication with .NET, Auth0 and Twilio SendGrid

Introduction

Authentication is essential for almost every application, but it can feel complicated and overwhelming to implement securely. Luckily, tools like Auth0 make it easier by handling the authentication process for you. In this post, you'll learn how to create a .NET Core MVC web application with Auth0 authentication and Twilio SendGrid email notifications for user registration.

Prerequisites

In order to be successful in this tutorial, you will need the following:

Building the app

Open Visual Studio. Click on Create a new project, then search for asp.net core web app. Click on ASP.NET Core Web App (Model-View-Controller). If there are multiple matching projects, be sure you select the project using the C# code base.Click Next.

Create ASP.NET Core MVC Web App

Add a name to your project and click Next. Select your .NET version, and set the Authentication type to None. Keep the rest of the defaults and click Create.

Choose .net framework

You will see the project created with a working MVC web app. If you try to run it, you will see a starting home page. You can learn more about MVC here.

Install Auth0 .NET SDK

In the top menu, click Tools > NuGet Package Manager > Manage NuGet Packages for Solution.

open package manager

Using the search bar and the Browse tab, browse for Auth0.AspNetCore.Authentication. Install it to the project as shown below. A popup will show up to apply dependencies and accept licenses. Click Apply, then Accept, to proceed.

Install auth0 SDK

Configure Auth0 application

Log in to your account at auth0.com. From the Auth0 dashboard, go to Applications > Applications > Create Application. Choose a name for your application. Select Regular Web Applications and click Create.

Select the settings tab for your application and review the Domain, Client ID and Client Secret for the application. You will use these later to connect to the application from the MVC application in Visual Studio.

Explore app settings

Then scroll down to the Application URIs section and add the following URLs to allow the connection between your localhost web app and the Auth0 application and authentication flow.

  • Allowed Callback URLs: https://localhost:7601/callback
  • Allowed Logout URLs: https://localhost:7601/
  • Allowed Web Origins: https://localhost:7601

Be sure to click Save Changes before you continue.

Note that the port number of the localhost might change depending on which port Visual Studio used when you run the MVC application locally. Make sure you fix the port number in Auth0 settings if it shows up differently from what is listed above.

Configure SendGrid in Auth0 Dashboard

Before you can start sending user registration emails to the users, there are a few more mandatory steps you’ll need to complete in your SendGrid account:

Once you’ve completed the above steps, you’ll need to create a new API Key. Keep this key somewhere safe as you will need it in the Auth0 dashboard.

Go to Auth0 dashboard and in the left navigation, click Branding > Email Provider. Then, make sure you enable the option to Use my own email provider. Choose SendGrid from the providers list as shown below.

Select email provider

Scroll down the page and you will be able to add your SendGrid API key and your SendGrid verified from email.

SendGrid Settings

Configure your MVC application

Go back to Visual Studio and open the appsettings.json file. Replace the code in that file with the code below. Replace the placeholder values with the corresponding Domain, Client ID and Client Secret from your Auth0.

{
  "Auth0": {
    "Domain": "YOUR_AUTH0_DOMAIN",
    "ClientId": "YOUR_AUTH0_CLIENT_ID",
    "ClientSecret": "YOUR_AUTH0_CLIENT_SECRET"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Open the program.cs file, and replace the code in the file with the following code. This includes adding the function AddAuth0WebAppAuthentication, which is responsible for loading Auth0 with your Auth0 application credentials.

using Auth0.AspNetCore.Authentication;
var builder = WebApplication.CreateBuilder(args);
// Configure Auth0
builder.Services.AddAuth0WebAppAuthentication(options =>
{
    options.Domain = builder.Configuration["Auth0:Domain"];
    options.ClientId = builder.Configuration["Auth0:ClientId"];
    options.ClientSecret = builder.Configuration["Auth0:ClientSecret"];
    options.Scope = "openid profile email";
});
// 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");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

Create login and logout actions

Right click the Controllers folder, then click Add > Controller. Select MVC Controller - Empty and click Add.

Choose empty controller

Name your controller as AccountController.cs. Replace the following code in your controller:

using Auth0.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
namespace ASPNetCore_MVC_WebAPP.Controllers
{
    public class AccountController : Controller
    {
        public async Task Login(string returnUrl = "/")
        {
            await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, new AuthenticationProperties
            {
                RedirectUri = returnUrl
            });
        }
        public async Task Logout()
        {
            await HttpContext.SignOutAsync(Auth0Constants.AuthenticationScheme, new AuthenticationProperties
            {
                RedirectUri = Url.Action("Index", "Home")
            });
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        }
    }
}

Now you need to add Login/Logout links to your MVC application’s layout header. Go to the Viewsfolder then click on Shared, then open _Layout.cshtml . Replace the code in this file with the following code to include the nav items for Login and Logout.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - ASPNetCore_MVC_WebAPP</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/ASPNetCore_MVC_WebAPP.styles.css" asp-append-version="true" />
</head>
<body>
    <header>
        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
            <div class="container-fluid">
                <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">ASPNetCore_MVC_WebAPP</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <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>
                        @if (User.Identity.IsAuthenticated)
                        {
                            <li><a class="nav-link text-dark" asp-controller="Account" asp-action="Logout">Logout</a></li>
                        }
                        else
                        {
                            <li><a class="nav-link text-dark" asp-controller="Account" asp-action="Login">Login</a></li>
                        }
                    </ul>
                </div>
            </div>
        </nav>
    </header>
    <div class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </div>
    <footer class="border-top footer text-muted">
        <div class="container">
            &copy; 2024 - ASPNetCore_MVC_WebAPP - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
        </div>
    </footer>
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>
    @await RenderSectionAsync("Scripts", required: false)
</body>
</html>

Run the application

Now your application has authentication configured. You can run the application in Visual Studio by clicking on the run button on the top toolbar as shown below.

Start the application

A console window will appear with the localhost url the application is running on. Make sure to revise it and match it with the URLs you have configured in Auth0.

Console window

Then browse to the localhost URL and you will see the web app showing up as shown below. You can then click Login.

Application run

The login action will redirect you to the Auth0 generated login page. Here, you can register as a new user and login to the app.

auth0 login page

When signup and login are successful, it will redirect back to your application. When you are already logged in, the Login button will now show as Logout as shown below.

Logout button

You can then secure any action page in the controllers of the MVC app with the annotation [Authorize] above the function if you want to have a page accessible to only logged in users.

To see all your registered users, go back to the Auth0 dashboard and click on User Management > Users. From here,you will be able to see the list of all users registered to your application.

Registered users will have a welcome email sent to their inbox with Auth0’s default template.

You can customize the email templates in Auth0 by navigating to Branding > Email Templates.

Customize your Auth0 Application

It is a good idea to extend your application through customization. You can start on Auth0’s login page by adding your logo. Customize how it looks by clicking on Branding > Universal login in the left navigation bar in the Auth0 dashboard. When you are ready to publish your application to a custom domain, you will be able to have the login page tied to your custom domain through the configuration in Branding > Custom domains.

What's next for Auth0 Applications?

At the conclusion of this tutorial, you will have acquired the skill sets to set up and utilize Twilio SendGrid APIs, and to create, configure and run ASP.NET Core MVC web applications with Auth0 authentication.

For more advanced customization for your Auth0 application, like implementing certain login or user registration events, you can explore Auth0 Actions. Actions can allow you to customize the authentication flow according to your application’s needs.

You can find the full code for this tutorial here.

Eman Hassan, a dedicated software engineer, prioritizes innovation, cutting-edge technologies, leadership, and mentorship. She finds joy in both learning and sharing expertise with the community. Explore more on her Medium profile: https://emhassan.medium.com/ .