In this blog post we will implement HTTP Basic Authentication on a DD4T REST service. For instructions on how to setup a DD4T RestService follow the instructions described in previous #dd4tdaily articles
DD4T.RestService.WebApi is based on OWIN (Open Web Interface for .NET), a new standardized interface between web servers and web applications. It is meant as a way to break up the tight coupling between ASP.NET and IIS. In this article I will not go in depth on what OWIN is, but it’s essential for this blog post to have a basic understanding on how this works. OWIN allows you to assemble and construct the pipeline of a HTTP Request, by adding so called Middleware to the pipeline. DD4T.RestService.WebApi is a middleware.
After installing the DD4T.RestService.WebApi NuGet package there is a Startup.cs class created in the root of the application, with a method called “Configuration”. Within this method we are able to add Middleware’s to the OWIN pipeline.There are Authentication modules written for OWIN by the community. In this post we will add Basic Authentication module to the service.
- Install NuGet package “Thinktecture.IdentityModel.Owin.BasicAuthentication“
- Update your startup file with the following startup.cs
Let’s have a closer look at the code. First of all we are adding 2 Middlewares to the pipeline.
- app.UseBasicAuthentication(…. ….)
- app.ForceAuthentication(authenticationType);
The first middleware makes sure that the request should have a “Basic” authentication header in the request and as parameter it accepts a BasicAuthenticationOptions object. Within this object we are able to customize the behavior of the Middleware. What we need to verify is if the hashed key in the request header is actually correct. BasicAuthenticationOptions accepts a parameter in the constructor method (Validate in this example). Within this method we are retrieving 2 parameters, “id” and “secret”, allowing us to verify if it’s correct. The second Middleware is forcing the request to be Authenticated.