Wednesday, 22 January 2020

How to secure ASP.NET Web API using basic authentication

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
public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response = actionContext.Request
.CreateResponse(HttpStatusCode.Unauthorized);
}
else
{
string authToken = actionContext.Request.Headers
.Authorization.Parameter;
string decodedAuthToken = Encoding.UTF8.GetString(
Convert.FromBase64String(authToken));
string[] unamepwdVal = decodedAuthToken.Split(':');
string username = unamepwdVal[0];
string password = unamepwdVal[1];
if (LoginPolicy.Validate(username, password))
{
Thread.CurrentPrincipal = new GenericPrincipal(
new GenericIdentity(username), null);
}
else
{
actionContext.Response = actionContext.Request
.CreateResponse(HttpStatusCode.Unauthorized);
}
}
}
}
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.
public class LoginPolicy
{
public static bool Validate(string username, string password)
{
// you can read username and password value from database and can easly use here to validate.
if (username.Equals("user@abc", StringComparison.OrdinalIgnoreCase) && password == "user@123")
{
return true;
}
else
{
return false;
}
}
}
view rawloginpolicy.cs hosted with ❤ by GitHub
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.
[BasicAuthentication]
public HttpResponseMessage Get()
{
string username = Thread.CurrentPrincipal.Identity.Name;
DataSet dsRecord = new DataSet();
if (username == "user@abc")
{
return Request.CreateResponse(HttpStatusCode.OK,
"Hello Learner.. Thanks for learning at code-adda.com");
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
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.
[su_note]Host: localhost:63938 Authorization : Basic dXNlckBhYmM6dXNlckAxMjM=[/su_note]
  • 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.
How to secure ASP.NET Web API using basic authentication
You can download complete source code from here
[su_button url=”https://github.com/code-adda” target=”blank” style=”3d” background=”#7a1d18″ size=”5″ radius=”round”]Download Source Code [/su_button]

No comments:

Post a Comment

Baisic Useful Git Commands

  Pushing a fresh repository Create a fresh repository(Any cloud repository). Open terminal (for mac ) and command (windows) and type the be...