This blog post is an addendum to the article, Build a Xamarin App with Authentication and Offline Support, to be published in MSDN Magazine, September 2015. I’ll update this post with a link once the article is available. Part 1, Cloud-Connected Mobile Apps – Create a Web Service with Azure Web Apps and WebJobs, which discusses the backend of the project, is available now.

The OAuth credential flow in Altostratus is as follows, using Facebook as an example. Once the user is

  1. The mobile client app displays a web browser control and navigates to a known URL on the backend.
  2. The backend redirects to the Facebook sign-in page where the user signs in with his or her Facebook credentials.
  3. The backend does sends requests to Facebook to retrieve an access token.
  4. The client app redirects the browser back to the backend’s endpoint. The redirect URL includes the access token in the fragment hash.
  5. The client app has been waiting for the redirect. At this point, it parses the access token from the URL fragment.
  6. If the user is not yet registered with the backend, the client app sends a registration request to the backend. The backend creates a database entry for the user and issues a second access token. This step only happens on the first login.
  7. Once the user is registered, the client app includes the access token to make authenticated requests.

Put graphically:

AltoStratus_OAuth_Flow


At first glance, and in reading different documentation (including the first edition of my book–I’m now working on the second), it seems like the Web Authentication Broker in WinRT is meant for a few key OAuth identity providers like Twitter and Facebook. That was at least my initial impression, but it’s mistaken.

The Web Authentication Broker is actually meant for any service that provides authentication. It’s primary purpose is to avoid collecting credentials in client apps and then transmitting those credentials over HTTP requests. Ideally, if apps always protected those credentials with appropriate encryption and using SSL over HTTP, and avoided storing any credentials on the client in plain text, then the web auth broker might not be necessary. But apps usually aren’t written that securely, so it’s best to authenticate directly with the service and have that service provide the app with an access token of some kind.

This is what the Web Authentication Broker is meant for. By invoking it–providing with your service’s authentication URI–an overlay appears above your app and displays the service’s page directly. This means that any and all information that the user enters at this point is going securely to the service and not to the app. The service, as described in the guidance for web auth broker providers, can provide whatever series of pages it needs for its own workflow, but at the end of it all it responds with a token that the client can use in subsequent calls.

So if your app in any way needs to collect credentials to authenticate with a service, consider using the web auth broker for this purpose and create the necessary pages on your service for this purpose. With just a little work, you can craft those pages so they look great within the broker window and integrate nicely into your app experience.


The other day I answered a question on stack overflow regarding the WinRT credential picker, and oddly enough, I got almost exactly the same question from another person.

Let me preface all this with the note that the CredentialPicker was designed for enterprise authentication scenarios, as it has a built-in capability to save credentials elsewhere if you instruct it to (see the chart on page 659 of my book PDF. For other scenarios, you can still use the picker if you want, or you might just implement your own controls. Alternately, if you’re authenticating with a service of your own, you can do this with the Web Authentication Broker and keep the credentials on the server. I have to admit that my impression of the Web Auth Broker has been that it’s for use with OAuth providers, but it’s not limited to that: it can be used with any site that has a page to authenticate and respond with an access token that the client can then store (in the credential locker).

Anyway, back to the credential picker. The question is one of saving credentials that a user enters in the Windows.Security.Credentials.UI.CredentialPicker, which comes back as a CredentialPickerResults object from the pickAsync method.

This results object has two properties, credentialUserName and credentialPassword, that are returned in plain text for certain input protocols (Basic and Digest). You can do with these whatever you want, but the important thing is that if you persist them to storage, be sure to use the Credential Locker–do not save them as plain text. A key benefit of the Credential Locker is that those credentials will roam to the user’s other devices, where your app can retrieve them even on first run and not have to bother the user again. (Refer to the Credential Locker sample for usage of the API.)

Note that if the input protocol for your device is something other than Basic or Digest, the credentialPassword comes back encrypted. The default protocol, Negotiate, could go either way (on my machine, which is domain-joined, the protocol is probably enforced through group policy so the password is encrypted). So if you need plain-text passwords back from the credential picker, use the variant of pickAsync that allows you to specify options, and set the the input protocol to Windows.Security.Credentials.UI.AuthenticationProtocol.basic. You can try this is scenario 3 of the Credential Picker sample.

Note also that if you’re transmitting such credentials over the Internet, always use https:// or be sure to encrypt that information on a unsecured URI. Never, ever transmit plain text credentials!

Anyway, the username and password fields from the CredentialPickerResults is enough to authenticate with whatever service you need, but the second question is how to get those credentials back into the credential picker at a later time? The picker’s options don’t support plain text username and password field as input. The picker does, however, accept a previousCredential object, which is basically a byte array (a buffer object) that contains a scramble of those credentials.

This buffer is what comes back from pickAsync in the CredentialPickerResults.credential property. During the same app session, you can simply store this value in memory and drop it into previousCredential for the next call to pickAsync.

More likely, though, you’ll want to save that buffer in appdata for use in later sessions. To do this you use the methods in Windows.Storage.FileIO, namely writeBufferAsync and readBufferAsync. Here’s some code I added to the completed handler for pickAsync in scenario 3 of the Credential Picker sample:

//results.credential will be null if the user cancels
if (results.credential != null) {
    //Having retrieved a credential, write the opaque buffer to a file
    var option = Windows.Storage.CreationCollisionOption.replaceExisting;
    Windows.Storage.ApplicationData.current.localFolder.createFileAsync(“credbuffer.dat”, option).then(function (file) {
        return Windows.Storage.FileIO.writeBufferAsync(file, results.credential);
    }).done(function () {
        //No results for this operation
        console.log(“credbuffer.dat written.”);
    }, function (e) {
console.log(“Could not create credbuffer.dat file.”);
    });
}

Then I created a new function to load that credential, if possible. This is called on the Launch button click instead of launchCredPicker in the sample:

//In the page ready method:
document.getElementById(“button1”).addEventListener(“click”, readPrevCredentialAndLaunch, false);

//Added
function readPrevCredentialAndLaunch() {
    Windows.Storage.ApplicationData.current.localFolder.getFileAsync(“credbuffer.dat”).then(function (file) {
        return Windows.Storage.FileIO.readBufferAsync(file);
    }).done(function (buffer) {
        console.log(“Read from credbuffer.dat”);
launchCredPicker(buffer);
}, function (e) {
console.log(“Could not reopen credbuffer.dat; launching default”);
        launchCredPicker(null);
    });
}

//Modified to take a buffer
function launchCredPicker(prevCredBuffer) {
    try {
       var options = new Windows.Security.Credentials.UI.CredentialPickerOptions();
       //Other options omitted

       if (prevCredBuffer != null) {
           options.previousCredential = prevCredBuffer;
       }

   //…

That’s it. I put the modified JS sample on http://www.kraigbrockschmidt.com/src/CredentialPickerJS_modified.zip.