1

I was looking for a way to Authenticate an IMAP session with google's Service account

But Since we already use Chilkat how do we do it, I found the following:

http://www.cknotes.com/imap-authentication-using-oauth/

allowing me to send a raw command:

imap.SendRawCommand("AUTHENTICATE XOAUTH <base64_data>");

This shows how to strucure the command: https://developers.google.com/gmail/xoauth2_protocol

But having trouble putting it all together.

limilabs puts things together nicely in this example: http://www.limilabs.com/blog/oauth2-gmail-imap-service-account

They have a neat imap.LoginOAUTH2(userEmail, credential.Token.AccessToken); that wraps things up into a command. How do I do this as a raw command for Chilkat?

Ephraim
  • 255
  • 2
  • 15

1 Answers1

1
const string serviceAccountEmail = "service-account-xxxxxx@developer.gserviceaccount.com";
const string serviceAccountCertPath = @"service-xxxxxx.p12";
const string serviceAccountCertPassword = "notasecret";
const string userEmail = "user@domain.com";



        X509Certificate2 certificate = new X509Certificate2(
            serviceAccountCertPath,
            serviceAccountCertPassword,
            X509KeyStorageFlags.Exportable);

        ServiceAccountCredential credential = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = new[] { "https://mail.google.com/" },
                User = userEmail
            }.FromCertificate(certificate));

        bool success = credential.RequestAccessTokenAsync(CancellationToken.None).Result;

        using (Chilkat.Imap imap = new Chilkat.Imap())
        {
            imap.UnlockComponent("unlock-code");
            imap.Ssl = true;
            imap.Port = 993;
            imap.Connect("imap.gmail.com");



            var authString = String.Format("user={0}" + "\x001" + "auth=Bearer {1}" + "\x001" + "\x001",userEmail, credential.Token.AccessToken);

           var encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(authString));

            string response = imap.SendRawCommand("AUTHENTICATE XOAUTH2 " + encoded);

            imap.SelectMailbox("Inbox");
            bool bUid;
            bUid = false;
            string mimeStr;
            int i;
            int n;
            n = imap.NumMessages;
            for (i = 1; i <= n; i++)
            {

                //  Download the email by sequence number.
                mimeStr = imap.FetchSingleAsMime(i, bUid);


                Chilkat.Email chilkatEmail = new Chilkat.Email();
                chilkatEmail.SetFromMimeText(mimeStr);
                Console.WriteLine(chilkatEmail.Subject);
            }


            imap.CloseMailbox("Inbox");

            Console.ReadLine();
        }
    }
Ephraim
  • 255
  • 2
  • 15