Introduction
Nowadays, WebAPI is a trending technology. As we are exposing our WebAPI to the outside world, we should maintain security in WebAPI. It means a valid user can only access WebAPI, or else it will throw an unauthorization error. In this blog, we will discuss how we can implement basic authentication in WebAPI.
Using Code
In order to implement basic authentication, the steps are listed below.
Step 1
Method to validate a user
Add a class called ApiSecurity and add a method called ValidateUser(string username, string password), which takes two parameters - username and password. It checks the username and password with the database value, if it succeeds it returns boolean value as true, else false.
- public static bool VaidateUser(string username, string password)
- {
-
- if(true)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
Step 2
In the second step, add a class, which will used as Authorization filter. The class BasicAuthenticationAttribute inherits from BasicAuthenticationAttribute abstarct class.
It contains an override method OnAuthorization(), which performs all the validations. Inside method checks whether the header is present or not: if no, it sends an unauthorized, else it goes ahead to gets the values from the header. Here, we are using 64 bit encoding format to encrypt the username/password. Once you get the value from the header, it converts to original string, which contains the username and the password. Subsequently, it calls the VaidateUser() of ApiSecurity class(discussed in Step 1) with passing the required parameters to get the Boolean result. If it returns false, it sends an unauthorized error to the user.
- public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
- {
- public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
- {
- if (actionContext.Request.Headers.Authorization == null)
- {
- actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
- }
- else
- {
-
- string authenticationString = actionContext.Request.Headers.Authorization.Parameter;
- string originalString = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationString));
-
-
- string usrename = originalString.Split(':')[0];
- string password = originalString.Split(':')[1];
-
-
- if (!ApiSecurity.VaidateUser(usrename, password))
- {
-
- actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
- }
- }
-
- base.OnAuthorization(actionContext);
- }
- }
Step 3
Our authorization filter is ready and we need to register it. You can register at global, controller or action level. Here, we have added for controller level.
- [BasicAuthentication]
- public class BlogController : ApiController
- {
-
- }
Note You can add the filter in either WebApiConfig or FilterConfig class file.
- In WebApiConfig.cs
config.Filters.Add(new BasicAuthenticationAttribute());
- In FilterConfig.cs
filters.Add(new BasicAuthenticationAttribute());
Step 4
Send an AJAX request to call WebAPI
It's time to call WebAPI through jQuery AJAX by passing the header information. In AJAX code, we added a new attribute called headers. It contains a value as authorization, btoa() to encrypt the username and password.
The btoa() method encodes a string in base-64. This method uses the "A-Z", "a-z", "0-9", "+", "/" and "=" characters to encode the string.
You can convert a string to base 64 encoding here.
- $.ajax({
- url: 'http://localhost:1312/api/Blog?type=json',
- type: "POST",
- contentType: "application/json",
- data: JSON.stringify(blogData),
- dataType: "json",
-
- success: function (result) {
-
- var htmlContent = "";
-
- $("#blogs > tbody > tr").remove();
-
- $.each(result, function (key, item) {
- htmlContent = htmlContent + "<tr><td>" + item.Id + "</td><td>" + item.Name + "</td><td>" + item.Url + "</td></tr>";
- });
-
-
- $('#blogs').append(htmlContent);
- },
- error: function (err) {
- alert(err.statusText);
- }
- });
Conclusion
We discussed about basic authentication in WebAPI. You can use it to provide security to your WebAPI Service.
Hope it helps.