Web API 2 security extensibility points part 1: starting point and HTTP request context

Introduction

Web API 2 comes with a number of new security features. In this new series we’ll concentrate on the HTTP request context and its Principal property. In particular we’ll see how to hook into the different extensibility points in the Web API. These extensibility points offer you to plug in your security-related checks at different points in the application lifetime when a request hits your API. You can carry out a number of checks and modify the request Principal according to your business rules and needs.

I’m building the demo in Visual Studio 2013. I’m not sure at this point how much the Web API template will change in Visual Studio 2015.

Web API 2 project starting point

We’ll start by creating a Web API 2 project in Visual Studio 2013. Open VS 2013 and select to create a new project of type ASP.NET Web Application called CustomersApi:

Create asp.net project in visual studio 2013

Click OK and then select the Web API project template. Click “Change Authentication” and select the “No Authentication” option:

Create Web API project with no authentication

Click OK and the project will be created. In fact the project template creates a mixed MVC and Web API project. It has a couple of views and you’ll find two controllers in the Controllers folder: HomeController which is an MVC controller and ValuesController which is an API controller.

We’ll first remove a couple of MVC things so that we can concentrate on the API parts.

Open RouteConfig.cs in the App_Start folder and remove the contents of RegisterRoutes:

public static void RegisterRoutes(RouteCollection routes)
{

}

Open WebApiConfig.cs in the same folder and remove the “api” bit from the route template in the Register method:

public static void Register(HttpConfiguration config)
{
	// Web API configuration and services

	// Web API routes
	config.MapHttpAttributeRoutes();

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

This is so that we can directly navigate to e.g. /customers and be directed to an API controller, not an MVC one.

Remove both controllers from the Controllers folder. Then right-click the Controllers folder and click Add, Web API controller class (v2) in the context menu. Call it CustomersController. The template will add the same contents as there is for the default ValuesController which we have just deleted. Remove all of that and instead add the following Get action method:

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);
}

…where Customer is located in the Models folder and has the following properties:

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

Run the application and call the /customers extension in the browser. In Chrome you should see the list of customers in XML format:

List of customers in XML format from Web API 2 project

We could strip off a lot more stuff from the project to make it a pure API project. All elements related to MVC views could be deleted such as fonts, Content, Views, Scripts etc. However, the fact that we can reach the CustomersController without adding the “api” bit in the route is good enough for now.

The request context

The HTTP request context allows us to access some key properties of the incoming request. You can read the properties list here on MSDN but we’re mostly interested in the property called Principal in this series.

The request context can be accessed in at least 2 ways within a controller. The Request property has an extension method called GetRequestContext() which returns an HttpRequestContext in the System.Web.Http.Controller namespace:

HttpRequestContext httpRequestContext = Request.GetRequestContext();

The shorthand version within a controller class is the RequestContext property. We can add the following test code to the beginning of the Get action method:

HttpRequestContext httpRequestContext = Request.GetRequestContext();
Debug.WriteLine(string.Format("Principal authenticated from extension method: {0}", httpRequestContext.Principal.Identity.IsAuthenticated));
Debug.WriteLine(string.Format("Principal authenticated from shorthand property: {0}", RequestContext.Principal.Identity.IsAuthenticated));

If you run /customers then you’ll see the following output in the Debug window:

Principal authenticated from extension method: False
Principal authenticated from shorthand property: False

This is the expected result as we’ve allowed anonymous usage of the web application. The Principal property of the request context which is of type IPrincipal has an Identity property of type IIdentity. Both properties help you find information about the logged in user, his/her set of claims and a lot more.

HttpRequestContext.Principal has a short-hand property called User available in a controller class:

Debug.WriteLine(string.Format("Principal authenticated from User: {0}", User.Identity.IsAuthenticated));

That also resolves to false of course.

This is enough to start with. We’ll look at how to construct a custom authentication filter in the next part of the series.

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 Web API 2 security extensibility points part 1: starting point and HTTP request context

  1. Karthick_India says:

    excellent article Andras

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: