How to Secure ASP.NET Web API – Part 1–Where?

There are many different approaches to secure your ASP.NET Web API.  At the very least, you should leverage HTTPS/SSL/TLS. 

Here is my attempt to compare simple ways to secure Web API using some API key.  oAuth and OpenID are outside of the scope.  I will leave the bigger topic of encryptions (i.e. public/private keys and the data to encrypt/decrypt) to a later post.

Where should you put your code?

 

Pros

HTTP modules

· Runs earlier in the pipeline than HTTP Message Handlers

· Useful for authentication for both MVC and Web API

HTTP Message Handler

· Supports self-hosting

· Can be configured for all Web API routes or per-route.

· Have principal information

· Useful for authentication for Web API

· Run earlier than Authorization filters.

Authorization Filter (a type of Action Filters)

· Useful for authorization.

· Can be configured for all controllers, specific controllers, and specific controller actions.

In summary, HTTP Message Handler is a good choice, for performance reason.  If your authentication logic is controllers/actions specific, then use Authorization Filters.

 

Why not just put it inside Controllers?

I guess you can always call some custom authentication/authorization routines inside controllers, but then you are not taken advantages of asp.net pipeline.

The earlier in the pipeline you put the code, the better performance saving you get since a failed authentication request is handled and returned earlier.

 

 

References:

http://www.asp.net/web-api/overview/advanced/http-message-handlers

http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api

http://jamiekurtz.com/2013/01/14/asp-net-web-api-security-basics/

http://codebetter.com/johnvpetersen/2012/04/02/making-your-asp-net-web-apis-secure/

http://codebetter.com/johnvpetersen/2012/04/04/moving-from-action-filters-to-message-handlers/

Advertisements

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