Windows 8: Web Authentication in Metro Apps

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 = "https://www.facebook.com/dialog/oauth";
//Standard redirect uri for desktop/non-web based apps
var redirectUri = "https://www.facebook.com/connect/login_success.html";

            //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
                    break;
                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
                    break;
                default:
                    break;
            }

            return false;

        }

JavaScript Sample:

function launchFacebookWebAuth()
{
	var facebookURL = "https://www.facebook.com/dialog/oauth?client_id=";
	var clientID = "";
	var callbackURL = "https://www.facebook.com/connect/login_success.html";
	facebookURL += clientID + "&redirect_uri=" + encodeURIComponent(callbackURL) +
 "&amp;scope=read_stream&amp;display=popup&amp;response_type=token";

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

		Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync(
			Windows.Security.Authentication.Web.WebAuthenticationOptions.default,
			startURI,
			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:

screenshot_03072013_094732

Related Links

About these ads

31 Responses to Windows 8: Web Authentication in Metro Apps

  1. Pingback: Web Aunthentication Error in Metro Apps « World Wide Code

  2. This is interesting, however, could you please write up one on how to use it with Google Plus. Thanks.

    • 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.

  3. 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).

  4. Adeel Khan says:

    After authentication and login process completed then how can we show our user information in metro style page… using Javascript sample code

    • 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.

  5. Jaunty Ibbi says:

    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

  6. Adeel Khan says:

    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?

    • 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…

  7. mirolfm says:

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

  8. Does this work with OAuth 1.0a?
    Tumblr API uses that version of the protocol. http://www.tumblr.com/docs/en/api/v2#auth

  9. 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.

  10. Pingback: 70-481 vizsgafelkészítő anyagok « Balássy György szakmai blogja

  11. Pingback: Balássy György szakmai blogja

  12. Pingback: 70-481 exam preparation materials « Codes from the field

  13. Pingback: Study Notes for 70-484 Exam: Essentials of Developing Windows Metro style Apps using C# « Salem's Blog

  14. awesome says:

    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).

    • 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

      • awesome says:

        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.

      • The web services must be sending some sort of authentication info in the response. If possible you can capture that and send it with the next requests.

  15. Pingback: Giorgio Lasala » Study Notes for 70-484 Exam: Essentials of Developing Windows Metro style Apps using C#

  16. Gopal Rander says:

    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..

    • 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.
      Thanks,
      Shubhan

Share your thoughts

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: