How to authenticate IMAP client with Office 365 using Oauth2

I'm trying to get our IMAP client, that has been using username and password authentication, to use OAuth2.0 when connecting to Office 365. I've been looking at your example on how to use OAuth 2.0 with Gmail - [How to implement OAUTH 2.0 in Gmail using Ultimate Mail][1]. Also, I have been following the steps on [this][2] Microsoft page for obtaining the access token with client credentials flow. I can obtain the access token ok, I then convert it to SASL XOAUTH2 format, but when trying to authenticate the IMAP client it always fails with error "AUTHENTICATE failed (NO)" Here is my code: var accessToken = TokenService.GetToken(TenantId, ClientId, ClientSecret); if (string.IsNullOrEmpty(accessToken)) { throw new ApplicationException("Failed to retrieve access token."); } var rawSaslToken = string.Format("user={0}{2}auth=Bearer {1}{2}{2}", UserEmail, accessToken, '\x1'); var saslToken = Convert.ToBase64String(Encoding.ASCII.GetBytes(rawSaslToken)); var imapClient = new Imap(); imapClient.Connect("", 993, SslSecurityMode.Implicit); imapClient.Authenticate(saslToken, ImapAuthenticationMethod.OAuth20); I use the scope "" when obtaining the access token, as per Microsoft page instructions. I added API permission "IMAP.AccessAsApp" and granted Admin consent. I've also configured my Azure app to have access to the user mailbox. Any help would be appreciated. [1]: [2]:
asked 10/14/2022 9:28:18 PM
  I can confirm that the Azure app registration used to connect to the Office 365 account is configured correctly. I was able to authenticate and access the mailbox using a different mail client. So the token that I get back should be working. The problem must be with the way I construct the saslToken, or with imapClient.Authenticate. Ciprian Malaia 10/17/2022 7:32:57 PM
add a comment

0 Answers

Your Answer

Not the answer you're looking for? Browse other questions tagged imap or ask your own question.