JWT Authentication in ASP.NET Core Web API

Introduction

In this article, I will explain how to create the JWT token and how to Authenticate and Authorize it step by step in a very simple way

We will follow the below steps for JWT token creation, authentication, and authorization.

  • ASP.Net Core WebAPI Application
  • Add required packages.
  • Add Key, Issuer, and Audience in app settings.cs
  • Register JWT Token for Authentication in the Program.cs file.
  • Create Models (UserModel )
  • Create Login API Controller (Authenticate user and generate token)
  • Create Product WebAPI Project with Product Controller.
  • Test the API endpoint in Postman with Token.

1. Add ASP.Net Core API Application

Open Visual Studio 2022, click on Create New Project, Select ASP.Net Core Web API, and Next.

 Web API

Give the desired project and solution name, Next, Select framework .Net 8.0, Create.

2. Add Nuget Packages

Add the following packages from the NuGet package manager.

  • Microsoft.AspNetCore.Authentication.JwtBearer
  • Microsoft.IdentityModel.Tokens
  • System.IdentityModel.Tokens.Jwt

3. Add setting in appsetting.json

Open appsetting.json and add the following Key, Issuer, and Audience.

Appsetting.json

4. Register the JWT token for Authentication in the Program.cs file

JWT token

5. Create Models (UserModel)

Add a new folder with the model name and create UserModel.

UserModel

6. Create LoginAPI Controller (Authenticate user and generate token)

Add a new Empty API controller name “LoginController” in the controller folder.

Generate token

Here, it creates one Post Action method for Login and two methods for Authenticating the user credentials and Generates the token (if a user is authenticated).

Post Action

Response

Private

Userinfo

7. Create a Web API project with a Product controller to authorize getting Product Details

Add NuGet Packages

Add the following packages from the NuGet package manager.

  • Microsoft.AspNetCore.Authentication.JwtBearer
  • Microsoft.IdentityModel.Tokens
  • System.IdentityModel.Tokens.Jwt

Create a get method to get the product list.

Product list

add jwt authentication in the program. cs and key in appsettings.json.

 Program.cs

Key

8. Test the API endpoint in Postman with Token

Run the application and give the value of the Username and Password.

Password

Copy the URL, paste it into Postman, copy the token, and paste it into the bearer token.

 Bearer token

Summary

So I explained what is authentication and authorization and jwt token How to create jwt authentication and how to generate the token.

You can view or download the source code from the GitHub link here.

https://github.com/manideep-bestshop/AspNetCoreTutorials