Search code examples
c#imapmutexmailkit

Mailkit Authentication Failure


My problem:

The same code works fine in one instance but cannot authenticate with same username/password in another instance of the project.

My code:

static NetworkCredential _emailLoginCredentials;
_emailLoginCredentials = new NetworkCredential(_accountName, _accountPassword, _accountDomain);

using (var client = new ImapClient(new ProtocolLogger("C://Temp//Logs//imap1.log")))
{
    var credentials = _emailLoginCredentials;
    var uri = new Uri(_emailServer);
    string serverReply = String.Empty;

    client.Timeout = _imapClientTimeOut;
    client.Connect(uri);
    client.AuthenticationMechanisms.Remove("XOAUTH2");
    client.Authenticate(credentials);
    client.Inbox.Open(FolderAccess.ReadWrite);
}

Error:

Connected to imap://mail.company.com:143/?starttls=when-available
S: * OK The Microsoft Exchange IMAP4 service is ready.
C: A00000000 CAPABILITY
S: * CAPABILITY IMAP4 IMAP4rev1 AUTH=NTLM AUTH=GSSAPI AUTH=PLAIN UIDPLUS CHILDREN IDLE NAMESPACE LITERAL+
S: A00000000 OK CAPABILITY completed.
C: A00000001 AUTHENTICATE PLAIN
S: +
C: ZljbAY3hDYXJhdHNkZXYAQ2FyYXRzMTIz
S: A00000001 NO AUTHENTICATE failed.
C: A00000002 LOGIN username Password
S: A00000002 NO LOGIN failed.

Logs from the working project (same code):

Connected to imap://mail.company.com:143/?starttls=when-available
S: * OK The Microsoft Exchange IMAP4 service is ready.
C: A00000000 CAPABILITY
S: * CAPABILITY IMAP4 IMAP4rev1 AUTH=NTLM AUTH=GSSAPI AUTH=PLAIN UIDPLUS CHILDREN IDLE NAMESPACE LITERAL+
S: A00000000 OK CAPABILITY completed.
C: A00000001 AUTHENTICATE PLAIN
S: +
C: AN4FyYXRzZGV2AENhcmF0czEyMw==
S: A00000001 OK AUTHENTICATE completed.

To troubleshoot, I even hard-coded username and password in both. However, the outcome is still the same - one working and the other not working.

Well, there are some differences in the project setup etc. For example, in the non-working project, I am using above authentication code within a Mutex. Also, the entire method is protected override async Task Process(TaskMessage message)

Found this post but it was caused by NTLM which is not related to my case.

Mailkit Authenticate to Imap fails


Solution

  • Plain authentication contains two or three strings: "I wish to log in as x, I'm actually y, and my password is z". The two common cases are x=y and x not specified. Very rarely, y is a super-duper-privileged administrative user that can log in as others.

    In your working case, x is empty and y is xCaratsdev. In your error case, x is gicnt. Your password is the same in both cases (it's in the base64 blobs). Your next job is to find out where that gicnt comes from. But first, change the password.