In previous posts I have show how we can easily expose a database table on the web using OData capabilities, by creating a OData Web Api Service. In this post I am going to demonstrate an easy way to make this service secure so that only properly authenticated users can access it.
If you have noticed the new features in Visual Studio 2013, they have done a lot to make Authentication and Authorization a snap. There are built in features to Register and LogIn users through site specific account as well as through a Google, Facebook or Microsoft Account.
I wanted to be able to reuse all this functionality in my OData Service Stack so that I can easily secure my service without reinventing the wheel again. Turns out, it wasn’t too difficult.
The Microsoft implementation of service stack for authentication is not through OData. So I decided to just add the built in authentication side by side to my OData Controllers.
The steps to create a Web Api with Authentication are pretty simple.
It actually gives a dialog window with four different options for Authentication. I chose the Individual Account one which is sufficient for my purpose. Go here to learn more on how to add authentication as well as what the four different options mean.
After that, all I had to do to my OData Controller was put an Authorize attribute on top of it’s class definition. Now this attribute takes care of returning a 401 Unauthorized message if the user tries to access it’s methods without first authenticating himself.
One more step that I decided to do was to move around the authentication related tables. When Visual Studio creates the Authentication tables and service layer, the tables are created in an mdf file in the App_Data folder by default. I grabbed the schema of those tables and recreated them in my SQL Server database where the rest of my tables resided. This ensured that all my tables are in one place.
Here is a 15 minute video detailing all the steps I took to create a service stack with Authorization enabled and then test it using fiddler: