.NET Core  

Minimal API with Authorization JWT Token in .NET 9

Here we will discuss how to handle JWT tokens and authorization in Minimal API .NET Core 9.0. Create a .NET 9 Web API in Visual Studio 2022 with the updated version. Visual Studio 17.12 or higher version is required for .NET 9.0 applications. Then, install the below-mentioned package from the Manage Nuget Package option.

Microsoft.AspNetCore.Authentication.JwtBearer
Swashbuckle.AspNetCore

Here, to check the output, we will use Swagger View. Generally, Web API output can be checked in Swagger, Scalar, Insomnia, Postman, etc. Will check in Swagger for that we require 'Swashbuckle' package. JWT token is a JSON Web Token; it's used for authentication and authorization in web applications and APIs.

Program.cs

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSwaggerGen(options =>
{
    options.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
    {
        Name = "Authorization",
        Type = Microsoft.OpenApi.Models.SecuritySchemeType.Http,
        Scheme = "Bearer",
        BearerFormat = "JWT",
        In = Microsoft.OpenApi.Models.ParameterLocation.Header,
        Description = "your_key"
    });

    options.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
    {
        {
            new Microsoft.OpenApi.Models.OpenApiSecurityScheme
            {
                Reference = new Microsoft.OpenApi.Models.OpenApiReference
                {
                    Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[] {}
        }
    });
});

Will have GET and POST map methods to fetch the data from the WEB API. With authorization, a JWT token will generate the token from the token request and get the response.

app.MapGet("/token", () =>
{
    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.UTF8.GetBytes("Your_Key");

    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "user") }),
        Expires = DateTime.UtcNow.AddHours(1),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
    };

    var token = tokenHandler.CreateToken(tokenDescriptor);
    return Results.Ok(new { token = tokenHandler.WriteToken(token) });
});

Output

Web API

var products = new List<Book>
{
    new Book(1, "Laptop", 999.99m),
    new Book(2, "Phone", 499.99m)
};

// GET all products (requires JWT)
app.MapGet("/products", [Authorize] () =>
{
    return Results.Ok(products);
});

Output

Server Response