Soorya P
Soorya P

Reputation: 31

Office 365 XOAUTH2 for IMAP Authentication fails from standalone java code

I am trying to connect an outlook mail box using imap .

scope defined for app is : API Permission

I am generating the token using client credential flow :

Below is the request i am posting to get the access token.

grant_type=client_credentials&client_id=MyClientID&client_secret=Mysecret&scope=https://outlook.office.com/.default

I received token successfully.

Here's the code, used to connect to IMAP from Java:

Properties props = new Properties();
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imaps.sasl.enable", "true");
props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
props.put("mail.imap.auth.login.disable", "true");
props.put("mail.imap.auth.plain.disable", "true");
props.put("mail.debug", "true");
props.put("mail.debug.auth", "true");
Session session = Session.getInstance(props);
session.setDebug(true);
String accessToken = "access_token_received_on_previous_step";
final Store store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, "[email protected]", accessToken);

Receiving below error:

A1 AUTHENTICATE XOAUTH2 dXNlcj1zb29yeW.........
A1 NO AUTHENTICATE failed.
javax.mail.AuthenticationFailedException: AUTHENTICATE failed.

Could anyone please help me to resolve the issue

Upvotes: 3

Views: 3174

Answers (1)

Allen Wu
Allen Wu

Reputation: 16458

You assigned an Microsoft Graph delegated permission IMAP.AccessAsUser.All in Azure AD app. But delegated permission is not supported for client_credentials grant type.

Based on the documentation:

OAuth access to IMAP, POP, SMTP AUTH protocols via OAuth2 client credentials grant flow is not supported.

And you need to use OAuth2 authorization code flow or OAuth2 Device authorization grant flow.

Besides, I think you may need to set the scope as https://graph.microsoft.com/.default because the permission is under Microsoft Graph now.

Upvotes: 1

Related Questions