This blog post was authored by Taqi Jaffri, a senior program manager on the Windows Phone team.
– Adam
Facebook users increasingly rely on their Facebook identity to access apps, play games with friends, share playlists or comment in a forum. As a developer, you may also rely on Facebook Login to tap into the Facebook social graph to enhance your app’s experience, enable new scenarios and open up the app to new customers, resulting in better revenue opportunities.
Today, we are excited to release support for Facebook Login on Windows and Windows Phone 8. See the announcement, and check out the documentation on facebooksdk.net, or on the Facebook Developers site.
In this post, I will walk you through the simple steps of setting up your Windows Phone 8 app to integrate seamlessly with Facebook Login. Not only does Facebook Login reduce the amount of code you need to write for your app to log in to Facebook, it also improves the user experience by not requiring the user to log in again if they are already logged in to the Facebook app.
Important note: This feature is being rolled out as part of the Facebook Beta app (version 5.2). We are looking for feedback from developers via the comments section at the end of this post, as well as the Facebook for Windows Phone uservoice forum. Because the Facebook Beta app is not yet widely used by Windows Phone users (and requires a special link to install), we ask you to hold off on releasing apps that use this feature until we update the broadly distributed Facebook app.
This topic contains the following sections:
- User experience
- Configuring your app for Facebook Login
- Initiate login
- Handle the login response
- Securely storing access tokens
1) User experience
If the user is already logged in to the Facebook Beta app, then the Facebook Login experience is meant to be simple, fast, and delightful. Your app initiates login and the Facebook app takes care of showing any authorization screens. On completion, your app is called back with the access token and can interact with Facebook. The following screenshots illustrate how this looks:
If the user is not logged in to the Facebook Beta app, they will be prompted for their user name and password the first time the app is launched. In addition, if a version of the Facebook app that supports Login is not installed on the phone the user will be prompted to download the app from the store.
Important note: The Facebook Beta app does not appear in Store search results, so the feature that prompts the user to install the Facebook app from the store will not work completely till we exit beta and update the broadly distributed Facebook app to support Facebook Login.
2) Configuring your app for Facebook Login
2.1 App manifest
Configure your app’s manifest file (WMAppManifest.xml) to register a custom uri scheme that is of the form msft-{ProductID}, where {ProductID} is your app’s product ID (without dashes). It should look like this:
<Protocol Name=“msft-43245dd584d84cde837aa19a4a2e3914“ NavUriFragment=“encodedLaunchUri=%s“ TaskID=“_default“ />
Important note: If you have not yet submitted your app to the Windows Phone Store, be aware that the product ID used during development is a randomly assigned placeholder. After your app has been certified, it has a different product ID. In this case, submit your app first to get a product ID assigned, but select the Manual publish option to ensure that you don’t release an app that is not set up correctly on the Facebook Developers site. Once you have your final product ID, make sure you update your WMAppManifest.xml to Use the final product ID rather than the randomly assigned placeholder. See here for more information about the submission process.
2.2 Install NuGet packages
Install the latest NuGet packages for the Facebook SDK for .NET. There is a great tutorial for the SDK on that site that shows you how to add these packages. See the “Getting Started on the Application” section here.
2.3 Update your app on the Facebook Developers site
You also need to enter some information about your app in the Facebook Developers site, for example, identify your application ID in the Windows Phone Store so Facebook can ensure only your app gets access tokens granted by users to your Facebook app.
1. Go to http://developers.facebook.com and log in.
2. Click Apps in the top navigation bar.
3. Select your Facebook app in the left pane (or create a new one if you are starting from scratch).
4. Click edit settings.
5. Under select how your application integrates with Facebook, find the section for Windows App and expand it.
6. Enter exactly the same product ID you entered in your WMAppManifest.xml file, the {ProductID} portion (without dashes) of your msft-{ProductID} custom URI scheme.
Important note: See earlier note on how the product ID is different during development and after submission. This is crucial if you have not yet been assigned a product ID.
Here’s an example of how the Facebook Developers site looks when set up.
2.4 Set up your development environment
If you are developing on a phone, please make sure you have the latest version of the Facebook Beta app installed.
However, if you are developing on an emulator you will not be able to install the Facebook Beta app. To help enable emulator development, we are providing a login simulator app as part of the attached code sample that you can deploy to your emulator and use for development and testing. This is a very simple app that does not actually connect to Facebook, but simply echoes back values that you set up. This way, you can test success and failure paths easily.
Before you deploy the simulator, you need to provide an access token to use in success cases (you will see a build failure in MainPage.xaml.cs until you do). To get an access token, visit the Graph Explorer Tool on the Facebook Developers site and click Get Access Token.
3) Initiate Login
Using the Facebook.Client package, make a call to Facebook.Client.FacebookSessionClient.LoginWithApp(). This method has different overloads, which require the following parameters:
· The set of permissions your app is requesting
· A custom state parameter, which is echoed back to your application upon login completion. This can be used to redirect the user back to the original page within your application that initiated login, or any other app specific logic.
A full example would be:
FacebookSessionClient fb = new FacebookSessionClient(AppId);
fb.LoginWithApp(“basic_info,publish_actions,read_stream”, “custom_state_string”);
4) Handle the login response
The response comes back from Facebook as a custom URI scheme invocation. This URI can be passed into the AppAuthenticationHelper.IsFacebookLoginResponse() method to determine whether this is a normal app invocation or a Facebook login response. There is also a helpful FacebookSession.ParseQueryString method that you can use to easily parse the response and determine if it was successful.
An example of this can be found in the UriMapper of the attached code sample:
/// <summary>
/// Maps a deep link Uri to a navigation within this application
/// </summary>
/// <param name=”uri”>Deep link Uri to map</param>
/// <returns>Navigation Uri within this app</returns>
public override Uri MapUri(Uri uri)
{
// if URI is a facebook login response, handle the deep link (once per invocation)
if (AppAuthenticationHelper.IsFacebookLoginResponse(uri))
{
FacebookSession session = new FacebookSession();
try
{
session.ParseQueryString(HttpUtility.UrlDecode(uri.ToString()));
// Handle success case
// do something with the custom state parameter
if (session.State != “custom_state_string”)
{
MessageBox.Show(“Unexpected state: “ + session.State);
}
else
{
// save the token and continue (token is retrieved and used when the app
// is launched)
SessionStorage.Save(session);
}
}
catch (Facebook.FacebookOAuthException exc)
{
if (!this.facebookLoginHandled)
{
// Handle error case
MessageBox.Show(“Not signed in: “ + exc.Message);
this.facebookLoginHandled = true;
}
}
return new Uri(“/MainPage.xaml”, UriKind.Relative);
}
// by default, navigate to the requested uri
return uri;
}
5) Securely storing access tokens
The SessionStorage implementation in the attached sample uses System.Security.Cryptography.ProtectedData to encrypt the sensitive information as outlined here. We recommend that you use a similar strategy to handle your access tokens, instead of saving them in your app isolated storage without encryption.
6) Conclusion
We look forward to hearing your feedback about Facebook login on Windows Phone. The attached code sample should get you started on integrating this useful feature within your own application. This is a beta release and we need your help to make sure it is rock solid before rolling out broadly, so please do reach out via the comments forum below, or our uservoice forum, if you have any feedback.
Get the code sample here.