2-legged OAuth with Gmail

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 2-legged OAuth authentication method and .NET IMAP component. The basic idea is that domain administrator can use this method to access user 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

Remember to add reference to Mail.dll and appropriate namespaces.

// C#

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


const string consumerKey = "example.com";
const string consumerSecret = "secret";
const string email = "pat@example.com";

Gmail2LeggedOAuth oauth = new Gmail2LeggedOAuth(
    consumerKey, consumerSecret);

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

    string oauthImapKey = oauth.GetXOAuthKeyForImap(email);

    client.LoginOAUTH(oauthImapKey);

    //...

    client.Close();
}
' VB.NET

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


Const  consumerKey As String = "example.com"
Const  consumerSecret As String = "secret"
Const  email As String = "pat@example.com"

Dim oauth As New Gmail2LeggedOAuth(consumerKey, consumerSecret)

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

	Dim oauthImapKey As String = oauth.GetXOAuthKeyForImap(email)

	client.LoginOAUTH(oauthImapKey)

	'...

	client.Close()
End Using

Here are the google apps configuration screens:

Tags: , , , , , ,

One Response to “2-legged OAuth with Gmail”

  1. 2-legged OAuth with IMAP Says:

    […] This article describes generic OAuth class, if you are using Gmail please read 2-legged OAuth authentication with Gmail […]

Questions?

Consider using our Q&A forum for asking any questions.