Limit App Registration to specific mailbox

So I want to create an app registration and limit it to a specific mailbox – i.e. only send/ read emails from that mailbox. Can’t do this entirely via the Graph API. All I can do in Graph API is give it permissions to send/ read emails from all mailboxes.

To restrict this to a specific mailbox we need to use application access policies.

But first, let’s see what I can do a with an app registration that’s not restricted.

In this case I was lazy and didn’t create a self-signed cert for the app registration, instead I created a secret. When you use a secret Connect-MgGraph does not have a way to authenticate using it (it only does the interactive DeviceAuthentication or certificates) and so we have to resort to Invoke-RestMethod to authenticate (or Postman like in my previous post).

Just as an fyi, typically at this point I’d convert the hash to a JSON and use that to connect to the API.

But that gives an error:

Instead simply passing the hash table is fine:

(As an aside, I know the Url to connect to and the parameters to pass in the body from this doc). This gives me an access token if I successfully authenticate, which is what we have in the output. Ideally I should capture the output in a variable so I have the token.

Now I have the token in $connectGraph.access_token. Using that I can authenticate via the Connect-MgGraph cmdlet too:

(So yeah, it is easier to just use a certificate with Connect-MgGraph but I like to spice things up occassionally) :)

Now to get some emails of a user. I have the userid (not the UPN, Email-Address, or sAMAccountName… this is the Azure AD GUID of the user; get this from the portal or via say Get-MgUser) already so I am going to skip finding that:

Armed with the folder id I can see the emails in it:

So how do I limit this? Say I want to limit access to the mailbox of

First, install the ExchangeOnlineManagement module and connect with admin creds. This is Windows PowerShell only, so handy tip for anyone else not having access to Windows – if you have an Azure subscription open up Cloud Shell and install the module there, then login using Device Authentication to the Tenant you want to work with (My bad, this module works with PowerShell Core too; in fact, the Azure Cloud Shell is PowerShell 7.x)

Then I can limit using the New-ApplicationAccessPolicy cmdlet. This requires the client id of the app registration, permissions you want to set, and the email address(es) you want to limit to (in case of more than one, put them into a mail enabled security group and pass on the email address of that group).

This could take up to 30 mins to take effect for Graph API calls *yawn*… so I wait patiently… as time crawls by… frequently trying the same call as before… almost giving up…. until… finally… I am denied:

And just to confirm, I can view the mails of the user I restricted this app registration to: