HowTo: Facebook Connect & ASP.NET MVC

image

Facebook has created a nice little service named "Facebook Connect". With this application Facebook user are allowed to login into your site with their usual facebook log-in information´s and the whole thing is secured by Facebook. In Fact it´s quite similar to OpenID but it had some more specials than just identification. But in this HowTo we are just going to talk about the identification.

Why should I use this?

Because if you spend a lot of time into building something stunning and you want other people in public to see this than it´s much easier for them to login with their already created Facebook login files than to register again on your site and remember another keyword.

image

You convinced me. What do I need?

  • your own Facebook account
  • an API key (look at the registration)
  • in best case a library which will do most of the serious work
  • 10 minutes of time

    First step: get a Facebook account

    Just register yourself here.

    image

    Not as hard as you thought, hum? ;)

    Second step: register for the Facebook Connect / Facebook Development Account

    At the bottom of the Facebook page you will found a link named “developer”. Here you need to create an application. Than you need to enter a name and a URL.

     

    Wichtig für die Entwicklung: Localhost

    The API keys of Facebook are mapped on a URL. In conclusion you need to fix the port in visual studio according to the web server (In my example it is 55555) or you use the IIS.

    Especially with localhost there is another thing to beware if you want it to work:

    Ignore the second step. I´m going to talk about this later.

    Here are the two most important API keys:

    image

    Now you are able to see your application on the “Developer dashboard“.

    That´s exactly where we have to go now. Here you will find all your former created applications. During the registration for the Connect service Facebook creates a “Base Domain” for you. That´s very useful if you are planning to use many different domains but it will not work with local host. So we need to edit the application:

    image

    Please delete the base domain in the connect tab.

    image

    Now we are ready for developing. By the way, the fight with the base domain costs me 4 entire nights ;)

    Step 3: create an ASP.NET MVC Project

    Create a new ASP.NET MVC Project…

    Step 4: Facebook Developer Toolkit

    The Facebook Developer Toolkit is a .NET OpenSource wrapper around the REST APIs from Facebook. Microsoft supports this. Unfortunately there are several other .NET APIs but for now this is the easiest way.

    We need the SDK Binaries .

    Now our project should look like this:

    image

     

     

    Of course we need to reference the 3 Facebook .DLLs.

     

     

     

    Step 5: Facebook API Key + Facebook API Secret in .config

    I add both the keys to the web.config.

      <appSettings>
        <add key="Facebook_API_Key" value="462ab423fdc4d27XXXXXXX6a085af" />
        <add key="Facebook_API_Secret" value="641ca675f280XXXXXXXXded099"/>
      </appSettings>

    Step 6: prepare the Masterpage

    Now you have to include a Facebook Javascript into the Masterpage. After that you open the “init” Function with the API key and I refer to an “xdReceiver” file which will play an important role later.

        <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/de_DE" type="text/javascript"></script>
        <script type="text/javascript">FB.init("<%this.Writer.Write(ConfigurationManager.AppSettings["Facebook_API_Key"]); %>","XdReceiver");</script>
        

    Step 7: include the Facebook Login Button into the Home/Index View

    The People of Facebook created their own Markup (FBML) for Buttons, Pictures and so on. For example the Login Button looks like this:

     

        <p>
            <fb:login-button v="2" size="medium" onlogin="window.location.reload(true);">Mit Facebook anmelden</fb:login-button>
        </p>

    To keep the HTML valid you have to integrate the XML Namespace as well

    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">

    Schritt 8: Die XdReceiver Datei

    Step 8: the XdReceiver file

    That´s the file facebook already offer to us during the registration. With this file you are aloud to connect via AJAX to Facebook.

     

    <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <body>
            <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.js" type="text/javascript"></script>
        </body>
    </html>

    I stored this xdReceiver file into the home folder and I also created an xdReceiver action to render the view.

    Additionally I created a “Facebook” route into Global.asx. If a User registered successfully via facebook on your homepage he will automatically send up to “Domain/xdReceiver” via DEFAULT

                routes.MapRoute("Facebook",
                                "XdReceiver",
                                new {controller = "Home", action = "XdReceiver"});

    Step 9: the Homecontroler

    The last step is to control if the user is signed in successfully ore not.

    public ActionResult Index()
            {
                ConnectSession session = new ConnectSession(ConfigurationManager.AppSettings["Facebook_API_Key"], ConfigurationManager.AppSettings["Facebook_API_Secret"]);
                if(session.IsConnected())
                {
                    Api facebook = new Api(session);
    
                    ViewData["Message"] = "Hello, " + facebook.Users.GetInfo().name;
                }
                else
                {
                    ViewData["Message"] = "Login with Facebook!";
                }
    
                return View();
            }

    If the user is already signed in with facebook his username will be shown. Otherwise the “Log in with facebook” sign will appear.

    Result:

    start Login…

    image

    *klick*

    image

    *connect*

    image

    All in all it doesn´t take a lot of your time and the developer of facebook did a great job with their API. (excluded the base domain … if you enter this, local host won´t work)

    More Links:

    [Download Source Code]

    If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

    About the author

    Written by Code Inside Team

    Currently there is no additional info about this author.

    4 Responses

    1. Hi,

      I m not able to download the source code..broken link…
      Can u provide the correct link to download the source code…

      It will be of gr8 help….

      Reply
    2. Hi Fenil,
      the link is working.. at least on my computer :)

      If the link still won’t work, try:

      http://code-inside.de/files/democode/mvcfacebookconnect/mvcfacebookconnect.zip

      Reply
    3. Hi,

      I’m getting this error. Why? Could you help me please?

      To fix this error, please set your Connect URL in the application settings editor. Once it has been set, users will be redirected to that URL instead of this page after logging in.

      Many Thanks!

      Nando Stuull.

      Reply
    4. wats up friend. you’ve put up a good blog and i actually liked reading your posts. i wonder how you will know all this stuff. i was impressed when i looked at your blog. what blogging platform did you make use of for this blog. i’m utilising wordpress and i find it somewhat challenging. are you using wordpress too? if yes can you tell me about the themes and plugins you use for your blog. i will be grateful if you guide me on this.

      Reply

    Comment on this post

    Recent Posts

    • Windows Phone Fonts & what if Visual Studio lies

      Today I was confronted with a little Problem: my Windows Phone App refused to show me the Font I choose – also other thinks didn’t work. Although the Visual Studio Designer did show the Fonts: Unfortunately there isn’t much left in the Emulator: Reason for this: Windows Phone doesn’t include all the typos Windows does ...

    • Json-Online-Tools: Viewer & Json2Csharp generator

        Wherever APIs are mentioned the JSON format I not far away. Since I’m using two tools regularly I would like to introduce you to them. JSON Viewer If you only see the JSON-Text you are usually not able to see the structure. With the help of JSON Viewer you can have an easy overview: ...

    • Windows Phone SDK & „System“-Icons

        Although the Metro Design focuses a lot on Typography Icons are still quite important. If you install Windows Phone SDK you will receive 36 Icons. You can find them here: C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\Icons Unfortunately many Icons you might know from the common applications are not integrated. Pedro Lamas extracted 99 additional Icons ...

    • image1830-570x194.png
      How can I figure out if my ADFS 2.0 works?

        I was working with ADFS 2.0 (“Active Directory Federation Services”) for a while when this simple question crossed my mind: How can I figure out if the connection between ADFS and AD “works”? Here is a simple test… What is ADFS? If you need some “position of trusts” beneath the AD-boarders you choose an ...

    • Subdomain vs. Subdirectory

        Better blog.mydomain.com or mydomain.com/blog? Good question! If got asked this question again via Twitter on the weekend so therefore I decide to share my experiences:   Choose a subdomain, if…. - You plan to offer “different services” which are “logical separated” on one domain - You are able to influence the subdomains without much ...

    Support us