In this blog, we will see the implementation of basic authentication in Web API. Security is very important aspects while working on the distributed application. While exposing an API we must take care about security.
Basic Authentication is a simple authentication mechanism where the client sends requests with an Authorization header with word Basic.
In Basic Authentication, Authorization header contains a word Basic followed by base 64 encoded string.
Why Authentication?
The syntax for Basic Authentication –
Authorization: Basic username: password
Suppose user name is admin and password is admin@1234
Search for “Base64 encode” in any search engine.
You may probably find this link- https://www.base64encode.org/
Open the link and enter admin:admin@1234 and click on encode button.
You will get this output – YWRtaW46YWRtaW5AMTIzNA==
So to send authorization header with request the final syntax will be
Authorization: Basic YWRtaW46YWRtaW5AMTIzNA==
Basic Authentication Implementation
Now we have understood the concept of Basic Authentication. Let’s implement the Basic Authentication with a practical.
If you know the basics of Web API then it is ok, else look at my earlier blog first.
How to create ASP.Ner Web API? or Web API2 CRUD operation with Entity Framework
Once you created your Web API, add a new class to your project and name it ProductSecurity
Below is the sample code for ProductSecurity class.
public class ProductSecurity { public static bool AdminAuth(string adminid, string adminpassword) { try { using (ReviewAndShareEntities entity = new ReviewAndShareEntities()) { return entity.Users.Any(u => u.username.Equals(adminid) && u.password.Equals(adminpassword)); } } catch (Exception) { throw; } } } |
Now add one more class and name it BasicAuthentication.
Also, inherit this class with AuthorizationFilterAttribute.
Implement the OnAuthorization method as shown below.
public class BasicAuthentication : 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 plaintText = Encoding.UTF8.GetString(Convert.FromBase64String(authToken)); string[] adminArray = plaintText.Split(‘:’); string adminid = adminArray[0]; string adminpwd = adminArray[1]; if (!ProductSecurity.AdminAuth(adminid, adminpwd)) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); } } } } |
Once your BasicAuthentication code is ready, go to your controller and write BasicAuthentication class name as an attribute to either controller or particular action as per your need.
[BasicAuthentication] public class ProductMastersController : ApiController { //Action methods here } |
To test this Web API I am using Fiddler.
Enter URL select GET.
Type – Authorization: Basic YWRtaW46YWRtaW4= in Fiddler composer and click on Execute and you should get 200 HTTP status code if the given credentials are correct else 401 Unauthorized.
See below screen shots.
How to Pass a Basic Authorization header using C# code –
Apart from the Fiddler tool, I have explained C# code below to pass the Basic Authorization header to Web API to authenticate and execute successfully.
You have to set Authorization header value by using – client.DefaultRequestHeaders.Authorization
You may call below written function from a C# console application or any C# web applications by passing the correct username and password to get 200 HTTP status code.
private void ShowRecords() { try { IEnumerable<ProductModel> products; var username = “admin”; var password = “admin”; var base64Code = Convert.ToBase64String(Encoding.ASCII.GetBytes($”{username}:{password}“)); webClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(“Basic”, base64Code); HttpResponseMessage webResponse = webClient.GetAsync(“http://localhost:1000/api/ProductMasters”).Result; products = webResponse.Content.ReadAsAsync<IEnumerable<ProductModel>>().Result; foreach (ProductModel productModel in products) { Console.WriteLine(productModel.id + “—-“ + productModel.product + “—-“ + productModel.cost + “—-“ + productModel.stock); } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.InnerException); throw; } } |
Advantages of Basic Authentication :
- It is as per internet standard.
- Simple and Easy to implement.
Disadvantages of Basic Authentication :
- Authorization header requires credentials with each and every request.
- Vulnerable to cross-site request forgery (CSRF)
Watch this implementation on YouTube-
Hope you like this blog. Please comment your feedback below and share this blog.
You may like other blogs –
MVC Tutorial
Web API Tutorial
Is Angular JS different from Angular?
Interview Questions and Answers Series –
MVC Interview Questions and Answers
Web API interview questions and answers