2-legged OAuth with IMAP

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

This article describes generic OAuth class.
If you are using Gmail please read 2-legged OAuth authentication with Gmail.

Remember to add reference to Mail.dll .NET IMAP component and appropriate namespaces.

// C#

using Limilabs.Client.Authentication;
using Limilabs.Client.IMAP;

string consumerKey = "your_domain.com";
string consumerSecret = "your_oauth_consumer_secret";
string emailAccount = "address@your_domain.com";

using (Imap client = new Imap())
{
    client.ConnectSSL("imap.gmail.com");

    string imapUrl = string.Format(
        "https://mail.google.com/mail/b/{0}/imap/?xoauth_requestor_id={1}",
        emailAccount,
        HttpUtility.UrlEncode(emailAccount));

    string oauthImapKey = OAuth.ForUrl(imapUrl)
        .Consumer(consumerKey, consumerSecret)
        .SignatureMethod(SignatureType.HMACSHA1)
        .Sign()
        .GetXOAuthKey();

    client.LoginOAUTH(oauthImapKey);

    //...

    client.Close();
}
' VB.NET

Imports Limilabs.Client.Authentication
Imports Limilabs.Client.IMAP

Dim consumerKey As String = "example.com"
Dim consumerSecret As String = "secret"
Dim emailAccount As String = "pat@example.com"

Using client As New Imap()
    client.ConnectSSL("imap.gmail.com")

    Dim imapUrl As String = String.Format( _
        "https://mail.google.com/mail/b/{0}/imap/?xoauth_requestor_id={1}", _
        emailAccount, _
        HttpUtility.UrlEncode(emailAccount))

    Dim oauthImapKey As String = OAuth.ForUrl(imapUrl) _
        .Consumer(consumerKey, consumerSecret) _
        .SignatureMethod(SignatureType.HMACSHA1) _
        .Sign() _
        .GetXOAuthKeyForImap()

    client.LoginOAUTH(oauthImapKey)

    '...

    client.Close()
End Using

Tags:      

Questions?

Consider using our Q&A forum for asking questions.

2 Responses to “2-legged OAuth with IMAP”

  1. Gabriel Says:

    I’m trying to run this example in a ASP.NET with:

    string consumerKey = “anonymous”;
    string consumerSecret = “anonymous”;
    string emailAccount = “mymail@gmail.com”;

    using (Imap client = new Imap())
    {
    client.ConnectSSL(“imap.gmail.com”);

    The browser doesn’t show me the Gmail login page.

    And when trying to login (line 22) i got this “[ALERT] Invalid credentials (Failure)”.

    What am I doing wrong?

  2. Limilabs support Says:

    @Gabirel,

    I think you don’t want to use 2-legged but rather 3-legged OAuth:
    http://www.limilabs.com/blog/oauth-with-imap