Enable Basic Authentication in WevApi
There are various ways to authenticate a request in WebApi
but in this post I am going to talk about how to implement basic authentication
in WebApi. The primary purpose of these authentication mechanism is to validate
the incoming request.
In basic authentication user credentials are hooked-up
inside request and you can find it under the authorization header. If you are
using third party token base services like oAuth2 to validate the request then
these services are also uses the same basic authentication mechanism to
validate the user before sharing the token with them.
Lets get started
Step 1- Create an attribute class and inherits the members of
AuthorizeAttribute attribute class. The reason of inheritance is to override
the “IsAuthorized” method.
public class AuthorizeUser: AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
}
}
Step 2 – Override the IsAuthorized method
protected override bool IsAuthorized(HttpActionContext actionContext)
{
try
{
//Basic Aurthintiacation
string authString =
actionContext.Request.Headers.GetValues("Authorization").FirstOrDefault().Substring("Basic ".Length).Trim();
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string usernamePassword = encoding.GetString(Convert.FromBase64String(authString));
int seperatorIndex = usernamePassword.IndexOf(':');
string username =
usernamePassword.Substring(0, seperatorIndex);
string password =
usernamePassword.Substring(seperatorIndex + 1);
//Add the logic of
user validation
}
catch(Exception ex)
{
return false;
}
return true;
}
Step 3 – Now you need to use the attribute on the action
methods or controller level like shown as below
[AuthorizeUser]
public class DatabaseController : BaseController
{
[HttpGet]
[Route("user/{userCode}")]
public IHttpActionResult GetUserName([FromUri]string userCode)
{
}
}
Step 4 – Now when you will try to call “GetUserName” method
of “DatabaseController” api, it will first validate your request and then
return the result. Also, your request should contain the authorization header
otherwise it will not succeed. For demo purpose I use the Chrome “Rest Client”
to test the api.
As you can see I have added the authorization header along
with the request and when you click on the edit on the right side of header, it
will pop-up the window to supply the username and password (see the second
screen shot).


Comments