:::: MENU ::::

Facebook authentication from Windows Phone app

To share statuses on Facebook from your Windows Phone app, all you have to do is use a launcher called ShareStatusTask, and the system takes care of the rest (in case your phone is connected to social networks where you’d like to share). In cases other than simple statuses or links (for example, photos), you need to take care of connecting your app to Facebook yourself. This would be a tricky thing if you had to write all the code yourself, but luckily there’s a library called Facebook C# SDK that handles much of the trouble for you. Still, you need to write some code and authorize your app to access someone’s Facebook, and this article is all about that.

To start with Facebook in your application, first of all you need to get the Facebook C# SDK I mentioned before. You can find it on the following links:

Home page – find some useful tutorials here

github – find the source code here

NuGet – get the library in your project from here

The current project version (at the moment of writing this article) is 6.0.20.

Once you have the SDK inside your app project, you need to understand what happens when you want your app to communicate with Facebook. First of all, you need to let Facebook know that you’ll be using their APIs. In other words, you need to register your app. You can register your app here:

https://developers.facebook.com/apps

by clicking on Create New App. The only compulsory field is App Name, and you’re done.

image

After you’re done, you’ll get App ID/API Key and AppSecret. You’ll need those information later on to do stuff from your app, so I suggest you created the following classes in your project:


FacebookSettings will hold the information about your app, and FacebookAccess will hold information about the user who authorized your app to access his or her Facebook.

Facebook authentication gives your app the ability to know the identity of a Facebook user who uses your app, and to do some stuff on his Facebook on his behalf. For example, you could post pictures on user’s Facebook without him explicitly going to the Facebook site and uploading it himself. According to the Facebook API documentation, a successful authentication flow results in your application obtaining a user access token which can then be used to make requests to Facebook’s APIs. After the successful authentication, you will want to save the obtained token to IsolatedStorage to be able to reuse it later, even after the user leaves your application. Therefor, you should use something like FacebookAccess class above and serialize it to IsolatedStorage for later use.

Let’s start by obtaining the token. After you added the Facebook C# SDK to your project, create a page with a Browser control on it.


In the code behind, create the FacebookClient object and a string called ExtendedPermissions.


Facebook SDK enables you to ask for various permissions for you app depending on what it wants to do. You can find detailed information about permissions here:

https://developers.facebook.com/docs/authentication/permissions/

This app uses user_about_me and publish_stream. user_about_me means just basic information about the user, and that’s default. In order to be able to post photos to Facebook, you need to ask for publish_stream permission. The documentation says that it enables your app to post content, comments, and likes to a user’s stream and to the streams of the user’s friends. The next step is to get the log in URL for which you need to give Facebook C# SDK some parameters.


GetLoginUrl method in FacebookClient class creates the login URL which you use for navigating in you BrowserControl added earlier. It takes parameters dictionary as a parameter. Dictionary contains string/object pairs.

  • “client_id” is your app ID
  • “redirect_uri” is where you navigate upon successful login
  • “response_type” is what you get back as a response – a token in this case
  • “display” defines how you display the login screen. Use page.
  • “scope” are permissions you’d like your app to ask for

And then you navigate your BrowserControl to that URL.

Do not use “touch” as “display” parameter. Many places online suggest you do that, because that opens the mobile version of Facebook for authentication. After you do that, you’ll get an error from Facebook saying that:

An error occurred with YOUR APP. Please try again later. API Error Code: 11 API Error Description: This method is deprecated Eror Message: Display=wap dialogs have been deprecated….

If you use “page”, everything works fine.

After that, the BrowserControl will open the Facebook site where the user will be expected to log in. Browser_Navigated event will be raised.

After login, you need to use FacebookOAuthResult object. It is created by parsing the URL using FacebookClient method TryParseOAuthCallbackUrl. If the parsing is not successful, you shouldn’t do anything, but if it is, get the AccessToken property.


If the parsing was successful, you now have the AccessToken. This token is needed for getting the UserID property, too. UserID is needed in some cases and for some URL constructs, so it’s worth getting that one, too. That’s what the LoginSucceded method is for.


Create a new FacebookClient object with the token as a parameter and call the asynchronous GetAsync method with “me?fields=id” parameter. When the async call is completed, you handle the result and create the FacebookAccess object and serialize it using SaveSetting<T> generic method:


Just be careful – any UI stuff you want to do from the GetCompleted event handler needs to go through Dispatcher!

That’s it! You have the token and userid. In the next article, I’ll show you how to upload a photo from your Windows Phone app to Facebook rather simply.

Share the knowledge

31 Comments

  • Reply Eng Dev |

    This code worked with me but web browser is small in size and received success message after I login but when I got to my wall i didn’t see this post i don’t know what is wrong?

  • Reply Eve If |

    Could you please help me?
    I cannot install Facebook c# sdk. It said that “Install-Package : Could not install package ‘Facebook 6.0.24′. You are trying to install this package into a project that targets ‘Silverlight,V
    ersion=v4.0,Profile=WindowsPhone’, but the package does not contain any assembly references that are compatible with that framework. For more in
    formation, contact the package author.”
    Do you have any suggestion?

  • Reply Eve If |

    I have one more question. It’s ask me to add “SerializeHelper” class from this point:

    SerializeHelper.SaveSetting(“FacebookAccess”, new FacebookAccess
    {
    AccessToken = accessToken,
    UserId = id
    });

    I’m really sure that I already add this reference directly; System.Runtime.Serialization.

    Do I need to create “SerializeHelper.cs” and put “SaveSetting” method inside?

  • Reply william |

    sir..you still there? its not working.where should i put?
    var parameters = new Dictionary();
    parameters["client_id"] = FacebookSettings.AppID;
    parameters["redirect_uri"] = “https://www.facebook.com/connect/login_success.html”;
    parameters["response_type"] = “token”;
    parameters["display"] = “page”;
    parameters["scope"] = extendedPermissions;
    BrowserControl.Navigate(_fb.GetLoginUrl(parameters));

    plsss.tnx :D

    • Reply igrali |

      You can put it in the Loaded event handler for the page. What it does is navigates the browser control to the Facebook login URL. This means that you should put it wherever you want to navigate to the Login page.

    • Reply igrali |

      SerializeHelper is a public static class which should be put somewhere in your project. It has a SaveSetting method, which is the last code snippet in my article.

  • Reply william |

    its now working,but this:

    Error 2 ‘AWARE_new.DataContractSerializer’ does not contain a definition for ‘WriteObject’ and no extension method ‘WriteObject’ accepting a first argument of type ‘AWARE_new.DataContractSerializer’ could be found (are you missing a using directive or an assembly reference?) C:UsersHPDocumentsVisual Studio 2010ProjectsAWARE-newAWARE-newSerializeHelper.cs 27 36 AWARE-new

  • Reply gokul |

    hi the extended permissions and browser control does not exists in the current context…
    what ll be the error? pls help me out

  • Reply offers intensive spanish language |

    Hello! Someone in my Myspace group shared this website with us so
    I came to give it a look. I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers!

    Outstanding blog and superb design.

  • Reply Kerem Aytaç |

    Hi, I hope you still follow this article,
    I have a problem with ;
    _fb.TryParseOAuthCallbackUrl

    and

    _fb.GetLoginUrl

    this methods not included in FacebookClient even if I ve downloaded the last version of SDK and also the one you used while writing this article. I don’t know why; others are defined well.

    I really appreciated your article, hope you can help me. Thanks.

  • Reply Dasun Sameera Weerasinghe |

    It was very useful tutorial to me.

    Please don’t include your App Secret in your app(as its says it is something to stay secret.) ,IMHO. This tutorial work perfectly without including the App Secret :)

  • Reply Hogan scarpe |

    I really can’t advise bean bag chairs for kids enough. A causa di my opinion all kids really should have their own bean bag because it just makes life so much easier. So for all you parents grandparents out there I chose to write this guide to assist you choose the right kind of scarpe Hoganbeanbag for your own child. Hogan scarpe http://hogansitoufficiales.webs.com%2

  • Reply Sri Rama Reddy Satti |

    Hi Igor Very Nice Post ..But Now i have one problem

    My Requirement is i need to Log out the facebook from my present App

    i try to delete
    AccessToken and UserId file from Isolated storage succeed in that but my App is directly goingnext page with out opening Facebook log-in

    After that i try to make FacebookOAuthResult = null in another page thats also Not Work …

    can You plese Help me

So, what do you think ?