Thursday, 25 October 2012

API Keys for WEB API






ASP.NET Web API is a great tool to build an API with. Or as my buddy Kristof Rennen (and the French) always say: “it makes you ‘api”. One of the things I like a lot is the fact that you can do very powerful things that you know and love from the ASP.NET MVC stack, like, for example, using filter attributes. Action filters, result filters and… authorization filters.
Say you wanted to protect your API and make use of the controller’s User property to return user-specific information. You probably will add an [Authorize] attribute (to ensure the user is authenticated) to either the entire API controller or to one of its action methods, like this:
[Authorize]
public class SuperSecretController 
    : ApiController
{
    public string Get()
    {
        return string.Format("Hello, {0}", User.Identity.Name);
    }
}
Great! But… How will your application know who’s calling? Forms authentication doesn’t really make sense for a lot of API’s. Configuring IIS and switching to Windows authentication or basic authentication may be an option. But not every ASP.NET Web API will live in IIS, right? And maybe you want to use some other form of authentication for your API, for example one that uses a custom HTTP header containing an API key? Let’s see how you can do that…

Our API authentication? An API key

API keys may make sense for your API. They provide an easy means of authenticating your API consumers based on a simple token that is passed around in a custom header. OAuth2 may make sense as well, but even that one boils down to a custom Authorizationheader at the HTTP level. (hint: the approach outlined in this post can be used for OAuth2 tokens as well)
Let’s build our API and require every API consumer to pass in a custom header, named “X-ApiKey”. Calls to our API will look like this:
GET http://localhost:60573/api/v1/SuperSecret HTTP/1.1
Host: localhost:60573
X-ApiKey: 12345

In our SuperSecretController above, we want to make sure that we’re working with a traditional IPrincipal which we can query for username, roles and possibly even claims if needed. How do we get that identity there?

Translating the API key using a DelegatingHandler

The title already gives you a pointer. We want to add a plugin into ASP.NET Web API’s pipeline which replaces the current thread’sIPrincipal with one that is mapped from the incoming API key. That plugin will come in the form of a DelegatingHandler, a class that’s plugged in really early in the ASP.NET Web API pipeline. I’m not going to elaborate on what DelegatingHandler does and where it fits, there’s a perfect post on that to be found here.
Our handler, which I’ll call AuthorizationHeaderHandler will be inheriting ASP.NET Web API’s DelegatingHandler. The method we’re interested in is SendAsync, which will be called on every request into our API.
public class AuthorizationHeaderHandler
    : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // ...
    }
}
This method offers access to the HttpRequestMessage, which contains everything you’ll probably be needing such as… HTTP headers! Let’s read out our X-ApiKey header, convert it to a ClaimsIdentity (so we can add additional claims if needed) and assign it to the current thread:
public class AuthorizationHeaderHandler
    : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        IEnumerable<string> apiKeyHeaderValues = null;
        if (request.Headers.TryGetValues("X-ApiKey", out apiKeyHeaderValues))
        {
            var apiKeyHeaderValue = apiKeyHeaderValues.First();

            // ... your authentication logic here ...
            var username = (apiKeyHeaderValue == "12345" ? "Maarten" : "OtherUser");

            var usernameClaim = new Claim(ClaimTypes.Name, username);
            var identity = new ClaimsIdentity(new[] {usernameClaim}, "ApiKey");
            var principal = new ClaimsPrincipal(identity);
            
            Thread.CurrentPrincipal = principal;
        }

        return base.SendAsync(request, cancellationToken);
    }
}
Easy, no? The only thing left to do is registering this handler in the pipeline during your application’s start:
GlobalConfiguration.Configuration.MessageHandlers.Add(new AuthorizationHeaderHandler());
From now on, any request coming in with the X-ApiKey header will be translated into an IPrincipal which you can easily use throughout your web API. Enjoy!
PS: if you’re looking into OAuth2, I’ve used a similar approach in  “ASP.NET Web API OAuth2 delegation with Windows Azure Access Control Service” to handle OAuth2 tokens.





Sunday, 7 October 2012

It is better to learn javascripts Now itself


Hi All


http://www.sergiopereira.com/articles/advjs.html

Special thanks Goes to Waruna @ Exilesoft for linking me with this content.




Thursday, 4 October 2012

Introducing the ASP.NET Web API Help Page



Microsoft ASP.NET Web API Help Page

 

0.1.0-alpha-120814

The ASP.NET Web API Help Page automatically generates help page content for the web APIs on your site. Visitors to your help page can use this content to learn how to call your web APIs. Everything generated by the help page is fully customizable using ASP.NET MVC and Razor. ASP.NET Web API Help Page is a great addition to any ASP.NET Web API project.
To install Microsoft ASP.NET Web API Help Page, run the following command in the Package Manager Console
PM> Install-Package Microsoft.AspNet.WebApi.HelpPage -Pre

Owners





http://blogs.msdn.com/b/yaohuang1/archive/2012/08/15/introducing-the-asp-net-web-api-help-page-preview.aspx



Tuesday, 2 October 2012

Good Article Regarding Stored Procedures Performance



Stored Procedures DO NOT increase performance



In order prove the above point I did a couple of experiments. I wrote a simple .NET application which makes calls to SQL Server by using both methodologies, i.e., simple inline SQL and stored procedure.
Below is a simple experiment to prove the same.
We have created two scenarios: one which will run a simple inline SQL as shown below. This SQL goes and queries a simple “Users” table to check if a user exists in the database or not.
SqlCommand objCommand = new SqlCommand("Select * from Users where UserName='"
                                        + UserName + "' and Password='"
                                        + Password + "'", objConnection);
In the second scenario the same inline SQL is wrapped in a stored procedure called “sp_login”.
SqlCommand objCommand = new SqlCommand("sp_Login", objConnection);
objCommand.Parameters.Add(new SqlParameter("UserName", UserName));
objCommand.Parameters.Add(new SqlParameter("Password", Password));
objCommand.CommandType = CommandType.StoredProcedure;
Both these SQLs are fired from the application with a profiler running in the background. We capture two events when we ran the profiler: CacheHit and CacheInsert. The CacheInsert event is fired when the plan is inserted in the cache while CacheHit is fired when the plan is used from the cache.
When we ran the experiment with the stored procedure we saw the below results. You can see in the trace below:
CacheInsert” first creates the plan and inserts it into the cache. Once the plan is cached the CacheHit event occurs which means it has taken the plan from the cache rather than recreating it from scratch.
When we ran the experiment with inline SQL we saw similar kinds of results. You can see how the CacheHit event is hit after the CacheInsert event is fired.

Cheater, change the data?

If you see look at the previous experiment, the data is absolutely the same. The time I change the data as shown in the figure below, you can see it’s no longer using the cache, rather creating new cache entries. 
 
Let me go ahead and tweak the ADO.NET code to support parameters as shown below.
SqlCommand objCommand = new SqlCommand(
   "Select * from Users where UserName=@userName and Password=@Password", objConnection);
objCommand.Parameters.AddWithValue("@userName", UserName);
objCommand.Parameters.AddWithValue("@Password", Password);
When I capture the cache events in the profiler it is using the cache. You can see in the below figure how first the cache insert event occurs and after that it always hits the cache for the plan rather than recreating it.

Dynamic SQL and Dynamic SQL

One of the most confusing terminologies people use is Dynamic SQL. Let’s refine this word further. There are two types of dynamic SQL: one is dynamic SQL and the other is parameterized dynamic SQL.
Courtesy: Spiderman 3
Dynamic SQL is of the form as shown below (it can be more dynamic where column names are also built on the fly).
SqlCommand objCommand = new SqlCommand("Select * from Users where UserName='"
                                        + UserName + "' and Password='"
                                        + Password + "'", objConnection);
The above dynamic SQL will probably not use the plan from the cache until auto parameterization helps (http://msdn.microsoft.com/en-us/library/aa175264(v=sql.80).aspx).
If you use parameterized dynamic SQL like below, it will use the SQL plan from the cache as done by stored procedures.
SqlCommand objCommand = new SqlCommand("Select * from Users where UserName=@userName and Password=@Password", objConnection);

objCommand.Parameters.AddWithValue("@userName", UserName);
objCommand.Parameters.AddWithValue("@Password", Password);
In simple words performance of inline parameterized SQL is the same as that of Stored Procedures.







Type Script From Microsoft


Those who really wanted to implement design patterns without knowing javascripts :)

http://www.typescriptlang.org/Playground/


Cheers!!!

I want my home office to be like this








Into the Great Outdoors

When a closed office door no longer keeps the kids at bay, here's an idea: Just move into the backyard! This luxurious office space by OfficePOD is a flexible and complete working environment with built-in desk and storage, lighting, power, ventilation, heating, and cooling. Enjoy the view, the privacy, and a more productive workday. Bonus: You can brag about having the world's shortest commute.



Extracted From - http://www.inc.com/ss/marla-tabaka/7-crazy-space-savers-home-office#7