Generate JWT Tokens in 3 Easy Steps in .Net
Tags: csharp, dotnet, webdev, security
Published: 2023-02-16 21:43:20

Hi there !
Today's article is brief and succinct , no theory as well , maybe just a sprinkle of theory , I promise , let's get into it !


## The Problem We're Addressing Here
The point of having security tokens is to authenticate and authorize users while keeping their information safe while being sent back and forth between the server and the client , the token when issued from the authentication server , is sent to the client and it's then attached to every subsequent request so the server checks if it's valid based on a secret key used for **encoding** & **decoding** the token , but we're not here for that , this process takes up so much time to set up , and a lot of configuration just to start issuing tokens , in production , this's made possible by signing in with some user credentials , in response we receive a **JWT Token** , whereas in development , we may not want to write all the code just to have an authentication server , however , there's a tool that could help us issue tokens without any prior setup , so , now we know what we're concentrating on , let's begin.


## Creating A New Project
We'll keep things simple , and for the sake of simplicity , we'll create a **Minimal API** project , so fire up your terminal , and type this command:

```

dotnet new web -n GenerateJwtTokens

```

The name is optional by the way.

## Setting Up The Scene
For **authentication** and **authorization** to work , we need some basic configuration , start by doing the following:

**1:** Run this command to add a **NuGet Package**
`dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer` 

_This package is used to add Jwt Bearer as our authentication scheme_

**2:** Add both authorization and authentication services by adding these two lines of code to **Program.cs**:

![Registering Both Auth Services](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lpnd8uf0ukonco5hgug4.png)

**3:** Add the authorization middleware to the **request pipeline** by adding this line:


![Registering The Authorization Middleware](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x25c7c4874g8cjmlrqv0.png)


OK

## Let's Create **TOKENS**
In your terminal , type out this command:

```

dotnet user-jwts create -n DonaldDuck

```
Press enter , and a new token for the name **DonaldDuck** will be created , if you copy the token and head to either https://jwt.ms/ or https://jwt.io/ , and paste it there , you should see something like this:


![Donald Duck JWT Token](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8pnz871wroq7xb1hx7lo.png)

As you can see , there's some information inside the token and additionally , it's a valid token , see how easy and simple it is !

I'm not going to cover every possible option for this tool , however , you can check all the feasible options by using this command right here:

```

dotnet user-jwts -h

```

Before we do anything else , go to **appsettings.development.json** , you'll see that the file has been modified automatically to include some settings , this was done by the tool , those settings are used to issue the tokens so in case you were wondering where the valid audiences and valid issuer claims that you saw when you decoded the token came from , now you know !

The valid audience is every **URL** mentioned in **launchSettings.json** inside the **Properties** folder.

With the setup now completed , let's test it !


## Testing The Generated **JWT Token**
I created a basic list of strings named **values** just for demonstration purposes , and added a new **GET Endpoint** that when called , retrieves all the values inside the **values** list , this endpoint requires authorization though , so for now , add the following highlighted lines:

![Dummy Data and Endpoint](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ivdlg5raqj83cuoodvjw.png)

Ok , we're all set , let's run the API , type this command:

```

dotnet run

```

Copy the URL and paste it in a tool like **Postman** or **Insomnia** , and then hit send , you should get a **401 Unauthorized** as a response because we haven't supplied a token in the request's header , now go back to that token you generated for **DonaldDuck** , or create a new one , it doesn't matter , copy it and go to the authorization tab , and change the type to **Bearer Token** , then paste your token there , like this:


![Adding the bearer token to the request header](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rl3x9t8r6km53w15hyc3.png)

 Now press send and voila , you get a **200 OK** as a response with the values from our basic list , similar to the following: 


![The result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9g1zwxwyqlrsu1nbjzam.png)


## Summary
In this article , I merely covered a single command , but I gave you the foundation on how to generate JWTs with as little as 3 steps , moreover , there're other commands that for example add a claim for the user role , you can clear all tokens issued for a project and possibly list all the issued tokens as well plus a lot more , so yes , the tool is a great way to save up time on configuring and setting up an entire authentication process.

I hope you found this useful !