srijeda, 26. lipnja 2013.

ASP.NET MVC4 Facebook application, facebook authorization and form post data

OK - so I've seen this great tutiral on creating Facebook app's with ASP.NET MVC4. I figured - this will be peace of cake - I have a cool idea which I'm about to implement, and just follow this steps and everything should work. However, this is never true. First thing I stumbled upon were simple post-forms. The problem is when one uses FacebookAuthorize attribute on an action or a controller, and attempts a simple post to this page, it simply doesn't work! The problem is further described in this stackoverflow question

Basically, the problem is because for some reason FacebookAuthorize filter makes a redirect to check the identity of an user. It took me at least 2 hours to find a reason for this behaviour - the code is actually available online to see, on this github link. The solution lies in code between lines 50 and 60 - FacebookAuthorize checks if there exists a specific request parameter, named "signed_request", and if it does not exist, the redirect is made and all our post data is lost.

The best solution I could come up is making a simple hidden field inside our form which is named "signed_request" and contains this request. For that purpose, I've made this nice extender method that does the job:


public static class FacebookHelpers
    {
        public static MvcHtmlString RenderAuthorizationToken(this HtmlHelper helper)
        {
            var signedReqValue = helper.ViewContext.RequestContext.HttpContext.Request["signed_request"];

            TagBuilder hdnBilder = new TagBuilder("input");
            hdnBilder.Attributes.Add("type", "hidden");
            hdnBilder.Attributes.Add("name", "signed_request");
            hdnBilder.Attributes.Add("value", signedReqValue);

            return MvcHtmlString.Create(hdnBilder.ToString(TagRenderMode.SelfClosing));
        }
    }
It can be used like this using razor: @Html.RenderAuthorizationToken()
Problem: [solved].

1 komentar:

  1. Hi, I'm new to Asp.Net MVC 4, so I still don't know where to put this code...

    I've created the FacebookHelpers class, but I don't know what to do with the @Html.RenderAuthorizationToken() (Razor) code.

    Can you help me? Thanks!

    OdgovoriIzbriši