🌤

Securing .NET 6 Minimal API with Auth0

webdevapiauthenticationsecurity
Loading...
 

1

 

Published on

May 24, 2022

To better understand the content of this article, you should know at least the basics of the Minimal API. In this case, I can suggest to follow the official documentation at this link or the Microsoft Learn path about Minimal API and ASP.NET Core at this link

Creating the Minimal API project

You can create a Minimal API project directly from the command prompt. Open your favorite terminal (I use Windows Terminal) and execute the following command:

dotnet new webapi -minimal -o SampleAuth0

Then, switch to the directory SampleAuth0 and launch VS Code (or Visual Studio 2022).

Creating the Minimal API project

Add a new API endpoint

The template of the Minimal API includes only one GET endpoint with the route "/weatherforecast".

Project Template

Below the default endpoint, add the code below to add another endpoint (in this example a POST with a WeatherForecast model).

app.MapPost("/weatherforecast", (WeatherForecast forecast) =>
{
    return forecast;
})
.WithName("PostWeatherForecast");

If you launch the application and navigate to the url /swagger, you should see the Swagger documentation for our new API.

swagger documentation

Create the API in your Auth0 account

First of all we need to create an Auth0 API in the Auth0 Dashboard. If you don't have an account, you can create an account here.

From the Auth0 Dashboard, navigate to Applications -> APIs and click on Create API button on the right pane.

Auth0 Dashboard

In the new windows insert the data for the Name, the Identifier (it should be the url of your web api) and the Signing Algorithm.

create an api

Configure the project

Add the NuGet package to the project called: Microsoft.AspNetCore.Authentication.JwtBearer

Now you are ready to add the following code in the Program.cs file.

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.Authority = builder.Configuration["Auth0:Domain"];
    options.Audience = builder.Configuration["Auth0:Audience"];
});

builder.Services.AddAuthorization(o =>
    {
        o.AddPolicy("weatherforecast:read-write", p => p.
            RequireAuthenticatedUser().
            RequireClaim("permissions", "weatherforecast:read-write"));
    });

app.UseAuthentication();
app.UseAuthorization();

You can insert this code snippet at line 16 of the Program.cs file.

In the file appsettings.json, add the JSON section below and replace the placeholder with the values of your Auth0 application:

"Auth0": {
    "Domain": "<YOUR_DOMAIN>",
    "Audience": "https://www.yourapp.com"
  }

In each endpoints, add the Policy with the code:

.RequireAuthorization("weatherforecast:read-write")

Before testing the application, go back the Auth0 Dashboard, navigate to the Permissions tab of your API and add the policy:

policy

Come back to the Settings tab and enable the RBAC and the setting to include the permissions in the access token.

Settings tab

Now, in the Machine to Machine Applications tab, select your application, check the permission weatherforecast:read-write and click on the Update button.

Machine to Machine Applications tab

We are ready to test it.

Testing with Postman

One of the quick and easiest way to test the security, is using Postman. Let's do it.

Click on the "Test" tab and copy to the clipboard the value of the access_token.

access_token

When you are ready, open Postman and create a new Get request and insert your API url. Below the URL textbox, click on Authorization and select "Bearer Token". Paste the access token from the clipboard to the textbox.

Postman

Now, if you click on "Send" you can see your data in the Body result like in the screenshoot below.

Postman

Testing with Swagger

There is another way to test the security and the Minimal API. You can use Swagger. You have to add a few lines of code, but after that you have everything inside your project.

In order to do that, you can add these lines of code at line number 7 in Program.cs file.

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "SampleAuth0",
        Version = "v1"
    });
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
    {
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer",
        BearerFormat = "JWT",
        In = ParameterLocation.Header,
        Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 1safsfsdfdfd\"",
    });
    c.AddSecurityRequirement(new OpenApiSecurityRequirement {
        {
            new OpenApiSecurityScheme {
                Reference = new OpenApiReference {
                    Type = ReferenceType.SecurityScheme,
                        Id = "Bearer"
                }
            },
            new string[] {}
        }
    });
});

This code portion adds the Authorization button to Swagger.

Launch a debug session of the application and navigate to "/swagger". As you can see now you have a new button on the top right called "Authorize". Click on it and follow the instructions. Paste the bearer in the textbox with the "Bearer " text before (read the instructions). If you don't know how to retrieve an access token, take a look to the previous paragraph.

swagger

Now you are ready to test the API, directly from Swagger.

swagger results

Conclusion

As you can see, it's very easy to implement the authentication and the authorization with Auth0 in a Minimal API project.

You can find the code on my Gist account: gist

{% embed https://gist.github.com/kasuken/26c6f95c18f11c987ceec1256d9e3ad8 %}

React, comment and follow on