Heart of Angel

Archive for the ‘.net’ tag

Tutorial: Authenticating with Google OAuth

without comments

Recently I’ve been trying to get Google OAuth to work with my small tool but try as I might, I found no tutorial on the Internet on how to authenticating with Google OAuth using .NET Desktop application. With a few efforts I’ve been able to get it working and decide to share the knowledge with people who still have difficulty.

Authenticating with Google OAuth is similiar to other OAuth application, but there’s a few tricks to get it working with desktop application because of the nature of windows form. Some few main points you need to remember:

– ConsumerKey and ConsumerSecrets should be “anonymous”

– You should have a personal host lying around (free one is ok) as a callback to get verification code (I will get to that later).

What you need ?

– Scope of data you want to get. Generally a URL which define the data scope of Google service (Contacts, Calendar..) you wish to access. You can find sample data scopes here.

– DevDefined’s OAuth library. You can get it here.

For the purpose of this example, I will use “https://www.google.com/m8/feeds/” as I need to access user’s contacts.

Step 1: Get unauthorized request token.

string requestUrl         = "https://www.google.com/accounts/OAuthGetRequestToken";
string userAuthorizeUrl   = "https://www.google.com/accounts/accounts/OAuthAuthorizeToken";
string accessUrl          = "https://www.google.com/accounts/OAuthGetAccessToken";
string callBackUrl        = "http://yourhost.com/callback.htm";
                              //Blank callback HTML page on your host

 var context = new OAuthConsumerContext()
     ConsumerKey = "anonymous",
     ConsumerSecret = "anonymous",
     SignatureMethod = SignatureMethod.HmacSha1,
     //Remember to use SignatureMethod.HmacSha1 because we're desktop application

 var session = new OAuthSession(context, requestUrl, userAuthorizeUrl, accessUrl, callBackUrl)
  .WithQueryParameters(new { scope = "http://www.google.com/m8/feeds", xoauth_displayname = "Sample Google OAuth application" });
//xoauth_displayname will be your application name displayed on Google confirmation page, so choose carefully.
 var requestToken = session.GetRequestToken();

Step 2: Now we have the unauthorized request token, next step is get Authorization Url so user can grant us access

var loginUri = new Uri(session.GetUserAuthorizationUrlForToken(requestToken));

GoogleLoginForm form = new GoogleLoginForm(loginUri, callBackUrl);

The idea is you create a form which consist of one WebBrowser control, direct user to AuthorizationUrl and parse the verifier code in your callback’s url, here’s the whole code behind for that form:

    public partial class GoogleLoginForm : Form
        private Uri _loginUri;

        string _callBackUrl;
        string _OAuthVerifierToken;
        public string OAuthVerifierToken
            get { return _OAuthVerifierToken; }

        public GoogleLoginForm(Uri authUri, string callBackUrl)
            _loginUri = authUri;
            _callBackUrl = callBackUrl;

        private void GoogleLoginForm_Load(object sender, EventArgs e)
            wbGoogleLogin.Url = _loginUri;

        private void wbGoogleLogin_Navigated(object sender, WebBrowserNavigatedEventArgs e)
            string fullPath = e.Url.ToString();
            if (fullPath.StartsWith(_callBackUrl))
                string key = "oauth_verifier=";
                int index = fullPath.IndexOf(key);
                if (fullPath.IndexOf(key) != -1)
                    int length = fullPath.IndexOf("&", index) == -1 ? fullPath.Length - (index + key.Length) : fullPath.IndexOf("&", index) - (index + key.Length);
                    _OAuthVerifierToken = fullPath.Substring(index + key.Length, length);

                    DialogResult = DialogResult.OK;
                else DialogResult = DialogResult.Cancel;


The idea is we will try to parse verifier code when we detect user redirected to our callback url, then:

Step 3: Exchange request token for access token

IToken accessToken;
var dr = form.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
    accessToken = session.ExchangeRequestTokenForAccessToken(requestToken, form.OAuthVerifierToken);

You see, it’s just that easy, if we have access token then everything just go straight forward:

Step 5: Connect to Google

var request = new ContactsRequest(new RequestSettings("Sample Google OAuth application", "anonymous", "anonymous", accessToken.Token, accessToken.TokenSecret, "", ""));

That’s it. Now you can use your request like everyday use. If you don’t know how to working with Google Data API .NET then refer here.

Written by Tung Linh Le

November 24th, 2010 at 10:13 pm

Posted in Development

Tagged with , , , ,