1
votes

I am trying to use MailKit (http://jstedfast.github.io/MailKit/docs/index.html) to log into Gmail using oAuth. I am able to log into Google API using a refreshed AuthToken, but when I try to use the refreshed token in MailKit, I get an error "Invalid Credentials"

Any clues?? Thanks, Jeff

Here is my code:

 var secrets = new ClientSecrets()
        {
            ClientId = "xxx-yyy.apps.googleusercontent.com",
            ClientSecret = "xyzSecret"
        };

        IAuthorizationCodeFlow flow =
                new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = secrets,
                    Scopes = new string[] { GmailService.Scope.GmailReadonly }
                });

        var tokenResponse = flow.RefreshTokenAsync("", connection.RefreshToken, CancellationToken.None).Result;

        using (var client = new MailKit.Net.Imap.ImapClient())
        {
            var credentials = new NetworkCredential("[email protected]", tokenResponse.AccessToken);

            client.Connect("imap.gmail.com", 993, true, CancellationToken.None);
            try
            {
                client.Authenticate(credentials, CancellationToken.None);
            }
            catch (Exception ex)
            {

                throw;
            }


        }
3
OAUTH2 requires a custom authentication flow, it cannot use standard IMAP Authentication, which is what this appears to be doing. It looks like you're passing the access token as a password, which it is not. - Max
Actually, with MailKit I think it is passed in as the password. Here is a link to another answer using SMTP, but still mine doesn't work. I am going to look into the scope which my AuthCode may not be built using the one I need. I just found mail.google.com for IMAP access. Mine had only read access from the API. Didn't realize it was different till just now. Anyway, here is the link @Max. [link] (stackoverflow.com/questions/24195508/smtp-and-oauth-2/…) - Jeff

3 Answers

1
votes

a clearer answer is that the scope was incorrect in the original code

Scopes = new string[] { GmailService.Scope.GmailReadonly }

needs to be

Scopes = new string[] { GmailService.Scope.MailGoogleCom }

in order to authenticate with imapi using a access token.

0
votes

It was just a scope problem. The above code works fine for gmail oAuth!!

0
votes
using (var client = new ImapClient())
            {
                client.Connect("imap.gmail.com", 993, true);  
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate(EmailId, Password);
            }

The above piece of code is used to log in to gmail using imap and MailKit tool. But before this, you have to log in to gmail manually and check "Enable Imap" option in Settings. This will surely work.