Geeks With Blogs
Joe Mayo

Last July, I blogged about how to do OAuth in Windows 8 with LINQ to Twitter:

A the time, that worked well, but was still not an optimal solution. It required setting up a page to handle a WebBrowser control, navigating to that page, authorizing, and then asked the user to copy a PIN into a text box to complete the dance. You still have to do that with desktop and Windows Phone apps, but not with Windows 8 apps anymore.

LINQ to Twitter now has a new authorizer, called WinRtAuthorizer. It’s based on the WebAuthenticationBroker and allows a seamless integration of the OAuth workflow with your app. You don’t need PIN numbers anymore. This post shows how to use WinRtAuthorizer to perform OAuth authentication with LINQ to Twitter. There are essentially two steps: instantiate WinRtAuthorizer and Authorize.

Instantiating WinRtAuthorizer

WinRtAuthorizer is much like other authorizers with LINQ to Twitter. The main difference is that I’ve included various credential stores for managing credentials. Here’s an example that instantiates a new WinRtAuthorizer that stores credentials on your local machine.

            var auth = new WinRtAuthorizer
                Credentials = new LocalDataCredentials
                    ConsumerKey = "",
                    ConsumerSecret = ""
                UseCompression = true,
                Callback = new Uri("")

The code above instantiates a WinRtAuthorizer, using object initialization syntax. I’ll discuss the Credentials property in a moment, but want to quickly point out that setting UseCompression to true will cause the underlying HTTP request to be sent to Twitter with GZip compression. The underlying authentication code expects a Callback Uri, which isn’t used in this case, but is still required. You can use the callback address that you specified as the Web callback when setting up your application and received credentials at the Twitter developer’s site.

This particular example uses LocalDataCredentials to store credentials in local data. LocalDataCredentials is just one way to store your credentials and you can create your own custom class to save credentials by implementing IOAuthCredentials, a LINQ to Twitter type, yourself. In particular, I’ve created the following hierarchy of IOAuthCredentials types to support Windows 8:


WinRtCredentials is a base class that supports a set of credential types unique to Windows 8. LocalDataCredentials stores credentials on the local machine, meaning that they persist for the authenticating user, but only on the machine where the authentication took place. RoamingDataCredentials uses the Windows 8 roaming data feature that persists credentials in the cloud, allowing the user to authenticate only one time and be authenticated on any other machine without needing to re-authenticate. TemporaryDataCredentials exist for at least the lifetime of the current session, but aren’t guaranteed to be available after that.


On the surface, performing the authorization part is dirt simple, but there are nuances that you might be curious about or eventually encounter in practice. The following code checks to see if the user is already authorized and, if not, performs the authorization:

            if (auth != null && !auth.IsAuthorized)
                await auth.AuthorizeAsync();

The first part of the code above checks the IsAuthorized property. Sometimes, this is a little confusing because the purpose of this is to verify whether the user’s authorization credentials are loaded into the IOAuthCredentials type instance of the authorizer. The four credentials are the ConsumerKey and ConsumerSecret that Twitter gives you as part of your application, and the OAuthToken and AccessToken that the Twitter API gives your code after the authentication process. If all four credential tokens are loaded, IsAuthorized returns true.

What IsAuthorized does *not* do is check with Twitter to verify if the credentials are valid. There’s an API call, VerifyCredentials, that’s specifically for that purpose. I could have embedded the VerifyCredentials call into the IsAuthorized, but there are a couple problems with that – it would have used more bandwidth and consumed rate limit – all without your knowledge. The current design gives you more flexibility.

This design also recognizes the fact that once Twitter gives you credentials for a user, those credentials don’t normally change. However, one scenario where the OAuth process can fail is if the user removes your application from their list of authorized applications via their Twitter settings page. If that happens, you’ll encounter an exception with an HTTP message of 401 Unauthorized the next time the user tries to use your application. In that case, you should delete existing credentials and make the user authorize your application again, using the process explained in this post.

This gives you the choice of either calling VerifyCredentials yourself or writing code to handle the exception, but LINQ to Twitter doesn’t take that design decision away from you.

If the user isn’t authorized, await the call to AuthorizeAsync. Through the magic of WebAuthenticationBroker, WinRtAuthorizer takes care of opening and closing the brower control and the user doesn’t need to copy a PIN number anymore. All you need to do is use the authorizer.

Using the new WinRtAuthorizer Instance

That’s all there is to it. Once you have a WinRtAuthorizer instance, just use LINQ to Twitter as normal. Here’s a quick example:

            (from search in twitterCtx.Search
             where search.Type == SearchType.Search &&
                   search.Query == SearchTextBox.Text
             select search)
                async response =>
                    await Dispatcher.RunAsync(
                        async () =>
                            Search searchResponse = response.State.Single();
                            string message =
                                    "Search returned {0} statuses",

                            await new MessageDialog(message, "Search Complete").ShowAsync();

The only thing you need to do is instantiate TwitterContext with the new WinRtAuthorizer instance. Then you can execute commands and perform queries, which need to run asynchronously. The code above shows how to use the MaterializedAsyncCallback to process query results. For commands, you would use an overload that accepts a callback.


WinRtAuthorizer is the preferred way to perform OAuth with LINQ to Twitter. You do this by creating an instance of WinRtAuthorizer, selecting the credential store you want, and then awaiting a call to AuthorizeAsync.



Posted on Saturday, January 19, 2013 2:07 PM Twitter , LINQ , LINQ to Twitter , Windows 8 | Back to top

Copyright © Joe Mayo | Powered by: