oauth-2.0azure-active-directoryazure-ad-msalmicrosoft-identity-platform

Can Azure AD OAuth client credentials flow permissions be limited to specific mailboxes?


I have a background service that needs to be able to monitor specific mailboxes for new emails in a customer's Azure AD. Because it's a background service, I'd like to use the OAuth client credentials flow.

To test this out, I registered an application in my own Azure AD (allowing accounts in any organizational directory), and am looking at setting the permissions. My understanding is that, for the client credentials flow, I can only set application-level permissions, not delegated. I see a Mail.Read permission for all mailboxes, but not a way to choose specific ones.

Am I missing the right way to set this up, or is switching to the authorization code flow with delegated permissions my only option?


Solution

  • Note that: You need to pass only application permissions while using Client Credential flow. As there is no user context involved in this flow, they are tenant-wide permissions.

    You can make use of Authorization code flow which needs delegated permissions which allows to request access.

    I created an Azure AD Application and granted API permissions like below:

    enter image description here

    Authorized users using below endpoint:

    https://login.microsoftonline.com/TenantID/oauth2/v2.0/authorize?
    &client_id=ClientID
    &response_type=code
    &redirect_uri=https://jwt.ms
    &response_mode=query
    &scope=https://graph.microsoft.com/Mail.Read
    &state=12345
    

    enter image description here

    enter image description here

    Now, I generated access token using below parameters:

    https://login.microsoftonline.com/TenantID/oauth2/v2.0/token
    
    client_id:ClientID
    grant_type:authorization_code
    scope:https://graph.microsoft.com/Mail.Read
    code:code
    redirect_uri:https://jwt.ms
    client_secret:ClientSecret
    

    enter image description here

    Using the above access token, you can read the mails like below:

    GET https://graph.microsoft.com/v1.0/me/messages
    

    enter image description here

    Otherwise, you can also try limiting the Application to specific mailboxes by creating the Application policy by referring this MsDoc:

    New-ApplicationAccessPolicy -AppId AppClientID -PolicyScopeGroupId xxx@xxx.com -AccessRight RestrictAccess -Description "Restrict this app to members"
    

    Reference:

    Get message - Microsoft Graph v1.0