Using OAuth 2 in WinRT using C#: it has never been easier before

by Leon Cullens 26. september 2012 18:24

WinRT has a built-in authentication client that can be used to authenticate users through Facebook, Twitter, Flickr, Google, etc. This post covers the process of authenticating users with Google.

Architecture

Before I start explaining how the OAuth process work, I'd like to talk about the architecture. While it's possible to write inline OAuth code in the code-behind of your View, I personally find it a nice and clean way to create an 'OAuth2Service' class for this. In this class we can place methods to request tokens, and that kind of stuff. We can then inject this 'service' into our View or ViewModel, or any other class. So for this example I'm going to an IOAuth2Service interface:

interface IOAuth2Service
{
    void RequestToken();
}

After that we create an OAuth2Service class that implements IOAuth2Service:

class OAuth2Service : IOAuth2Service
{
    public async void RequestToken()
    {
            
    }
}

Now that we have implemented the interface, we could also create another implementation of IOAuth2Service that can be used for testing purposes (i.e. unit testing).

OAuth

Now that we have the skeleton in place, we can implement the code needed to perform an actual request.

public async void RequestToken()
{
    const string url = "https://accounts.google.com/o/oauth2/auth?" +
                        "client_id=" + "clientID here" +
                        "&redirect_uri=" + "redirectURI here" +
                        "&response_type=code" +
                        "&scope=" + "scopes here";

    Uri startUri = new Uri(url);
    Uri endUri = new Uri("https://accounts.google.com/o/oauth2/approval?");

    try
    {
        WebAuthenticationResult webAuthenticationResult =
            await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.UseTitle, startUri, endUri);

        if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
        {
            string token = webAuthenticationResult.ResponseData;
            // now you have the token
        }
        else if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
        {
            // do something when the request failed
        }
        else
        {
            // do something when an unknown error occurred
        }
    }
    catch (Exception)
    {
        // do something when an exception occurred
    }
}

That's it. That's everything you need to perform OAuth requests. What happens here: we enter the client ID that can be found in the Google API Console for the API you'd like to use (for instance: youtube), we enter the redirect URI which can be found in the Google API Console as well, and finally we add the scope (actually it can hold multiple scopes). We also specify an endUri that will be used as a callback. After that we pass all the arguments into WebAuthenticationBroker.AuthenticateAsync which executes the request and returns us a response. Note that the method is marked as 'async' because we're executing an async call to the Google API (that's why we use 'await' in front of WebAuthenticationBroker.AuthenticateAsync).

Now you just have to instantiate an OAuth2Service object and call the RequestToken() method. This will launch a nice log on screen from Google:

The Google log on process also works when you're using 2-step verification; it will just take another extra step for the user.

Summary

That's about it. Performing OAuth 2 requests has become extremely easy in WinRT. There's basically one line of code that is needed: the call to AuthenticateAsync in the WebAuthenticationBroker class. This means that using DotNetOpenAuth is no longer needed in WinRT (in fact: it doesn't even work in WinRT when I'm writing this). If you'd like to see examples in other languages (C++, JS, VB.NET) or for other platforms (Facebook, Flickr, Twitter) you can download the examples from Microsoft from this link: http://code.msdn.microsoft.com/windowsapps/Web-Authentication-d0485122.

Tags: , , , ,

Windows 8

Comments (4) -

mark
mark United States
30-12-2012 22:18:10 #

> string token = webAuthenticationResult.ResponseData;
> // now you have the token

Are you certain about this? I get back something that looks like this:

"accounts.google.com/.../approval; which does not actually contain the access token.

Reply

mark
mark United States
31-12-2012 3:29:57 #

that last comment got mangled because my sample response looked like a URI

I forgot to mention: for me, I had to use an endUri of localhost to get the auth token back, using the google approval uri as shown in your code did not work for me

Reply

Matti Härö
Matti Härö Finland
10-1-2013 9:36:23 #

What about the final access token? If I got it right, this example only brings you the request token, which should somehow be used to get the access token, which in turn can be used by subsequent requests. Or is the token returned here the final access token?

Reply

Matti Härö
Matti Härö Finland
11-1-2013 9:46:03 #

It seems that webAuthenticationResult.ResponseData contains the authorization code, which in turn can be used to obtain the access token (which is described at: developers.google.com/.../OAuth2InstalledApp). Using localhost in endUri does not work well in environments that are behind a firewall.

Reply

Pingbacks and trackbacks (2)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

about

Name: Leon Cullens
Country: The Netherlands
Job: Software Engineer / Entrepreneur
Studied: Computer Science 
Main skills: Microsoft technology (Azure, ASP.NET MVC, Windows 8, C#, SQL Server, Entity Framework), software architecture (enterprise architecture, design patterns), Marketing, growth hacking, entrepreneurship

advertisements

my apps