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 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 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 parameter “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;
            }
        }
    }

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.
Host: localhost:63938 Authorization : Basic dXNlckBhYmM6dXNlckAxMjM=
  • Select protocol type.
  • Click on execute button.

You can see response when you click on 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

Download Source Code

Share Knowledge
This entry was posted in ASP.NET, C#, WEB API and tagged , , , , , , . Bookmark the permalink.

2 Responses to How to secure ASP.NET Web API using basic authentication

  1. Pingback: Implementing CRUD Operations using WEB API - code-adda

  2. Pingback: Creating your first WEB API Project - code-adda

Leave a Reply

Your email address will not be published. Required fields are marked *