Forum Discussion
Bland_Wu
Feb 25, 2021Copper Contributor
Connecting to Office 365 online mail with OAUTH 2.0 authentication always failed !
1 Issue Description There is an connecting issue using OAuth 2.0 to connect Office 365 mail server . I'm following the https://docs.microsoft.com/en-us/exchange/client-developer/legacy-protoc...
JLund75
Sep 16, 2022Copper Contributor
Bland_Wu Having the exact same issue and have tried to get in contact with Microsoft support to solve this without any luck. I use msal4j to get the access token which seems ok (sending the scope https://graph.microsoft.com/.default, sending any other scope will fail for me) but the access token returned have scope null but don't know if that is the issue.
Basically using the same attempt to connect with IMAP, a sample code below
String strClientID = "REMOVED ON PURPOSE";
String strClientSecret = "REMOVED ON PURPOSE";
String strTenant = "REMOVED ON PURPOSE";
Set<String> lstScope = new HashSet<>();
lstScope.add("https://graph.microsoft.com/.default");
IClientCredential cred = ClientCredentialFactory.createFromSecret(strClientSecret);
String AUTHORITY = "https://login.microsoftonline.com/" + strTenant + "/";
ConfidentialClientApplication cca = ConfidentialClientApplication.builder(strClientID, cred)
.authority(AUTHORITY).build();
ClientCredentialParameters parameters = ClientCredentialParameters.builder(lstScope).build();
IAuthenticationResult token = cca.acquireToken(parameters).join();
/* We have a token, this seems to work fine even though scope in the below print out will give 'null' */
System.out.println("We have token: " + token.accessToken());
System.out.println("Scope: " + token.scopes());
System.out.println("Expires: " + token.expiresOnDate());
/* Connect with IMAP */
Properties props = new Properties();
props.put("mail.debug.auth", Boolean.TRUE);
props.put("mail.event.scope", "session");
props.put("mail.imaps.starttls.enable", Boolean.TRUE);
props.put("mail.imaps.ssl.enable", Boolean.TRUE);
props.put("mail.imaps.host", "outlook.office365.com");
props.put("mail.imaps.port", "993");
props.put("mail.imaps.sasl.enable", Boolean.TRUE);
props.put("mail.imaps.auth.mechanisms", "XOAUTH2");
props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
props.put("mail.imaps.auth.login.disable", Boolean.TRUE);
props.put("mail.imaps.auth.plain.disable", Boolean.TRUE);
props.put("mail.imaps.usesocketchannels", Boolean.TRUE);
props.put("mail.imaps.sasl.mechanisms.oauth2.oauthToken", token.accessToken());
Session session = Session.getInstance(props, null);
session.setDebug(true);
session.setDebugOut(System.out);
IMAPStore store = (IMAPStore) session.getStore("imaps");
store.setUsername("EMAIL ADDRESS HERE");
store.setPassword(token.accessToken());
store.connect();
Result: always fails with
NO AUTHENTICATE failed.
Has anyone got this to work?