Saturday, July 14, 2018

SECURING WEB API USING JWT IN C# Tutorial


SECURING WEB API USING JWT IN C# .NET FRAMEWORK

Introduction:


In this tutorial our goal is to secure data transmission between two endpoints JWT is a way to achieve.

Json Web Token Consist of Three parts separated by dot(.).
Header
Payload
Signature

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImFkbWluIiwibmJmIjoxNTMxNDgzMjIyLCJleHAiOjE1MzIwODgwMjIsImlhdCI6MTUzMTQ4MzIyMiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDE5MSIsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTAxOTEifQ.l1oH8lU39JF-4iZO1dzkbqvi5W1Zm7KLvqbCUT-3Y6g


JWT Authentication Flow

 
Let’s do the coding:
Step 1: Create a new project and name your project and solution and select ASP.NET web application


Step 2: Select ASP.NET web API and change Authentication to None.




Step 3: Click on OK and then our solution is ready




Step 4: Install the Nuget package that will help to handle task related to jwt web api  System.IdentityModel.Tokens.Jwt




Step 5: Select The latest version and install



Step 6: Now, we need to add a class in our solution that will take care about incoming HTTP Request and Validate the token. In order to do this, we are going to create this class at root level that extends DelegatingHandler and we need to override SendAsync method.
I am going to name this class as ValidateTokenHandler.cs




Please add the code like this:





So, we created our own class that derived from the DelegatingHandler class and we override SendAysnc method to intercept HTTP request and validate the JWT.

Generating the JWT Token Web Api C#:


Step 1: Create UserRequest.cs and UserResponse.cs class in Models folder as follows:




Step 2: In order to create a JWT after verifying the username and password with our database, we are going to create a controller class as GenerateJWTTokenController.cs
CreateToken method will generate a token and Authenticate method will receive an HTTP request and validate the username and password and if they are valid we send back the Token.



Step 3: Register the Message Handler class in the WebApiConfig.cs, add the following code:



Step 4: Now it’s time to secure our end points; Let’s decorate our Values Controller with Authorize attribute:



JWT Web Api Testing

Step1: In order to test we can use any REST API Testing tool, however for demo purpose we are going to use POSTMAN.






  

Step 2: In order to make a GET Request we are now required to have a TOKEN. To generate a token, we need to do a post request providing a json data and set the content-application value as json and then request on the following url:
{
“Username”: “admin”,
“Password”: “admin”
}




Step 3: Now after generating token, we will try to fetch the record from ValuesController using JWT token from the following url:



As you can see we have added the JWT token in the header do notice syntax Bearer token.  we accessed our secured resource using JWT. It is valid for about of time we set when we generated it. if we temper with it unauthorized code is returned.

2 comments:

  1. your source code does not contain delegating and api controller

    ReplyDelete