While you develop an API, it is necessary to ensure its security because this API is going to be exposed over the internet. Here, we will show you how HMAC authentication mechanism can be used to protect your API.
Further, a source code will also be given that can be used to secure an ASP.NET Web API using HMAC.
So, first of all let us understand what is HMAC? Later then, we will discuss as to how it can be used to secure an ASP.net web API?
HMAC – Meaning and Definition:
HMAC stands for Hash base Message Authentication Code. When the implementation request is received from a client to the Web API then it will ensure to have data integrity, request origination and no replay request.
These three main points address the most important security vulnerabilities which an API service can expose.
So, how HMAC exactly works?
This works basically on a shared secret between the client and the server. A cryptographic hashing depending on a particular set of parameters like as client ID, request method, Request URL, a nonce value, timestamp and the real content by using the secret key.
With the request authorization header, there are a few values which can be used in the client side comparison like as nonce, timestamp and much more. These are separated by a special character and then sent to plain text.
It is noted that this string must not contain any values which only the client and the server must know. Here, is the sequence of steps followed on the server to know whether the request is valid or not:
Steps to identify the request validity:
- Client ID is validated.
- Nonce value and timestamp are used to identify whether it’s a replay request.
- Secret key is fetched for the given client ID and using all other parameters, the HMAC string is then generated.
- HMAC string generated on the server is compared on the server.
The .NET framework comes with pre developed class for HMAC. It supports both SHA1 and MD5 cryptographic hashing. The SHA1 based HMAC classes offer flexibility to boost hashing bits such as 160, 256 or 512.
Let’s take a look at its source code:
In this sample, we will find the sample console client as well as ASP.NET WEB API applications which implement HMAC authentication.
Develop a console application and then add the below given code in the program.cs file. The http client must be passed on with a custom delegating handler.
Now, the Authentication filler is to be added in the ASP.NET Web API which will do server side HMAC authentication. The code for it is as follows:
This sum up the HMAC authentication process of an ASP.NET Web API. Hope this guide is useful to you to implement HMAC authorization in a Web API.
Liked this blog post? Would like to discuss more about ASP.net application development then stay get in touch with Softqube Technologies, a well known ASP.net application development company in India.