DEV Community

Cover image for Create JSON Web Tokens for development and testing
George Papadopoulos
George Papadopoulos

Posted on • Updated on

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 simplify this process. It allows you to generate custom JSON Web Tokens that can be used during development and (system) testing of your JWT-Protected API endpoints.

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);

builder.Services.AddAuthentication()
                .AddJwtBearer(o =>
                {
                    o.Authority = "https://login.microsoftonline.com/common";
                    o.Audience = "myApi";
                });

builder.Services.AddAuthorization();

var app = builder.Build();

app.UseAuthorization();

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

app.Run();
Enter fullscreen mode Exit fullscreen mode

To test our endpoint we would need a valid token from our authority (in this case login.microsoftonline.com). 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 user@mail.com
    

    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!

Join Discord Group

Top comments (0)