Custom ASP.NET MVC Authorization with Facebook Connect

Posted Posted by Ahmad Barirani in Blog     Comments 4 comments
Sep
20

Action filters are an interesting concept in ASP.NET MVC. The point with action filters is that you can basically intercept a call to an ASP.NET MVC action and execute some code before the action’s code is executed. The ‘Authorize’  action filter is often used in Forms Authentication to make sure that an action reserved to a member is not executed by a non-member. When it come to using this feature with Facebook Connect applications, things get a little bit dirty. In this article, I will explore some contradicting aspects of Facebook Connect in regards to its integration with Forms Authentication and propose a solution which is based on implementing a custom ASP.NET MVC authorization.

Forms authentication is a cookie-based authentication method. The thing is that Facebook Connect also uses cookies as a mean of authentication. A Facebook cookie contains a session key which is valid for the session. Facebook API calls must be done with this session key to associate actions to a Facebook account.

Now, if a developer wants to use both Forms Authentication and Facebook cookies to handle a session, there will be countless issues of data incoherence to handle (ex: Facebook sessions expire when the browser is closed, but not Forms Authentication sessions).

The solution is to not use Forms Authentication or any other ASP.NET authentication at all, but use a custom authorization class which wraps Facebook’s session cookie. To do so, create a new class like with the following code:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (Validate_Facebook_Connect_Cookie())
            return true;
 
        httpContext.Response.Redirect("Facebook_Connect_URL");
        return false;
    }
}

The ‘Validate_Facebook_Connect_Cookie()‘ function should look into the cookie and verify that the user is correctly authenticated. Now, all you have to do is to add the ‘[CustomAuthorize]‘ attribute to those actions that need authorization.

4 Comments to “Custom ASP.NET MVC Authorization with Facebook Connect”

Post comment

About Singular Technologies

Location: Montreal, Canada

Services: Data mining. Information retrieval. Social networks analysis.

Featured Website