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 :

System.IdentityModel.Tokens.Jwt

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.

  • Select type GET
  • Enter URL of WEB API with “/RequestToken” like “http://localhost:port/RequestToken”
  • Enter credential in Params { username and password }.
  • Click on the Send button.

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

About Ravi Ranjan Kumar 31 Articles
An Indian who Living, Loving & Learning Technology with different tastes and willing to share knowledge and thoughts.

6 Comments

    • Without creating function name ChallengeWith you can not declare it. You have to create it. Navigate source code hosted on github and have a look at HttpAuthChallengeContextExtension class inside Auth directory.

  1. Hi,

    Again, nice article but I cannot find the ChallengeWith in the Challenge function. Any Ideas? I’ve googled it but can’t find anything regarding ChallengeWith

    Thanks

    • ChallengeWith is not inbuilt function of any package. ChallengeWith function is defined in HttpAuthChallengeContextExtension class. Please download source code given in article and have a look.

    • @Ravi Thanks I got it to work. Another couple of questions if you don’t mind.

      1. What is the user of the Realm? I assume that when I login a user against my database, I return its roles and set them in claims which will be included in the token but I’m not sure what the Realm is for?

      2. Is there a way to check for the roles returned in the Claims using an Attribute, more specifically the [JwtAuthentication(“Admin”, “Staff”)] for example or should I check the claims in each function but it could feel a bit overkill, if I want to put it at the class level.

      Thanks again.

      Thierry

Leave a Reply