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.
To create a WEB API project in Visual Studio, you can follow the given steps step by step.
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.
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.
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.
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.
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 Web API's default output format is supposed to be JSON, but when I access my Web APIs using the browser address ba...
ＬＩＫＥ | ＣＯＭＭＥＮＴ | ＳＨＡＲＥ | ＳＵＢＳＣＲＩＢＥ Implement Get Method In this section we will implement Get action methods in our Web API controller class that will handle...
ＬＩＫＥ | ＣＯＭＭＥＮＴ | ＳＨＡＲＥ | ＳＵＢＳＣＲＩＢＥ Implement Post Method The HTTP POST request is used to create a new record in the data source in the RESTful architecture....