Entries from June 2010 ↓

oAuth for IMAP and Gmail in C#

As part of developing Sentimnt (the Personal and Social Search engine) we needed to authenticate users with Gmail/Google Apps with IMAP OAuth. Here is how:
I looked for this one around the net for a long time and ended up implementing it myself so thought I should share it:

If you are going to use oAuth authentication with Gmail using IMAP in C# the you’d need to sort out two things:

  1. Get Access Token and Token Secret from Google
  2. Use an AUTHENTICATE method in IMAP protocol

This code uses dotNetOAuth for the oAuth part to get the access token and secret code. As for IMAP implementation I use LumiSoft IMAP and added AUTHENTICATE support to it.

Assuming you have the Consumer and TokenManager that you’ve used to get the AccessToken and TokenSecret, this will help you to build the XOAUTH parameter needed:

        public static string GetXAuth(string consumerKey, string consumerSecret, string token, string tokenSecret, string emailAddress)
        {
            Uri uri = GoogleOAuthHelper.GmailEndPoint(emailAddress).Location;
            OAuthBase oAuthBase = new OAuthBase();
            string normalizedUrl;
            string normalizedReqParams;
            string signature = oAuthBase.GenerateSignature(uri,
                                                           consumerKey,
                                                           consumerSecret,
                                                           token,
                                                           tokenSecret,
                                                           "GET",
                                                           oAuthBase.GenerateTimeStamp(),
                                                           oAuthBase.GenerateNonce(),
                                                           out normalizedUrl,
                                                           out normalizedReqParams);

            var parameters = HttpUtility.ParseQueryString(normalizedReqParams);
            parameters.Add("oauth_signature", signature);

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("GET {0} ", GoogleOAuthHelper.GmailEndPoint(emailAddress).Location.AbsoluteUri);
            IList<string> keys = new List<string>(parameters.AllKeys)
                .OrderBy(item => item)
                .ToList();
            foreach (var key in keys)
            {
                string value = parameters[(string)key];
                sb.AppendFormat("{0}=\"{1}\",", key, HttpUtility.UrlEncode(value));
            }
            string baseString = sb.ToString().TrimEnd(',');
            return Convert.ToBase64String(Encoding.UTF8.GetBytes(baseString));
        }