How to login to Facebook from Windows 8 Metro using HTML 5

Facebook login with OAuth 2.0 is baked into WinRT. You can't actually use the samples on the Facebook Developer postal. So, from an application, try these steps:

  • Start with a Navigation template, or add an appbar to your app
  • Add a login button to your appbar. Should be in the default.html page in the root directory
<button id="loginButton" class="win-command" style="float: right;">
  <span class="win-commandicon win-large login"></span><span class="win-label">login</span>
</button>
  • In the related JS file, add an event handler for the button. This collects the required values for the OAuth call and then calls Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync, where all the magic happens. The scope parameter in the querystring is how you get extended permissions.
function loginButtonClick() {
        var facebookURL = "https://www.facebook.com/dialog/oauth?client_id=";
        var callbackURL = "https://www.facebook.com/connect/login_success.html";
        var clientID = "12434567890987654321";
        facebookURL += clientID + "&scope=publish_stream,publish_checkins,publish_actions,share_item&redirect_uri=" + encodeURIComponent(callbackURL) + "&scope=read_stream&display=popup&response_type=token";

        var startURI = new Windows.Foundation.Uri(facebookURL);
        var endURI = new Windows.Foundation.Uri(callbackURL);

        try {

            Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync(
								Windows.Security.Authentication.Web.WebAuthenticationOptions.default,
								startURI,
								endURI).then(callbackFacebookWebAuth, callbackFacebookWebAuthError);
        } catch (err) {
            console.log(err.message);
            return;
        }
    }
  • The promise has callbacks for completion and error. You can swallow the error, but on completion, make sure to keep the token.
function callbackFacebookWebAuth(result) {
        var url = result.responseData;
        var querystring = {};

        url.replace(
            new RegExp("([^?=&]+)(=([^&]*))?", "g"),
            function ($0, $1, $2, $3) {
            querystring[$1] = $3; }
        );
        facebookToken = querystring["access_token"];

    }
 
And that's about it. The token in facebookToken is what is used to call the open graph. For instance, to get my data, I could call the graph like this: 
 
facebookButton.addEventListener('click', function () {
	var buildUrl = "https://graph.facebook.com/billsempf/feed?access_token=" + PA.facebookToken;
	WinJS.xhr({ type: "GET", url: buildUrl }).then(parseProfileJson, promiseError);
    });

Pingbacks and trackbacks (2)+

Comments are closed
Mastodon