IMAP OAuth2 with client credentials authentication failed

Boris T 1 Reputation point
2022-07-29T10:43:07.91+00:00

I am writing application that need to read mailbox using IMAP, but as daemon, without user interaction. I need to use OAuth2 to get access. Because I need it without user interaction, I need to use client credentials flow. This was added this June.

I have done everything from official documentation. Registered application, added permissions, added mailbox permission using PowerShell. When registering service principal using New-ServicePrincipal for ServiceId I used ObjectID from registered and from enterprise app, but it gets the same result.

When I get request access token with scope https://outlook.office365.com/.default, the one that I receive has role IMAP.AccessAsApp, so I believe that is correct. I used https://jwt.ms/ to parse JWT.

The problem is when I try to authenticate using this access token in Java, for example

    Properties props = new Properties();  
    props.put("mail.imap.ssl.enable", "true");  
    props.put("mail.imap.auth.mechanisms", "XOAUTH2");  
    props.put("mail.debug", "true");  

  
    Session session = Session.getInstance(props);  
    Store store = session.getStore("imap");  
    store.connect("outlook.office365.com", 993, "testing@mydomain.com", "accessToken");  

I receive AUTHENTICATE failed. I tried same code with access token received using authorization code flow, which requires user interaction. Using that access code I was able to connect to mailbox. So the code is correct.

I even tried using client id and service id instead of email address as username, but without success.

I am not sure where I made the mistake and if I am using correct username. Any help is appreciated.

Microsoft Exchange Online Management
Microsoft Exchange Online Management
Microsoft Exchange Online: A Microsoft email and calendaring hosted service.Management: The act or process of organizing, handling, directing or controlling something.
4,704 questions
Exchange Server Management
Exchange Server Management
Exchange Server: A family of Microsoft client/server messaging and collaboration software.Management: The act or process of organizing, handling, directing or controlling something.
7,771 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,758 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Boris T 1 Reputation point
    2022-07-29T13:00:24.143+00:00
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.