# Create JSON Web Tokens for development and testing

It can be challenging to test an API that requires authentication through a [JSON Web Token](https://jwt.io/introduction) *(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`](https://github.com/Phoesion/Phoesion.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 :

```cs
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();
```

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
    
    ```bash
    dotnet tool install --global phoesion.devjwt.cli
    ```
    
2. Generate token using
    
    ```sh
    dotnet devjwt create myApi --email user@mail.com
    ```
    
    ![Console output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ni92rem76h4rookdsj7y.png align="left")
    
3. Configure your service `appsettings.Development.json`
    
    ```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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r47sa37n3ciw1xkbqqa2.png align="left")

You can find [more samples here](https://github.com/Phoesion/Phoesion.DevJwt/tree/main/Samples)

If you want to learn more, check out [the project documentation](https://github.com/Phoesion/Phoesion.DevJwt)

Happy Coding!
