javaazureoauth-2.0outlookoffice365

How to read my outlook mail using java and oauth2.0 with application regsitration in Azure AD


I am just trying to read my mail using java as shown in the code

how-to-access-outlook-office365-com-imap-form-java-with-oauth2

Also, aware of the documentations:

and gone through SO threads.. and done the steps as mentioned (i hope i did correctly)...

I can fetch token using client_credential but I am still stuck in A1 NO AUTHENTICATE failed error.

Though asking here to confirm that :

Update 1:

So far progressed..!


Solution

  • For client credentials flow, you need to add application permissions under Office 365 Exchange Online

    enter image description here

    Make sure to grant admin consent for all the application permissions.

    Once consent has been provided, the admin must register your AAD application's service principal in Exchange using powerShell by following commands:

    Install ExchangeOnlineManagement

    Install-Module -Name ExchangeOnlineManagement -allowprerelease Import-module ExchangeOnlineManagement Connect-ExchangeOnline -Organization

    Register Service Principal in Exchange:

    1.New-ServicePrincipal -AppId <APPLICATION_ID> -ServiceId <OBJECT_ID> [-Organization <ORGANIZATION_ID>]

    Make sure to use ObjectId from enterprise applications rather than object id of application registration. For the same application you registered in Application Registration. A corresponding application has been created in Enterprise Application as well. You need to pass object id from there while registering service principal in Exchange: enter image description here

    2.Get-ServicePrincipal | fl

    3.Add-MailboxPermission -Identity "john.smith@contoso.com" -User <SERVICE_PRINCIPAL_ID> -AccessRights FullAccess

    In the application, you need to use scope = 'https://outlook.office365.com/.default'

    Once you will get the access token, you can create and open a Java Mail connection to read mails.

        Properties props = new Properties();
    
        props.put("mail.store.protocol", "imap");
        props.put("mail.imap.host", "outlook.office365.com");
        props.put("mail.imap.port", "993");
        props.put("mail.imap.ssl.enable", "true");
        props.put("mail.imap.starttls.enable", "true");
        props.put("mail.imap.auth", "true");
        props.put("mail.imap.auth.mechanisms", "XOAUTH2");
        props.put("mail.imap.user", mailAddress);
        props.put("mail.debug", "true");
        props.put("mail.debug.auth", "true");
    
        // open mailbox....
        String token = getAuthToken(tanantId,clientId,client_secret);
        Session session = Session.getInstance(props);
        session.setDebug(true);
        Store store = session.getStore("imap");
        store.connect("outlook.office365.com", mailAddress, token);