Posts Tagged ‘OAuth’

OAuth with IMAP

Monday, June 28th, 2010

OAuth is an open protocol to allow secure API authorization in a simple and standard method from desktop and web applications.

In this post I’ll show how to access GMail account using OAuth authentication method. The key advantage of this method is that it allows an application to access users email without knowing user’s password.

You can read more on OAuth authentication with Google accounts here:
http://code.google.com/apis/accounts/docs/OAuth_ref.html

Gmail IMAP and SMTP using OAuth:
http://code.google.com/apis/gmail/oauth/protocol.html

If your application is not registered, please select HMAC-SHA1 and use the following key and secret:
consumer key: “anonymous”
consumer secret: “anonymous”

You can manage your domains here:
https://www.google.com/accounts/ManageDomains

The following code makes several HTTP requests to authenticate your application. It also fires up the web browser, so the user can allow or deny the application to access his emails.

const string userEmailAccount = "alice@gmail.com";
const string consumerKey = "anonymous";
const string consumerSecret = "anonymous";

// First: get request token
ParameterList parameters1 = OAuth.ForUrl(
        "https://www.google.com/accounts/OAuthGetRequestToken")
    .Consumer(consumerKey, consumerSecret)
    .AddParameter("scope", "https://mail.google.com/")
    .AddParameter(OAuthParameterName.OAuthCallback, "oob")
    .Sign()
    .ExecuteWebRequest();

// Second: user interaction
string url2 = OAuth.ForUrl(
        "https://www.google.com/accounts/OAuthAuthorizeToken")
   .Consumer(consumerKey, consumerSecret)
   .Token(parameters1.GetValue(OAuthParameterName.OAuthToken))
   .TokenSecret(parameters1.GetValue(OAuthParameterName.OAuthTokenSecret))
   .Sign()
   .GetUrl();

// Fire up the browser
Process.Start(url2);
Console.WriteLine("Please enter the key: ");
string key = Console.ReadLine().Trim();

// Third: get access token
ParameterList parameters3 = OAuth.ForUrl(
        "https://www.google.com/accounts/OAuthGetAccessToken")
   .Consumer(consumerKey, consumerSecret)
   .Token(parameters1.GetValue(OAuthParameterName.OAuthToken))
   .TokenSecret(parameters1.GetValue(OAuthParameterName.OAuthTokenSecret))
   .AddParameter("oauth_verifier", key)
   .Sign()
   .ExecuteWebRequest();

// Log-in to IMAP server using XOAuth
using (Imap client = new Imap())
{
    client.ConnectSSL(TestConstants.GmailImapServer);

    string imapUrl = string.Format(
        "https://mail.google.com/mail/b/{0}/imap/", userEmailAccount);

    string oauthImapKey = OAuth.ForUrl(imapUrl)
        .Consumer(consumerKey, consumerSecret)
        .Token(parameters3.GetValue(OAuthParameterName.OAuthToken))
        .TokenSecret(parameters3.GetValue(OAuthParameterName.OAuthTokenSecret))
        .Sign()
        .GetXOAuthKey();

    client.LoginOAUTH(oauthImapKey);

    // Now you can access user's emails.

    client.Close(true);
}