.NET Core —Adding JWT Claims To Web API — Part 1 The Setup

Vaygeth (Abdulmohsen)
2 min readNov 17, 2020

How to add JSON Web Token to protect your web APIs and authenticate users

What We Going To Build

A web API that allows users to

  1. Sign Up (obtain JWT token)
  2. Sign In to obtain JWT token
  3. Get User Profile API (Protected by JWT authorization)

The Required Packages & CLIs

  1. ASP Core JWT to add authorization to our API
  2. Any Database Package, I’m SqlServer to connect to SQL Server Database and store data
  3. Entity framework Identity to facilitate Database ORM and handle migrations
  4. Entity Framework Core Design a required package for database
  5. Entity Framework CLI to facilitate migrations and database changes

Here shortcut if you are using dotnet CLI

dotnet new webapi -n JWTProtectedAPIdotnet add package Microsoft.AspNetCore.Authentication.JwtBearerdotnet add package Microsoft.EntityFrameworkCore.SqlServer dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCoredotnet add package Microsoft.EntityFrameworkCore.Design dotnet tool install --global dotnet-ef 

The Setup

appsettings.json

Open appsettings.json and add JWT configurations. these configurations used to modify the JWT settings like when it’s expires, the Secret Key used to authorize the claim….etc. ExpiryTimeInMinutes is set for JWT to expire in 2 hours, you can set it to whatever you want.

Also add your Connection String, I’m using my own config for SqlServer

appsettings.json

Startup.cs

Inside ConfigureServices method add the following to configure our AppDbContext and Connection String as well the coming of JWT setup. Note the Sign In/Password security policy, make sure you update it to suits your security policies

Also inside Startup.cs after ConfigureServices() define setUpBearerJwtAuth

setUpBearerJwtAuth()

Also inside Startup.cs in Configure(IApplicationBuilder app, IWebHostEnvironment env)

AppDbContext.cs

Create AppDbContext class conventionally under Models folder in the root of your project folder (JWTProtectedAPI/Models/AppDbContext.cs) and add the following code.

We going to use ASP core identity for creating Users so that’s why our DB Context extending IdentityDbContext<IdentityUser>

Migrations and Database Update

To create migrations and apply them into the database run the following commands.

dotnet ef migrations add Init -c AppDbContextdotnet ef database update -c AppDbContext

What we did is tell our framework to create Asp Dotnet JWT identity configurations and tables migrations and apply them into our database.

You will see several new tables if above were successful

JWTProtectedAPI database

Conclusion for Part 1

This concludes Part 1 for .NET JWT Setup, Part 2 The APIs implementation will be published this Friday.

--

--

Vaygeth (Abdulmohsen)

I’m a software developer & UI/UX designer who want to share my experience with fellow developers. abdulmohsen.co https://www.patreon.com/vaygeth