You may have used  OAuth 2.0 protocol for authentication and authorization in your Desktop or web based apps. Now, you would like to build a Metro app for Windows 8 which requires web authentication.

For this purpose, there exists a Web Authentication WinRT API do perform the required task.

The web authentication can be performed using C# as well as JavaScript. I am providing some code snippets for the authentication process. You may want to add more steps and error handling to these samples.

Update: Since writing this post, many things have changed. We now have a better support using VS 2012 and Windows 8 Pro for the WinRT API(s) and asynchronous programming. I have updated the C# sample to reflect these changes. I guess, the same changes would apply to the JavaScript version as well, I din’t have time to update that sample. 🙂

C# Sample:

private async Task _login()

            //Facebook Authentication Uri
var facebookUri = "";
//Standard redirect uri for desktop/non-web based apps
var redirectUri = "";

            //Place your app client id here
var clientId = APPID;
            //The type of token that can be requested
var responseType = "token";
            //The Facebook access permissions.
            var scope = "manage_notifications,read_friendlists,read_stream";
            //Response pattern
var pattern = string.Format("{0}#access_token={1}&expires_in={2}", redirectUri, "(?<access_token>.+)", "(?<expires_in>.+)");

            //Step 1. Create a Request and Callback Uri for the Authentication operation
var requestUri = new Uri(string.Format("{0}?client_id={1}&redirect_uri={2}&response_type={3}&scope={4}&display=popup",
facebookUri, clientId, redirectUri, responseType, scope), UriKind.RelativeOrAbsolute);
var callbackUri = new Uri(redirectUri, UriKind.RelativeOrAbsolute);

//Step 2. Initialize a Authentication operation using WebAuthenticationBroker
var asyncOperation = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, requestUri, callbackUri);

            switch (asyncOperation.ResponseStatus)
                case WebAuthenticationStatus.ErrorHttp:

                    //An HTTP error like a 404 was returned
                case WebAuthenticationStatus.Success:
                    var match = Regex.Match(asyncOperation.ResponseData, pattern);
                    var access_token = match.Groups["access_token"];
                    var expires_in = match.Groups["expires_in"];
                    //Use access_token and expires_in for further API Calls
AccessToken = access_token.Value;
TokenExpiry = DateTime.Now.AddSeconds(double.Parse(expires_in.Value));
                    return true;

                case WebAuthenticationStatus.UserCancel:
AccessToken = null;
TokenExpiry = DateTime.MinValue;
                    //The User selected to cancel the Authentication process

            return false;


JavaScript Sample:

function launchFacebookWebAuth()
	var facebookURL = "";
	var clientID = "";
	var callbackURL = "";
	facebookURL += clientID + "&redirect_uri=" + encodeURIComponent(callbackURL) +

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

			endURI).then(callbackFacebookWebAuth, callbackFacebookWebAuthError);
	catch (err) {	/*Error launching WebAuth"*/	return;	}

function callbackFacebookWebAuth(result)
	var FacebookReturnedToken = result.responseData;
	var response = "Status returned by WebAuth broker: " + result.responseStatus + "\r\n";
	if(result.responseStatus == 2)
		response += "Error returned: "+ result.responseErrorDetail +"\r\n";

function callbackFacebookWebAuthError(err)
	var error = "Error returned by WebAuth broker. Error Number: " + err.number + " Error Message: " + err.message + "\r\n";

When the authentication process ins initiated, the WinRt platform displays a web-based authentication popup prompting you to enter credentials.

The popup looks something similar to this one:


Related Links


33 thoughts on “Windows 8: Web Authentication in Metro Apps

    1. Hey William, Web auth in Windows 8 is not tied to a provider like Facebook or Google. It uses the Request and callback uri to perform the required task. So if you want to use Google then you would require to read on google apis for authentication.
      Here’s a link: Using OAuth 2.0 to Access Google APIs.

      There is also a demo app from MSDN which allows to connect using OAuth providers like Facebook, Flickr, Google, Live, and Twitter. (I have’nt tested this app though)

      I would be writing a detailed code snippet on using Google Authentication in a few days time.

  1. Your C# sample can be simplified if you used the new C# ‘await’ feauture. Instead of setting the Completed handler you can write ‘var webResult = await auth.Start()’ and then the rest of the code will be turned into a continuation by the compiler (so you will just need the second switch statement).

    1. You only request for authentication when you want to show data that is restricted.

      After the authentication is complete, then in the case of say Facebook, you now have access to the Facebook API(s) using which you can show the content for example the user’s friend list.

  2. hey shuban thanks for the info, but kindly clear one thing that is u say dat for showing user’s friendlist we just have to request for authentication.. I have the same scenario as Adeel Khan mentioned earlier in his comment, but when I authenticate the user, nothing happens however I have successfully authentication process. Kindly suggest me what to do. n can u plz share the API for retrieving the friendlist of the user who is signed in

    1. This is specific to Facebook, After authentication process you will get a access token. Please store this token for further request. As you mentioned, Windows 8 will not notify you about the auth process completion, you will have to retrieve the token from the response. Using that token you can request Facebook the fireinds list of the logged in user using For more info on Facebook API(s) see Graph API. Hope this helps.

  3. thanks shubhan I have got the json object that contains the user information, but how can i show the contents of this file on my page? i mean when the json object is retrieved, how to show the data contains in the json object?

    1. Hey Adeel, How to show the object really depends on you and the app that you are developing. For example you can have a section in your page showing the users’ picture and name. In that case, you can just assign the say text block or div with the value from the json object like this:

      document.getElementById('txtUserName').value = userObject.Name;

      For starters, I suggest you take a look at Metro style apps: Web Authentication. A lot more samples are available on MSDN Dev center if you search for them.

      Does this solve your problem? Keep me posted…

  4. does your c# example also work in, or are you using any specific c# functions which are not available in
    in general, do you know any limitations by writing a metro app for windows 8 in compared to c#?
    thank you,

      1. I tried and it worked. I used the web authentication broker example that comes in the Sample Pack. Tumblr authentication works the same as the Twitter example that is in there (

        The only thing you must be aware of is that you have to use the same callback url you specified in the app on Tumblr when calling WebAuthenticationBroker.AuthenticateAsync method. Otherwise the “Connecting to service” window will take the user to the Callback of the app ignoring what you used when calling the broker and the window won’t be closed. Since that window can be closed only with the back button, you ended up with a userCanceled response status or something similar.

  5. Has anyone been able to get this working successfully with the Google Api.
    By using the sample I was able to retrieve the token from the Google Service, but Im not able to make requests to the google Api’s.
    Google’s documentations are very confusing.
    If someone goes have a Google example it will be highly appreciated.

  6. Is it possible to do this with AD authentication w/o oAuth? Looking to build enterprise authentication into an app that is not joined to a doamin (so I can’t use the enterprise authentication capability in the manifest).

    1. Since you said that the app is not in the domain, how do you plan to access the active directory services? Are they accessible out side the domain?

      Take a look at Directory Services (Windows) if it meets your requirements.

      Another option could be to host a page with Active directory auth on the AD network and access that page inside your app. If the response says the user is authenticated, you may use the details in you app.

      Hope this helps

      1. Well they are public facing services/web sites that authenticate to AD on the backed. Looking for a way to authenticate every https the app makes rather than with each request send credentials from the password vault.

  7. Hey… I am able to authenticate my app.. but it again asks for authentication, once i close and restart the app. Isn’t there a way for maintaining a session as in web Browsers. Please help me out in that case..

    1. Hey Gopal, The Web Authentication broker will not store the authentication for you. This auto authentication is supported for providers which allow “Single sign-on” support. If you are developing a Facebook app, Facebook does not support SSO. You will have to save the response retrieved from the authentication broker inside your app.

      E.g. In case of Facebook, you will have to save the token received in the app and validate the token the next time you open the app. If not valid then ask for authentication again, otherwise proceed ahead with the normal flow of the app post authentication.

      Hope this helps.

  8. Hi Shubhan nice tutorial for Facebook integration. I want to ask is it possible to use Windows 8 Facebook app for login purpose just like we can use Facebook Android App to build login flow in Android App. In android when you want to login user with Facebook to obtain access_token etc. You can login using Android Facebook App is it possible with windows 8

Share your thoughts

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s