Geeks With Blogs

News
Joe Mayo Cloud and Glue

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

http://geekswithblogs.net/WinAZ/archive/2012/07/02/using-linq-to-twitter-oauth-with-windows-8.aspx

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("http://linqtotwitter.codeplex.com/")
            };

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:

IOAuthCredentials
    WinRtCredentials
        LocalDataCredentials
        RoamingDataCredentials
        TemporaryDataCredentials

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.

Authorizing

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)
            .MaterializedAsyncCallback(
                async response =>
                    await Dispatcher.RunAsync(
                        CoreDispatcherPriority.Normal,
                        async () =>
                        {
                            Search searchResponse = response.State.Single();
                            string message =
                                string.Format(
                                    "Search returned {0} statuses",
                                    searchResponse.Statuses.Count);

                            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.

Summary

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.

 

@JoeMayo

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


Comments on this post: WinRtAuthorizer–A Better Way to do OAuth with LINQ to Twitter in Windows 8

# re: WinRtAuthorizer–A Better Way to do OAuth with LINQ to Twitter in Windows 8
Requesting Gravatar...
Hello,

I am trying to implement this way of authorization and wonder how this:

if (auth == null || !auth.IsAuthorized)
{
await auth.AuthorizeAsync();
}
is supposed to work if auth really were null? Then auth.AuthorizeAsync() would fail from what I can understand.
Left by Jan Andersson on Oct 17, 2013 10:32 PM

# re: WinRtAuthorizer–A Better Way to do OAuth with LINQ to Twitter in Windows 8
Requesting Gravatar...
Jan Andersson, Thanks for catching that. Fixed now.
Left by Joe Mayo on Oct 17, 2013 11:11 PM

# re: WinRtAuthorizer–A Better Way to do OAuth with LINQ to Twitter in Windows 8
Requesting Gravatar...
Is it still true that Windows Phone apps still need to use PIN-based authorization?
Left by Carlos on Feb 05, 2014 11:54 AM

# re: WinRtAuthorizer–A Better Way to do OAuth with LINQ to Twitter in Windows 8
Requesting Gravatar...
Carlos,

Not yet, I opened a user voice issue for the Windows Phone team to add a WebAuthenticationBroker, just like in Windows Store apps. That will make it easier to add the same functionality to Windows Phone. Please vote on this and ask your friends to do the same:

http://windowsphone.uservoice.com/forums/101801-feature-suggestions/suggestions/4994891-webauthenticationbroker
Left by Joe Mayo on Feb 05, 2014 12:18 PM

# re: WinRtAuthorizer–A Better Way to do OAuth with LINQ to Twitter in Windows 8
Requesting Gravatar...
Ok, I just voted and shared the request.

Let's hope they pay attention.

Keep up the great work, Joe.
Left by Carlos on Feb 05, 2014 1:13 PM

# re: WinRtAuthorizer–A Better Way to do OAuth with LINQ to Twitter in Windows 8
Requesting Gravatar...
Cliff Simpkins, Product Manager for Windows and Windows Phone Developer Experience just told me that we have the wrong user voice. This one is for consumer requests.

I went to the WPDev one, and saw that the equivalent request is already there. So, if you can vote, and let your friends and followers know, it would be appreciated.

This is the link:
http://wpdev.uservoice.com/forums/110705-dev-platform/suggestions/3388892-add-webauthenticationbroker-to-wp7-and-wp8

Best,
Left by Carlos on Feb 05, 2014 1:41 PM

# re: WinRtAuthorizer–A Better Way to do OAuth with LINQ to Twitter in Windows 8
Requesting Gravatar...
Carlos, Thanks for the research and letting me know.

Left by Joe Mayo on Feb 05, 2014 3:47 PM

Your comment:
 (will show your gravatar)
 


Copyright © Joe Mayo | Powered by: GeeksWithBlogs.net | Join free