How to secure ASP.NET Web API using basic authentication
ASP.NET Web API allows us different ways to implement security while exposing resources. In the previous article, we have learned about how to secure ASP.NET WEB API using token-based authentication. In this article, we are going to learn how to secure ASP.NET WEB API using basic authentication. Basic Authentication is easy to implement, expose and consume and is widely supported by any Web client, but it’s not as secure as token-based authentication and it requires that SSL(Secure Sockets Layer) is used to keep the encoded credentials in order to the safe application from simple attacks.
Implementation of ASP.NET Web API using basic authentication
Step 1 :
create a class for your filter and inherit it with AuthorizationFilter. Here, we are going to create Inherit “BasicAuthenticationAttribute” class from “AuthorizationFilterAttribute” class which reside in “System.Web.Http.Filters” namespace. Inside “BasicAuthenticationAttribute” class we will override OnAuthorization function of “AuthorizationFilterAttribute”
Here, we are using Base64 format to encrypt the username:password. Once you get the value from the header, it converts to original value which only contains the username and the password. Format used to store username and password is “username:password”
Step 2 :
We are going to add a class LoginPolicy and have a function Validate containing two parameters “username” and “password” to validate authentication while consuming resources.
Step 3 :
We have created our basic authorization filter and now its time to implement it in your controller. You just have to register it. Here we are going to create controller name “TestController” and implement “BasicAuthentication” on action level.
Great.. Now you have successfully created your WEB API using basic authentication. You can use WEB API testing tools like fiddler or postman. Don’t worry we will guide you how to check. In last article – How to secure ASP.NET Web API using Token Based Authentication we learnt how to test Web API using postman, Here we are going to learn how to consume WEB API using fiddler. Follow given steps.
- Select action type – GET
- Enter WEB API link
- Enter Header value.
- Select protocol type.
- Click on execute button.
You can see the response when you click on the execute button. Have a look at below pic.
You can download complete source code from here