Create JWT Token with .NET 7 Minimal API

Mohammed Abbod Yahya
8 min readNov 26, 2022

--

This project is for demo purposing to understand how JWT token can be created and how using the .NET 7.0 Minimal API end point to give the user a token for authentication against other ASP.NET websites including Blazor WebAssembly.

Will discuss in detail with tutorial:

Creating Web API Project

Create “ASP.NET Core Web API” project

Set the name of the project, and Location:

Then uncheck the “Use Controller” checkbox to switch for Minimal API and OpenAPI:

Building Database using EntityFramework

Create a folder in the project, name it “Data”

Create a new class, name it User

Simply add required fields for identify the user in the system, in general the email and password is the traditional but you can use different type, and this is the good time to build the way you need by modifying the User class.

Also there is possible to add more classes like Roles, Permission but the goal of this blog is just to demo the generating token in simple way.

Now it’s time for creating the DBContext class that will represent the tables for user class, let’s call it DbUsersContext:

And will build this class manually to understand the minimum requirement to build class in “Code First DB Model”

First of all, let’s add the classes that expecting to see table for each of them in the Database.

To create a table for any class requires to use DbSet type, but this type is inside the Microsoft.EntityFramework.Core, so its required to add from NuGet

From Nuget select the 3 packages that will make the connection to SQL

But for “testing purposes” its possible to use the Sqlite database base instead of SQL, so its required to install that related package:

After installing all these packages, let’s return to the DbContext Class, and when try to solve the DbSet, the using option is now in the solving list:

If there is more tables you need to add, just create a class and a new line in the DbUsersContext a line of DbSet:

That’s it.

Let’s try to tell the DbContext where is the data that should create these tables and be connected with this project

There is an overridable function should add to the DbUsersContext to choose what type of database and whre is that database

Then inside this function, if you decided to use the SQL server, then it should be like this:

But for quick test its possible to use Sqlite, like this:

Now its time to create the DB and with all tables that add to the DbUsersContext

In the Package Manager Console type this command:

The result should be like this:

And there is a new folder been create called “Migration” under the project, contains 2 files:

And now we are ready to create the database by issuing this command :

The result will be like this:

And there is a new file “users.db” has been created inside the project:

Create the Minimal API end point:

So when you created the EntityFramework DBContext and connected to the Database, now it’s the time to create the Minimal API functions:

Open the Program.cs

And add the DbUsersContext to the Services collection of DependencyInjection

And before app.run() method, add the functions of the API

Add the Minimal API Method:

Or the best option is adding the async/await style to this function:

One more function and the testing will be easy and clear, by creating the Add function: So after the GetUsers, Add the AddUser

Now its time to test, just run the app:

And let’s add a user:

Click on “Post” to add the user:

And then on the try:

There is a structure of the class that created earlier in the EntityFramework section needs to fill and post:

And hit “Execute”

The result will be in the response, shows a successful submit (Post)

Then we can test the first method “GetUsers” after we have a new record in the database

Click on the GET

And you’ll see the result:

This is in details how to interact with EntityFramework and Minimal API in .NET 7

The next step is how to add a method in Minimal API that will create a token for user and return it simply through a POST call.

Add a new function after the app.run() , its better to add in a separated class but I added to the Program.cs for demo purposes:

use a private key like ( but for best working it should be read from appsetting.json)

String K = "12345678901234567890123456789012345678901234567890123456789012345678901234567890";

Then Convert to bytes

var key = Encoding.UTF8.GetBytes(K);

And convert to symmetric Security key

var skey = new SymmetricSecurityKey(key);

Sign the key

var SignedCredential = new SigningCredentials(skey,SecurityAlgorithms.HmacSha256Signature);

Then Add some Claims

var uClaims = new ClaimsIdentity(new[] 
{     new Claim(JwtRegisteredClaimNames.Sub,user.Name),     new Claim(JwtRegisteredClaimNames.Email,user.Email) });

//Add of course the expire date (how long this token will be valid):

var expires = DateTime.UtcNow.AddDays(1);

Now to build the token, we need to use the TokenDescriptor and JwtSecurityTokenHandler classes:

var tokenDescriptor = new SecurityTokenDescriptor {     Subject = uClaims,     Expires = expires,     Issuer = "MasterBlazor",     SigningCredentials = SignedCredential, }; //initiate the token handler var tokenHandler = new JwtSecurityTokenHandler(); var tokenJwt = tokenHandler.CreateToken(tokenDescriptor); var token = tokenHandler.WriteToken(tokenJwt);

The token now is available and ready to return to the user:

And will add the Minimal API to Build that token and returns it when the email and password are correct in the time of calling /Login function

And now let’s test it:

Just run the app and will see a new API method has been listed:

Just need the email and password to fill then post it to the /Login API

In the response body it will be a beautiful string that represent to token

GitHub source code is here: Src

Now its time to create Blazor application to get token from Minimal API by calling /Login end point

Let’s create a Blazor Full Stack Project to consume the Minimal API and get the token.

Create Blazor WebAssembly

Give a name to the project:

and be sure to check “ASP.NET Host Core Hosted”

You’ll see new 3 projects:

Rename the existing control that come with template and rename it to AccountController.cs:

Add User class in this controller:

Then edit the Get method to be able to create a User class and set sample values (Simulate the calling from Login razor page). and will use the Url of the minimal API address with the route /Login to post the body of user to this method: to be like this:

in the Client Project, just edit the Index.razor:

Then add a simple button to call Login() function.

In the Login there is a call to the AccountController /Get to get the token:

Then show the token in the page

Is it nice!

--

--