Create JSON Web Tokens for development and testing

Create JSON Web Tokens for development and testing

It can be challenging to test an API that requires authentication through a JSON Web Token (JWT). To obtain a valid access token that can be used with your API, you typically need to setup/use an entire identity and access management system.

Using the dotnet-devjwt tool you can make this process much easier. It allows you to generate custom JSON Web Tokens that can be used during development and (system) testing.

Let's go through the steps of using this new tool.

Getting started

Let's create a small ASP.NET Core application, configured to use JTW Bearer authentication :

var builder = WebApplication.CreateBuilder(args);

                .AddJwtBearer(o =>
                    o.Authority = "";
                    o.Audience = "myApi";


var app = builder.Build();


app.MapGet("/protected", (ClaimsPrincipal user) => $"Hello {user.FindFirst(ClaimTypes.Email)?.Value}")


To test our endpoint we would need a valid token from our authority (in this case Getting this token is not always easy or even possible. This becomes even more difficult when we want to run isolated system tests in different environments.

Let's use the DevJwt lib/tool to create a token for local development.

Using Phoesion.DevJwt

  1. Install the dotnet tool

     dotnet tool install --global phoesion.devjwt.cli
  2. Generate token using

     dotnet devjwt create myApi --email

    Console output

  3. Configure your service appsettings.Development.json

     "Authentication": {
        "Schemes": {
           "Bearer": {
              "ValidIssuer": "phoesion.devjwt",
              "SigningKeys": [
                  "Issuer": "phoesion.devjwt",
                  "Value": "c29tZV9kZWZhdWx0X2tleV9mb3JfZGV2cw=="

Now we can call our API by passing the generated JWT token :
curl -i -H "Authorization: Bearer {token}" http://localhost:5256/protected

Postman window

You can find more samples here

If you want to learn more, check out the project documentation

Happy Coding!