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?



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 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.





Leave a Reply

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

You are commenting using your 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