Wiring up a custom authentication method with OWIN in Web API Part 1: preparation

Introduction

There are a number of authentication types for a web project: basic -i.e. with username and password -, or token-based or claims-based authentication and various others. You can also have some custom authentication type that your project requires.

In this short series we’ll go through how to wire up a custom authentication method in a Web API project. We’ll see the classes that are required for such an infrastructure. We’ll also discuss how to wire up these elements so that the custom authentication mechanism is executed as part of the chain of Katana components.

What are OWIN and Katana?

We’ve taken up OWIN and Katana in various series on this blog lately so I won’t repeat that stuff here. Check out this page and scroll down to the “OWIN and Katana” section. In short Katana is a new light-weight web framework built by Microsoft. It is based on a specification called OWIN – Open Web Interface for .NET. The default MVC5 template in Visual Studio 2013 have elements of Katana and OWIN.

OWIN has been around for a while now so I guess you’ve come across it in your .NET development work. If not then check out one of the series available on this blog to get to learn the basics.

This page has a number of posts dedicated to OWIN and Katana at a basic level. Whereas this page lists the posts on security. Check out the posts under the sections “Claims transformation posts” and “Web API 2”.

The custom authentication type

In this demo we’ll simulate that the authentication details are stored in the HTTP header “x-company-auth”. The details need to include two elements: a user id and a PIN consisting of 6 digits that can only be used once. You may have seen authentication schemes where you get a number of pre-generated PIN numbers on a list that you have to provide for each transaction. I used to have a bank account which had a similar security mode. I had to provide a PIN from a list upon logging in every time I wanted to view my account. Our scenario is an approximation of that system.

Don’t get bogged down by this scenario however. The main goal of this series is to show you a possible solution for how to wire up any custom authentication mechanism with OWIN.

Starting point

I’ll be doing this demo in Visual Studio 2012 using a fairly empty Web API 2 project template. You should be able to follow the steps in VS 2013 as well. If you start an MVC5 project in VS 2013 then you’ll automatically get the OWIN-related libraries included in the project. For this demo I’ll use VS2012.

Fire up Visual Studio 2012 and start a new Web API project called “CustomAuthenticationOwin”. I downloaded the MVC5 project templates for VS 2012 from this link if you need to do the same. It gave me the following template type:

Empty Web API 2 project template

The project is very empty to start with:

Empty web api project

Open WebApiConfig.cs and remove the “api” bit from the route setup:

config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
	name: "DefaultApi",
	routeTemplate: "{controller}/{id}",
	defaults: new { id = RouteParameter.Optional }
);

Adding OWIN

This project has no OWIN installed at all currently. Therefore we’ll add the OWIN parts to begin with using the steps we saw in this series.

In order to integrate the OWIN pipeline into our application we’ll need to add a couple more NuGet packages. First off the OWIN version of System.Web:

Install SystemWeb OWIN through NuGet

Second let’s add the following NuGet package:

Install Web API Owin through NuGet

The Startup class

The Startup class is the entry point into a Katana-based application. It’s like Global.asax in a traditional ASP.NET app. If you go through the posts on OWIN/Katana referenced above you’ll know that by convention this entry point class must be called “Startup” and not “StartUp” or “startup” i.e. the casing is important. Another convention is that the Startup class must contain a method called Configuration which accepts an object of type IAppBuilder.

Therefore add a class called Startup to the root of the project:

public class Startup
{
	public void Configuration(IAppBuilder appBuilder)
	{
             Debug.WriteLine("OWIN is working.");
	}
}

…where IAppBuilder is located in the Owin namespace.

Start the project. If everything has gone well then you should see “OWIN is working” printed in the debug window, meaning that the Startup class was successfully registered.

Adding a controller

Add the following Customer class to the Models folder:

public class Customer
{
	public string Name { get; set; }
	public string Address { get; set; }
	public string Telephone { get; set; }
}

Right-click the Controllers folder and add a new empty Web API controller:

Add empty controller to project

Call it CustomersController and add the following Get method to return a list of customers:

public class CustomersController : ApiController
{
	public IHttpActionResult Get()
	{
		IList<Customer> customers = new List<Customer>();
		customers.Add(new Customer() { Name = "Nice customer", Address = "USA", Telephone = "123345456" });
		customers.Add(new Customer() { Name = "Good customer", Address = "UK", Telephone = "9878757654" });
		customers.Add(new Customer() { Name = "Awesome customer", Address = "France", Telephone = "34546456" });
		return Ok<IList<Customer>>(customers);
	}
}

Run the web app. Extend the localhost URL with /customers and press Enter in the browser. You should see the three customers on the screen. How the customer objects are presented depends on the browser type but in Chrome it looks like this:

Customers list presented as XML

This is enough for starters. We’ll continue by building the components around the OWIN middleware in the next post.

You can view the list of posts on Security and Cryptography here.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Wiring up a custom authentication method with OWIN in Web API Part 1: preparation

  1. Pingback: Wiring up a custom authentication method with OWIN in Web API Part 2: the headers | Dinesh Ram Kali.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

My goal with this blog is to offend everyone in the world at least once with my words… so no one has a reason to have a heightened sense of themselves. We are all ignorant, we are all found wanting, we are all bad people sometimes.

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: