Tuesday, May 15, 2012

How to determine the username of the logged on user in Windows 8 Metro Style apps

There are 2 options available here, depending on what you would like to achieve.

If it's simply to authenticate a user, you would want to use the Windows.Security.Authentication.Web.WebAuthenticationBroker, and one or more OAuth2.0 identity services like Facebook or Windows Live. There are very good samples available on using these. Start with MSDN

If you need to do authorization or log a user in using a web service, you may need to know the logged in user's username. This can be found in the UserInformation object, like so:

Windows.System.UserProfile.UserInformation.getPrincipalNameAsync().then(function (result)
{
    Debug.writeln(result);
});
 
 
You can then look at using the various web services and APIs provided by your chosen identity provider. One option is to provide your own web service, which may perform any further required logging in for the user, if Kerberos is not working for you.

Another option when having to ask the user for credentials is to use the CredentialPicker object. Here's an example of how to use it:

var credentialPickerResults;
var credentialPickerOptions = new Windows.Security.Credentials.UI.CredentialPickerOptions();
credentialPickerOptions.targetName = "My App";
credentialPickerOptions.caption = "My App";
credentialPickerOptions.message = "Sign in to My App";
credentialPickerOptions.authenticationProtocol = Windows.Security.Credentials.UI.AuthenticationProtocol.ntlm;
credentialPickerOptions.alwaysDisplayDialog = false;
var credentialPicker = Windows.Security.Credentials.UI.CredentialPicker;
credentialPicker.pickAsync(credentialPickerOptions).done(
function complete(result) {
    console.log("pickAsync complete: username = " + result.credentialUserName + ", password = " + result.credentialPassword + " errorCode = " + result.errorCode);
    credentialPickerResults = result;
},
function error(e) {
    console.log("pickAsync error: " + e.message);
});
 
 
The result object will contain the credentials the user specified. No authentication is performed on these credentials.

No comments:

Post a Comment