DEV Community

Robertino
Robertino

Posted on

🧩 Exploring the Auth0 ASP.NET Core Authentication SDK

πŸ“˜ The new Auth0 #ASP.NET Core Authentication SDK makes adding authentication and authorization to your web applications a breeze. Learn how.


Auth0 brings you the new ASP.NET Core Authentication SDK, which improves your development experience and better integrates with Auth0 features! Let's take a tour through the main features of the SDK to see how easy it becomes to integrate your ASP.NET applications with Auth0.

The SDK Overview

So far, you were used to relying on the standard Microsoft.AspNetCore.Authentication.OpenIdConnect package to integrate your ASP.NET application with Auth0. That library does its job very well. However, when you move away from implementing the simple login and logout, your code starts becoming verbose until it gets messy.

You can mitigate this issue by implementing your authentication with C# extension methods. But why do it yourself when the experts at Auth0 can provide you with a ready-to-use SDK?

The ASP.NET Core Authentication SDK allows you to write less code to integrate Auth0 authentication and authorization into your ASP.NET applications. It simplifies configuration, supports additional query parameters and refresh tokens, natively supports Auth0 Organizations and user invitations. It is actually a wrapper around the Microsoft.AspNetCore.Authentication.OpenIdConnect library, but it brings you a standard and easy way to integrate Auth0 into your applications.

You can use the SDK for all your ASP.NET applications that require authentication, such as ASP.NET MVC apps, Razor web apps, and Blazor server apps.

Install the ASP.NET Core Authentication SDK

You can install the Auth0 ASP.NET Core SDK by using the NuGet Package Manager UI in Visual Studio, as shown below:

Installing the Auth0 ASP.NET SDK with NuGet Package Manager UI

You can also install it by running the following command in the Package Manager Console:

Install-Package Auth0.AspNetCore.Authentication
Enter fullscreen mode Exit fullscreen mode

Or you can use the following command in a terminal window:

dotnet add package Auth0.AspNetCore.Authentication
Enter fullscreen mode Exit fullscreen mode

Independently of your preferred approach, you will get the Auth0.AspNetCore.Authentication dependency in your ASP.NET project.

The Basic Login Use Case

Let's start to take a look at the way the new SDK improves your developer experience. Of course, you need an Auth0 account to integrate your ASP.NET application with Auth0. If you haven't, you can sign up for a free one right now. Follow the Auth0 ASP.NET Core Authentication SDK quickstart to register your application and get your application keys.

The following is the typical code you write to enable authentication in your ASP.NET application when using Microsoft.AspNetCore.Authentication.OpenIdConnect:

public void ConfigureServices(IServiceCollection services)
{
  services.AddAuthentication(options => {
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
  })
  .AddCookie()
  .AddOpenIdConnect("Auth0", options => {
    options.Authority = $"https://{Configuration["Auth0:Domain"]}";
    options.ClientId = Configuration["Auth0:ClientId"];
    options.CallbackPath = new PathString("/callback");
    options.TokenValidationParameters = new TokenValidationParameters
    {
      NameClaimType = "name"
    };
    options.Events = new OpenIdConnectEvents
    {
      OnRedirectToIdentityProviderForSignOut = (context) =>
      {
        var logoutUri = $"https://{Configuration["Auth0:Domain"]}/v2/logout?client_id={Configuration["Auth0:ClientId"]}";

        var postLogoutUri = context.Properties.RedirectUri;
        if (!string.IsNullOrEmpty(postLogoutUri))
        {
          if (postLogoutUri.StartsWith("/"))
          {
            // transform to absolute
            var request = context.Request;
            postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri;
          }
          logoutUri += $"&returnTo={ Uri.EscapeDataString(postLogoutUri)}";
        }

        context.Response.Redirect(logoutUri);
        context.HandleResponse();

        return Task.CompletedTask;
      }
    };
  });
}
Enter fullscreen mode Exit fullscreen mode

I will not go through that code to explain every single step. You just need to know it implements the login and logout features in your applications by relying on the Auth0 Universal Login page.

By using the Auth0 ASP.NET Core Authentication SDK, your code shortens as follows:

public void ConfigureServices(IServiceCollection services)
{
  services.AddAuth0WebAppAuthentication(options =>
  {
    options.Domain = Configuration["Auth0:Domain"];
    options.ClientId = Configuration["Auth0:ClientId"];
  });
}
Enter fullscreen mode Exit fullscreen mode

Impressive, isn't it? 😲

The SDK takes care of all the configuration stuff you previously needed to do manually. And that's just the beginning! πŸŽ‰

Read more...

Top comments (0)