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:


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

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:

public class FacebookSettings  
        public static string AppID = "YOUR APPID"
        public static string AppSecret = "YOUR APPSECRET"

public class FacebookAccess  
        public string AccessToken { get; set; }
        public string UserId { get; set; }

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.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">  
    <phone:WebBrowser Name="BrowserControl" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" IsScriptEnabled="True" Nhttp://igrali.azurewebsites.net/wp-admin/post.php?post=496&action=edit#avigated="Browser_Navigated" Loaded="Browser_Loaded"/>

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

private const string ExtendedPermissions = "user_about_me,publish_stream";  
private readonly FacebookClient _fb = new FacebookClient();

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:


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.

var parameters = new Dictionary<string, object>();  
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;  

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.

private void Browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)  
    FacebookOAuthResult oauthResult;
    if (!_fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))

    if (oauthResult.IsSuccess)
        var accessToken = oauthResult.AccessToken;

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.

private void LoginSucceded(string accessToken)  
    var fb = new FacebookClient(accessToken);

    fb.GetCompleted += (o, e) =>
        if (e.Error != null)
            Dispatcher.BeginInvoke(() => MessageBox.Show(e.Error.Message));

        var result = (IDictionary<string, object>)e.GetResultData();
        var id = (string)result["id"];

        SerializeHelper.SaveSetting<FacebookAccess>("FacebookAccess", new FacebookAccess
            AccessToken = accessToken,
            UserId = id


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:

public static void SaveSetting<T>(string fileName, T dataToSave)  
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            using (var stream = store.CreateFile(fileName))
                var serializer = new DataContractSerializer(typeof(T));
                serializer.WriteObject(stream, dataToSave);
        catch (Exception e)

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.

About Igor Ralic

Software engineer at Microsoft. Running for Office. Passionate about making an impact with great apps & services. Stays close to coffee and away from coriander. Opinions expressed here are my own.