Securing .NET 6 Minimal API with Auth0
Tags: webdev, api, authentication, security
Published: 2022-05-24 14:16:08

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](https://docs.microsoft.com/en-us/aspnet/core/tutorials/min-web-api?view=aspnetcore-6.0&tabs=visual-studio) or the Microsoft Learn path about Minimal API and ASP.NET Core at this [link](https://docs.microsoft.com/en-us/learn/paths/aspnet-core-minimal-api/)

## 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
](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ro5gtp7degtijx1x01a.png)

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

![Project Template](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p1fya7887osl38cf2f3w.png)
 
Below the default endpoint, add the code below to add another endpoint (in this example a POST with a WeatherForecast model).
```csharp
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/835xl86597axueczfyl5.png)

## 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](https://a0.to/signup-for-auth0).

From the [Auth0 Dashboard](https://manage.auth0.com/), navigate to Applications -> APIs and click on Create API button on the right pane.

![Auth0 Dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t3v3uxw055b8hs8vfznl.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yvz57sgv90ov1xzo7wte.png)

## 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.

```csharp
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:
```json
  "Auth0": {
    "Domain": "<YOUR_DOMAIN>",
    "Audience": "https://www.yourapp.com"
  }
```

In each endpoints, add the Policy with the code:

```csharp
.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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q92n0tww4274vjvm0xre.png)

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

![Settings tab](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ddrat2kgzt2uim89xm9.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lodn10al8k5acy4a0hoc.png)

We are ready to test it.

## Testing with Postman
One of the quick and easiest way to test the security, is using [Postman](https://getpostman.com).
Let's do it.

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

![access_token](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zq2yvwi0ar7wfc7uyaxo.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gg55oqq3sbuu9dm3tg23.png)

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

![Postman](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ryz92hq1gd0c2izakqg6.png)

## 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.

```csharp
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k6394n6qld7px3ivg810.png)

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

![swagger results](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5tqx98cuu86xea6g44d2.png)
 
## 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](https://gist.github.com/kasuken/26c6f95c18f11c987ceec1256d9e3ad8)

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