When a REST Web API is created to share data across multiple devices, e.g., mobile devices, desktop applications, or any website, then the authorization of REST Web API becomes a vital aspect in order to protect data sensitivity from any outside breaches.
Today, I shall demonstrate a simple mechanism to authorize a REST Web API without the complex authorization process of OWIN security layers but at the same time, benefiting from [Authorize] attribute.
The prerequisites include knowledge about the following technologies.
- ASP.NET MVC 5.
- C# programming.
- REST Web API.
You can download the complete source code for this or you can follow the step by step discussion given below. The sample code is developed in Microsoft Visual Studio 2013 Ultimate.
Let's begin now.
- Create new Web API project and name it as "WebApiAuthorization".
- Rename "ValueController.cs" file to "WebApiController.cs".
- Now, in "WebApiController.cs" file replace the following code.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- namespace WebApiAuthorization.Controllers {
- [Authorize]
- public class WebApiController: ApiController {
-
- public IEnumerable < string > Get() {
- return new string[] {
- "Hello REST API",
- "I am Authorized"
- };
- }
-
- public string Get(int id) {
- return "Hello Authorized API with ID = " + id;
- }
-
- public void Post([FromBody] string value) {}
-
- public void Put(int id, [FromBody] string value) {}
-
- public void Delete(int id) {}
- }
- }
In the above code, I simply replaced some of the existing string values, nothing special is done here.
- Now, for the authorization part, I am using HTTP Message Handlers technique, its detail can be studied here. In simple essence, this technique captures HTTP request sand responds accordingly. In order to use this technique, we need to inherit "DelegatingHandler" class and then hook its method SendAsync(...) that will process every hit to our REST Web API and verify our allocated authorization or API header key accordingly. Then, it will finally set our Principal after successful authorization. Principal will simply set our security context by containing information about the user whom we have claimed as authorized user by using Identity Based Authorization. This will allow us to utilize [Authorize] attribute for our Web API controller.
So, create new folder under project root >> Resources and name it "Constants". I like my code architecture clean, so, I am using Constants in a resource file.
- Now, create a file "Resource->Constants-> ApiInfo.resx". Open the file and place the following constants in it.
Make sure that Access Modifier is set to Public. This file will contain authorization constants that I will be using to authenticate my REST Web API.
- Now, create new folder hierarchy under project root i.e. "Helper_Code->Common".
- Create your authorization file and name it "Helper_Code->Common->AuthorizationHeaderHandler.cs".
- Open the file "Helper_Code->Common->AuthorizationHeaderHandler.cs" and replace it with the following piece of code.
-
-
-
-
-
-
- namespace WebApiAuthorization.Helper_Code.Common {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Security.Claims;
- using System.Security.Principal;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Web;
- using WebApiAuthorization.Resources.Constants;
-
-
-
- public class AuthorizationHeaderHandler: DelegatingHandler {#
- region Send method.
-
-
-
-
-
-
- protected override Task < HttpResponseMessage > SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
-
- IEnumerable < string > apiKeyHeaderValues = null;
- AuthenticationHeaderValue authorization = request.Headers.Authorization;
- string userName = null;
- string password = null;
-
- if (request.Headers.TryGetValues(ApiInfo.API_KEY_HEADER, out apiKeyHeaderValues) && !string.IsNullOrEmpty(authorization.Parameter)) {
- var apiKeyHeaderValue = apiKeyHeaderValues.First();
-
- string authToken = authorization.Parameter;
-
- string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
-
- userName = decodedToken.Substring(0, decodedToken.IndexOf(":"));
- password = decodedToken.Substring(decodedToken.IndexOf(":") + 1);
-
- if (apiKeyHeaderValue.Equals(ApiInfo.API_KEY_VALUE) && userName.Equals(ApiInfo.USERNAME_VALUE) && password.Equals(ApiInfo.PASSWORD_VALUE)) {
-
- var identity = new GenericIdentity(userName);
- SetPrincipal(new GenericPrincipal(identity, null));
- }
- }
-
- return base.SendAsync(request, cancellationToken);
- }#
- endregion# region Set principal method.
-
-
-
-
- private static void SetPrincipal(IPrincipal principal) {
-
- Thread.CurrentPrincipal = principal;
-
- if (HttpContext.Current != null) {
-
- HttpContext.Current.User = principal;
- }
- }#
- endregion
- }
- }
In the above code, "Helper_Code->Common->AuthorizationHeaderHandler.cs" class inherits "DelegatingHandler" class. We have hooked the "SendAsync(...)" method and created a new method "SetPrincipal(...)" to set our authorization principal.
Now, let’s discuss the above code chunk by chunk .i.e.
In Method "SetPrincipal(...)" the following code
-
- Thread.CurrentPrincipal = principal;
-
- if (HttpContext.Current != null) {
-
- HttpContext.Current.User = principal;
- }
The above code will set our authorization principal with Identity Based Authorization model.
Let’s dissect "SendAsync(...)" method step by step.
-
- if (request.Headers.TryGetValues(ApiInfo.API_KEY_HEADER, out apiKeyHeaderValues) && !string.IsNullOrEmpty(authorization.Parameter)) { ...
- }
The above lines of code will verify whether our authorized header key and credentials are empty or not. I have used a combination of both header key and credentials to authorize my REST Web API.
If the authorization is successful, then the following code will extract our authorization information from the HTTP request and store them into local variables.
- var apiKeyHeaderValue = apiKeyHeaderValues.First();
-
- string authToken = authorization.Parameter;
-
- string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
-
- userName = decodedToken.Substring(0, decodedToken.IndexOf(":"));
- password = decodedToken.Substring(decodedToken.IndexOf(":") + 1);
After above code, we will verify whether the provided authorization for REST Web API hit is valid or not, with the following code.
-
- if (apiKeyHeaderValue.Equals(ApiInfo.API_KEY_VALUE) && userName.Equals(ApiInfo.USERNAME_VALUE) && password.Equals(ApiInfo.PASSWORD_VALUE)) { ...
- }
If the hit to our REST Web API contains valid authorization credentials and header key, then we register our principal with Identity Based Authorization model.
-
- var identity = new GenericIdentity(userName);
- SetPrincipal(new GenericPrincipal(identity, null));
- Now, Open "Global.asax.cs" file and replace following code in it i.e.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Http;
- using System.Web.Mvc;
- using System.Web.Optimization;
- using System.Web.Routing;
- using WebApiAuthorization.Helper_Code.Common;
- namespace WebApiAuthorization
- {
- public class WebApiApplication : System.Web.HttpApplication
- {
- protected void Application_Start()
- {
- AreaRegistration.RegisterAllAreas();
- GlobalConfiguration.Configure(WebApiConfig.Register);
- FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
- RouteConfig.RegisterRoutes(RouteTable.Routes);
- BundleConfig.RegisterBundles(BundleTable.Bundles);
-
-
- GlobalConfiguration.Configuration.MessageHandlers.Add(new AuthorizationHeaderHandler());
- }
- }
- }
In the above code we have registered our authorization class within global configuration.
- Now, execute the project and use the following link in the browser to see your newly created REST Web API method in action.
In the above snippet, you will notice that so far, our REST Web API has been authorized, therefore, we cannot directly execute the REST Web API URL in the browser.
- Let's test out REST Web API in REST Web API client. I am using Firefox plugin i.e. "RESTED". At first, I simply try to hit the REST Web API without any authorization details and I will get the following response.
- Now, I will provide the authorization and hit the REST Web API and will get following response i.e.
Conclusion
In this tutorial, we learned how to authorize REST Web API by using a simple technique of HTTP Message Handlers without going into the complex nature of OWIN. We also learned about principal authentication for identity claim based authorization model, which will enable the utilization of [Authorize] attribute.