I tried to authenticate on a O365 application I created on the Azure portal and it doesn't work as expected.
The following code works well but it's using a login/password and it's not recommended by Microsoft. (found here https://github.com/jstedfast/MailKit/issues/989)
var scopes = new[] { "https://outlook.office365.com/IMAP.AccessAsUser.All" };
var confidentialClientApplication = PublicClientApplicationBuilder.Create(_clientId).WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs).Build();
SecureString securePassword = new NetworkCredential("", _userPassword).SecurePassword;
var acquireTokenByUsernamePasswordParameterBuilder = confidentialClientApplication.AcquireTokenByUsernamePassword(scopes, _userMail, securePassword);
var authenticationResult = acquireTokenByUsernamePasswordParameterBuilder.ExecuteAsync().Result;
if (_debugCall)
{
imapClient = new ImapClient(new ProtocolLogger(_configurationId + "_IMAP_" + DateTime.Now.ToString("yyyyMMddHHssffff") + ".log"));
}
else
{
imapClient = new ImapClient();
}
imapClient.CheckCertificateRevocation = false;
imapClient.ServerCertificateValidationCallback = (s, c, h, e) => true;
imapClient.Connect(_webServiceUrl, _webServicePort, SecureSocketOptions.Auto);
imapClient.Authenticate(new SaslMechanismOAuth2(_userMail, authenticationResult.AccessToken));
if (string.IsNullOrEmpty(_folder))
{
oFolder = imapClient.Inbox;
}
else
{
oFolder = imapClient.GetFolder(_folder);
}
oFolder.Open(FolderAccess.ReadWrite);
In fact I want to be able to authenticate using the tenanid, client secret and clientid but without the interactive mode (as the app is a windows services).
So I tried to use another code with the tenantid, clientSecret and ClientId but I receive the "Authentication failed" error message :
var confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(_clientId)
.WithClientSecret(_clientSecret)
.WithRedirectUri("http://localhost")
.WithAuthority(new Uri("https://login.microsoftonline.com/" + _tenantid + "/"))
.Build();
var scopes = new[] { "https://outlook.office365.com/.default" };
var authenticationResult = confidentialClientApplication.AcquireTokenForClient(scopes);
var authToken = authenticationResult.ExecuteAsync().Result;
var oauth2 = new SaslMechanismOAuth2(_userMail, authToken.AccessToken);
imapClient = new ImapClient(new ProtocolLogger("TEST_IMAP_" + DateTime.Now.ToString("yyyyMMddHHssffff") + ".log"));
imapClient.CheckCertificateRevocation = false;
imapClient.ServerCertificateValidationCallback = (s, c, h, e) => true;
imapClient.Connect(_webServiceUrl, _webServicePort, SecureSocketOptions.Auto);
imapClient.Authenticate(oauth2);
I've the following permission for my app on the Azure portal:
MSGraph
IMAP.AccessAsUser.All
Mail.Read
Mail.ReadWrite
Mail.Send
Did I miss something? I'm afraid it may be impossible? The official sample on Mailkit website use the interactive mode.
Btw, I'm using Mailkit v2.4
Thank you for your help.