WinRT has built-in support for the “browser control/redirect” sign-in mechanism that is used in OAuth2 implicit flow. The API for that is called the WebAuthenticationBroker and using it has some advantages, e.g.
- Give the user a consistent interface for entering credentials (though I don’t know how hard it would be to spoof such an interface).
- The app itself never sees the password, just the token that gets returned by the handshake.
- The container that does the web interaction has separate cookie management and integrates with the Windows 8 capabilities sandbox. This includes capabilities like network access restrictions and sending Windows credentials.
Setting up a resource/client for WebAuthenticationBroker works exactly the same as for a JavaScript client – see Christian’s post.
In your Windows Store app, you then construct a request URL, e.g.:
var startUri = new Uri(
string.Format(
“{0}?client_id={1}&scope={2}&redirect_uri={3}&response_type=token”,
endpoint.AbsoluteUri,
Uri.EscapeDataString(clientId),
Uri.EscapeDataString(scope),
Uri.EscapeDataString(callbackUri.AbsoluteUri)));
You also have to tell the broker how to detect when the handshake is done. There are multiple ways to do this, either wait for a specific redirect URI, wait for a POST or looking for something in the title bar. The most common option would be the redirect URI.
If you don’t specify a specific redirect URI, the broker is looking for the app specific App-Id (in the ms-app:// format). You can query that value by calling WebAuthenticationBroker.GetCurrentApplicationCallbackUri().
You don’t have to use the ms-app:// ID, but this allow the broker container to maintain a cookie with the token service, which might be useful.
So in the end, you can invoke the broker e.g. like this:
var result = await WebAuthenticationBroker.AuthenticateAsync(
WebAuthenticationOptions.None,
startUri);
This will render the sign-in and consent UI:
After that, the result variable will contain the redirect URI including the query string/hash fragment – and you can then retrieve the access token or authorization code from there.
In addition you can combine that with WinRT’s PasswordVault to securely store the access token – and maybe even sync it across multiple devices.
You can find the complete sample here.
HTH
Filed under: IdentityModel, IdentityServer, OAuth, WebAPI
