JWT Authentication with ASP.NET WEB API

JWT Authentication with ASP.NET WEB API

In this article, we will learn how to authenticate ASP.NET WEB API using JSON Web Token(JWT). If you are new to JWT then I would like to request you to please go through with our article which briefly explains A Basic Introduction to JSON Web Token(JWT).

You can also read another article ( How to secure ASP.NET WEB API using Token Based Authentication) based on Token based authentication on Code-Adda to have some idea about how token based authentication works.

Create a WEB API Project

To create a WEB API project in Visual Studio, you can follow the given steps step by step.

  1. Open Visual Studio
  2. Go to the file menu
  3. Create > Project
  4. Select Web
  5. Select “asp.net web application”
  6. Enter application name
  7. Select your project location
  8. Click on add button

It will bring up a new dialog window for select template > here I will select empty template > and then checked MVC & Web API checkbox from Add folder and core references for > and then click on Ok button.

Add NuGet package :


To add NuGet package you can either use Manage NuGet Packages windows after right click on References available in Solution Explorer or you can simply use below command in Package Manager Console.

install-package System.IdentityModel.Tokens.Jwt

Create a Middleware for JWT Authentication

You need a middleware which can generate JWT and validate it based on some provided required values. To create a middleware you have to create some classes and some methods. Let’s see one by one.

Create a Folder name Auth in your application and then create given classes with some piece of code having different methods serving different purposes.

JwtAuthManager class having two methods GenerateJWTToken and GetPrincipal.

GenerateJWTToken method needs two values for username and expire_in_Minutes. the username will be used as a value to Initializes a new instance of the System.Security.Claims.Claim class with the specified claim type, and value. expire_in_Minutes act as Get or Set value for the ‘expiration’ claim.

You can use HMACSHA256 to create your own SecretKey. It belongs to System.Security.Cryptography namespace. Use below code to generate your own secret code

var hmac = new HMACSHA256(); var key = Convert.ToBase64String(hmac.Key);

As of now, you might be thinking I’ve not written any single word for the second method which is GetPrinciple of JwtAuthManager class. Don’t worry, we’ll go through with this later because to generate token only GenerateJWTToken method will work.

When user request with the valid required credential to get JSON Web Token, GenerateJWTToken comes in action and create a token for that particular user. Have a look at below image where you can see what different things combined in order to create a token.

Fine! I hope till now you have created Token successfully with the help of above code, now next thing is to validate it when that particular user again requests with the generated token. We use below code to validate the token. Have a look.

JwtAuthentication class inheriting Attribute class and IAuthenticationFilter. IAuthenticationFilter is an interface having two declared function AuthenticateAsync and ChallengeAsync.

Note :

Attribute class represent a base class with a custom attribute. IAuthenticationFilter Interface Define a filter that performs authentication.

AuthenticateAsync invokes first when sending a request with the token. Two parameter context and cancellationToken belongs to AuthenticateAsync is used to get a request from the user. context will have the authentication context and cancellationToken will have the token to monitor for cancellation requests.

ValidateToken method having two parameter token and username will validate requested token is exact same or not issued to that particular user based on username. Here comes GetPrincipal method in action, GetPrinciple read token with same and validate it with TokenValidationParameters.

While Validating token, there are chances that authentication might be failed if a request having token is not valid. You can deal with same as given below code

AuthFailureResult class inherit IHttpActionResult Interface. You have to implement ExecuteAsync that belong to IHttpActionResult. ExecuteAsync is used to perform a task contains the System.Net.Http.HttpResponseMessage when completed.

you can use below code to add authorization in the header.

Create WEB API Controller

You need to create two different actions one for generating a token, send back to the user and second one for validating that token and expose requested data by the user. You can have both actions in the same controller or can have two separate controllers. It all depends upon the requirement of your project. For Demo purpose, I have created two separate controllers, one for creating a token and another one for validate. Have a look at below code.

RequestTokenController – To create a JWT and issue to those user whoever request with valid credentials.

JwtAuthentication – It is used to at action level to protect it. It is only available when user request with validly issued JWT Token to that particular user.

Great. Now you have created your WEB API with JWT based authentication. You can use WEB API testing tools like Fiddler or Postman. Don’t worry we will guide you how to check. Here we are going to learn how to consume WEB API using postman. Follow given steps

Step 1: You have to enter a few details before you post details on the server.

Step 2: Once you get token, again you have to follow some step to authenticate generated token.

  • Select Type – GET
  • Enter WEB API URL with “/Values” in Params like “http://localhost:port/api/Values”
  • Enter Authorization for Key under Header and for Value, you have to enter “Bearer generated-token…” Or, Select authorization type – Bearer Token and Enter Token in Token field.
  • Click on the Send button

Once you click on the send button after entering all required field. you can see the output. If there is 200 Ok. Status which means you have successfully authenticated JSON Web Token and get back the result. In case if you have not provided valid token you will get an unauthorized error.

You can download complete source code from here – Download Source Code

asp.net api java

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Create Asp Net Web API for CRUD operation | CRUD Using Asp Net Api

LIKE | COMMENT | SHARE | SUBSCRIBE Web API CRUD Operations Using Asp Net MVC and Entity Framework Contents * Web API Project For CRUD Operations - Insert Upd...

Hire ASP.Net Developers

Looking to outsource your asp dot net development requirement? ASP.Net is a special feature of the DOT Net framework created by Microsoft. At [HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io"), we have a team of experienced...

Consume Web API Post method in ASP NET MVC | Calling Web API | Rest API Bangla Tutorial

LIKE | COMMENT | SHARE | SUBSCRIBE In this tutorial, I will discussed about how to consume Web API Get method and display records in the ASP.NET View. Here, ...

Consume Web API Get method in ASP NET MVC | Calling Web API | Rest API Bangla Tutorial

LIKE | COMMENT | SHARE | SUBSCRIBE In this tutorial, I will discussed about How to Consume Web API Get method in ASP NET MVC. Blog : http://aspdotnetexplorer...

Consume Web API Put method in ASP NET MVC | Calling Web API | Rest API Bangla Tutorial

LIKE | COMMENT | SHARE | SUBSCRIBE In this tutorial, we learned how to consume Web API Get and Post methods in the ASP.NET View. Here, we will see how to con...