Sign into Windows Phone 8 apps with Facebook Login

Sign into Windows Phone 8 apps with Facebook Login

  • Comments 11
  • Likes

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:

  1. User experience
  2. Configuring your app for Facebook Login
  3. Initiate login
  4. Handle the login response
  5. 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:

facebook first step

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.

image

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.

image

 

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.

11 Comments
You must be logged in to comment. Sign in or Join Now
  • Apologize for not reading all the documentation. Apparently, it is a bug and workaround is mentioned at developers.facebook.com/.../login-for-windows-phone

    NOTE: There is currently a bug which will prevent Facebook Login for Windows Phone from working if you have any entries in the "Valid OAuth redirect URIs" field in the Advanced section of your app settings. This can be worked around by adding "m.facebook.com/.../ms" in this field.

    Making the above update, resolve the issue.

  • It works well with on emulator. But on phone after it calls the Facebook Beta, it gives an error 'Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the Apps Settings. It must match the Website URL or Canvas URL, or the domain must b e a subdomain of one of the Apps Domains.'

    Looks like something App configuration is facebook is incorrect. What else needs to be added other than Windows Phone Store Id?

  • my friend'zs mom makes $84 every hour on the computer. She has been out of a job for 9 months but last month her pay was $14824 just working on the computer for a few hours. hop over to this sit www.bay92.com

  • carl_w
    0 Posts

    I think that this is great and clearly long overdue.

    One observation from my brief testing of it:

    I have never used iOS or Android for this sort of thing, so I'm not sure what would be considered normal, but I think that something needs to be done about the startup time of the facebook app if this is going to be useful.

  • Regarding my previous question: I've asked around and apparently right after uploading your XAP to the developer portal and saving (but not submitting for certification!), the app's Details page already lists your app's Product ID. So you can quickly add that to your app and upload again. No need to submit the non-working app. If that's indeed the preferred way for this situation, I would advise you to update this blog to reflect it.

  • Section 2.1 puzzles me. I understand the need for the app's real Product ID in order for this to work. But the workflow for a new app for which we haven't yet got a Product ID seems broken. It looks like there are two ways to handle this:

    1) Submit your app with an invalid Product ID, making sure to set manual publication. Once the app is approved, you've got the real Product ID and you can update the app and submit the update.

    2) Submit your app without the Facebook features. Once it's approved and you've got the Product ID, we update the app to include the Facebook featurs.

    Both seem problematic: in the first scenario I don't see how the app can pass certification, since the Facebook stuff is clearly broken by using that invalid Product ID. Or does the cert team ignore this issue. Should we add a remark to the submission, describing why Facebook doesn't work and that we're going to update it later?

    The second scenario may be valid for many apps, unless the Facebook feature is an absolute requirement for you app to work at all. Of course you could add Facebook login to the app itself. But that's a lot of extra work that we're trying to skip by using the new method.

    Any comments? Am I overthinking this?

  • Great! Hope to see Candy Crush Saga on Windows Phone soon!

  • gaurav
    10 Posts

    Great news. Please add Twitter support in future. Just a little concern about security, what if an app registers a uri scheme using other app's product id. Is it possible?

  • @theRTC It's simple. You've got the access token from this method. Just pass on that access token to the Azure log in API. It's quite similar to the method which uses Microsoft Account single sign on.

    @fahdriyami: That's exactly what this new API does!

  • theRTC
    0 Posts

    This is so fantastic! I have been hoping to see this arrive on WP8 at some point, so glad to see it finally in action.

    How does/can this integrate with Azure login?

  • What would be really useful is if Windows Phone apps could tap into the Facebook profile already connected to our phones. That way we wouldn't have to sign into facebook on every, single, app that uses the service.