In this article, I will explain how to create the JWT token and how to Authenticate and Authorize it in very simple steps.

1. Add ASP.Net Core API Application

Open visual studio 2022 click on create new project –> Select ASP.Net Core Web API –> Next

Give desired project and solution name –> Next –> select framework .Net 6.0 –> Create

2. Add Nuget Packages 

Add the following packages from 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 following Key, Issuer and Audience

* To generate the random key use 

https://www.random.org/strings

* For issuer and audience local URL follow the below steps

Project properties –> Debug –> General –> Open Debug Launch Profile UI

Select IIS Express and pick the App URL

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

5. Create Models (UserLogin, UserModel and UserConstant)

Add a new folder with Models name and create UserLogin, UserModel and UserConstant classes.

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

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

JWT Token Creation, Authentication and Authorization in ASP.Net Core 6.0 with Postman

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

7. Create User API Controller to authorize user role

Add new empty API controller named “UserController.cs” in controller folder.

Here we will authorize the endpoint on the behalf of role. 

8. Test the API endpoint in Postman with Token

Run the application and copy the URL domain from the browser.

Now open the Postman, give the URL with correct API route and select post request –> Body –> Json –> give the value of Username and Password

JWT Token Creation, Authentication and Authorization in ASP.Net Core 6.0 with Postman

After clicking on send button we will get the JWT token in response.

JWT Token Creation, Authentication and Authorization in ASP.Net Core 6.0 with Postman

Now copy this token and add a new Get request in postman and add the JWT token Authorization Tab –> Select Bearer –> Insert token and click on send button to test the authorization with given token.

If the token is not valid token then we will get 401 Error otherwise will get the bolow result.

JWT Token Creation, Authentication and Authorization in ASP.Net Core 6.0 with Postman

Summary

So we created the token and did the authentication on the behalf of username and password then check the user authorization.

Leave a comment

Your email address will not be published.