Facing: AUTHENTICATE failed. Unable to authenticate through client credentials access token.

Vinay Sharma 56 Reputation points
2022-09-22T12:24:02.473+00:00

I am trying to follow this document https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth. I was able to generate access_token through postman successfully.
But when I am using that access_token with javax.mail, I am facing AUTHENTICATE failed.
Below is the code and screenshot
243892-accesstoken.png

    private void fetchMicrosoftMail() throws MessagingException {  
        Properties props = new Properties();  
        props.put("mail.imap.ssl.enable", "true");  
        props.setProperty("mail.imap.starttls.enable", "true");  
        props.put("mail.imap.auth.mechanisms", "XOAUTH2");  
        props.setProperty("mail.debug", "true");  
        Session session = Session.getInstance(props);  
        Store store = session.getStore("imap");  
        store.connect("outlook.office365.com", 993, "abc@example.com",  
            "{{access_token}}");  
        Folder[] folders = store.getDefaultFolder().list("*");  
        for (Folder folder : folders) {  
          System.out.println(folder.getName());  
        }  
      }  

What I am doing wrong?

Not Monitored
Not Monitored
Tag not monitored by Microsoft.
40,311 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. 2022-09-23T00:14:53.753+00:00

    Hello @Vinay Sharma , in order to succesfuly Authenticate an IMAP connection using OAuth client credentials with Azure AD you need to obtain an access token targeting the https://outlook.office.com/.default scope and encode the access token using the SASL XOAUTH2 format. E.g. base64("user=" + userName + "^Aauth=Bearer " + accessToken + "^A^A")

    In your code replace

       store.connect("outlook.office365.com", 993, "abc@example.com",  
                    "{  
           
                        {access_token}}");  
    

    With:

       store.connect("outlook.office365.com", 993, "abc@example.com", "SASL XOAUTH2 encoded access token");  
    

    Let us know if you need additional assistance. If the answer was helpful, please accept it and complete the quality survey so that others can find a solution.


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.