🧩 Exploring the Auth0 ASP.NET Core Authentication SDK
Tags: security, programming, dotnet
Published: 2021-10-20 20:17:32

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

### <br>

Auth0 brings you the new [ASP.NET Core Authentication SDK](https://github.com/auth0/auth0-aspnetcore-authentication), 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](https://auth0.com/blog/using-csharp-extension-methods-for-auth0-authentication/). 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](https://github.com/auth0/auth0-aspnetcore-authentication) 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](https://auth0.com/docs/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](https://images.ctfassets.net/23aumh6u8s0i/52AB2b6XDotBDpBlPPR1F7/f4b71a1b33c3cecb56b46d96b2e27788/installing-auth0-aspnet-core-authentication-sdk.png)

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

```powershell
Install-Package Auth0.AspNetCore.Authentication
```

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

```bash
dotnet add package Auth0.AspNetCore.Authentication
```

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 <a href="https://auth0.com/signup" data-amp-replace="CLIENT_ID" data-amp-addparams="anonId=CLIENT_ID(cid-scope-cookie-fallback-name)">sign up for a free one</a> right now. Follow [the Auth0 ASP.NET Core Authentication SDK quickstart to register your application and get your application keys](https://auth0.com/docs/quickstart/webapp/aspnet-core#configure-auth0). 

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

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

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](https://auth0.com/docs/login/universal-login) page.

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

```csharp
public void ConfigureServices(IServiceCollection services)
{
  services.AddAuth0WebAppAuthentication(options =>
  {
    options.Domain = Configuration["Auth0:Domain"];
    options.ClientId = Configuration["Auth0:ClientId"];
  });
}
```

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...](https://auth0.com/blog/exploring-auth0-aspnet-core-authentication-sdk/?utm_source=content_synd&utm_medium=sc&utm_campaign=dotnet)