Hands-on lab: lock a Graph app down to a single shared mailbox on the Exchange side, then use the test results to prove the boundary to IT.

用 Microsoft Graph 读取客户的 Outlook 邮箱,而不向整个租户开放访问

Image: Uploaded by ClassicMacOSGuy / Public Domain

Key takeaways

  • Application permission scopes are extremely broad: with no signed-in user, the app can access all data covered by the permission.
  • When listing messages, Mail.ReadBasic.All is the lowest application permission; more data requires requesting a higher permission.
  • RBAC for Applications can lock an app down to specific mailboxes, and the strongest evidence is the app being denied on a mailbox outside the scope.

Granting a single consent to a connector that should only read an invoices mailbox

Mail.Read

lets the app read every mailbox in the tenant. A 2021 article on rakhesh.com described this reality: Graph can only grant read access across all mailboxes, and restricting it requires additional configuration on the Exchange side.

If your agent needs to read a customer's email, be prepared for the question IT will inevitably ask: "What can it read?" After reading this article, you can answer with test results.

What to build and what to prepare first

The scenario: the customer wants an agent to read a shared mailbox

invoices@

—and only that one. You will build an app that calls Graph without a signed-in user, lists messages, and then locks the app down to that mailbox.

You need a test tenant with admin rights, two mailboxes (one in scope, one out of scope),

curl

、

jq

, and an Exchange Online PowerShell session. First send a few emails to each mailbox. Do not practice on the customer's tenant.

Ask one question before writing code: will a user be signed in when the app runs? Microsoft recommends preferring delegated permissions whenever they meet the need. App-only access suits unattended background tasks.

Step 1: Register the app and request the narrowest permission

Register the app, create credentials, then add the application permission

Mail.ReadBasic.All

. For the list-messages API, this is the lowest application permission;

Mail.Read

and

Mail.ReadWrite

are both higher.

This permission serves Step 3; in Step 4 you will remove it and switch to a scoped permission. In a lab environment, a secret is the easiest option; at a customer, ask about their credential policy before choosing.

Application permissions always require admin consent. Check: the permission has been granted admin consent in the tenant. In your own lab you can just click it yourself; at a customer, this is a meeting that must be scheduled.

Step 2: Get a token

The version below uses raw HTTP requests so you can see every parameter. It is for the lab only—do not ship it to production as-is. The tenant's token endpoint is documented in Get access without a user.

.default

The scope bundles all application-level permissions the admin has consented to, so you don't need to list permissions individually here.

# 实验用的简便写法:TOKEN_URL 是租户的 token 端点
export TOKEN_URL='<tenant token endpoint>'
export CLIENT_ID='<application id>'
read -rs CLIENT_SECRET

TOKEN=$(curl -s -X POST "$TOKEN_URL" \
  -d "client_id=$CLIENT_ID" \
  --data-urlencode "client_secret=$CLIENT_SECRET" \
  --data-urlencode "scope=https://graph.microsoft.com/.default" \
  -d "grant_type=client_credentials" | jq -r .access_token)

if [ -n "$TOKEN" ] && [ "$TOKEN" != "null" ]; then
  echo "已获取 token"
else
  echo "未获取 token"
fi

Check: the terminal outputs

已获取 token

. If not, remove the

jq

part and rerun the command, then read the error response; but never paste a response containing a token into a chat or ticket.

Step 3: Read messages from the specified mailbox

To read a user's mail, call

/users/{id | userPrincipalName}/messages

. The code below uses

$select

to fetch only the needed fields.

This is a minimal version, just to confirm the app can read mail—not code for reading an entire mailbox; see the List messages documentation for parameter details.

export MAILBOX='invoices@test-domain'
URL="https://graph.microsoft.com/v1.0/users/$MAILBOX/messages?\$select=subject,receivedDateTime"

curl -s -H "Authorization: Bearer $TOKEN" "$URL" \
  | jq '{message_count: (.value | length)}'

Check:

message_count

is greater than 0, because you sent mail to this mailbox. Compare the returned data with the task the agent needs to accomplish; this is the basis for deciding whether a higher permission is needed.

Why a working app is only half the job

The app works, but the permission is still too broad. Microsoft classifies application permissions as high-privilege permissions because the app can access and modify data without anyone signing in. Its documentation states it plainly: granting an app more permissions than it needs is poor security practice.

The table below explains why

Mail.ReadBasic.All

alone is not enough. When the agent needs more data, you must request a higher permission, and that's when mailbox scoping becomes the piece you must lock down.

ConfigurationPermission levelWhose mail
Mail.ReadBasic.All from EntraLowest permission for listing messagesNot restricted by mailbox
Mail.Read from EntraHigherAll mailboxes
Scoped Application Mail.Read roleMail access via Exchange RBACOnly mailboxes in scope

Step 4: Swap the permission and lock the app down to the right mailbox

Now the requirements change: suppose the agent also needs to read invoice PDFs, and the lowest permission is no longer enough. You must upgrade to

Mail.Read

, but this time grant it not in Entra, rather through Exchange's

Application Mail.Read

role, bound to a scope.

RBAC for Applications in Exchange Online pairs permissions with resource scopes, where the resource scope determines which mailboxes the app can access. It replaces Application Access Policies.

Here's the trap: the effective permission is the union of what Entra grants and what Exchange RBAC grants. As Tony Redmond warned on Practical365, if

Mail.Read

is still present in Entra, all the controls RBAC provides are nullified.

Run the numbers with a hypothetical: the tenant has 800 mailboxes, and the scope contains only

invoices@

. If

Mail.Read

is still retained in Entra, the union of 800 mailboxes and 1 mailbox is still 800. After revoking consent, the app is left with just 1 mailbox.

So clean up Entra first. Any permission left in Entra adds to the effective permissions, so the

Mail.ReadBasic.All

granted in Step 1 must be removed, and if

Mail.Read

was ever added, remove it too: open the app under Enterprise applications, revoke admin consent, then delete these permissions from the app configuration.

Check: the list of permissions consented to the app contains no Mail permissions. The portal's button locations may change; use this criterion instead.

Next, prepare a management unit containing only

invoices@

and note its ID; see Microsoft's

RBAC for Applications 指南

for the full process. Then fill in three values and run the two commands below.

# AppId 和 ObjectId 取自 Enterprise applications 页面
$AppId = '<Application ID>'
$ObjectId = '<Object ID>'
$AdminUnitId = '<admin unit ID>'

New-ServicePrincipal -AppId $AppId -ObjectId $ObjectId
New-ManagementRoleAssignment -App $AppId -Role "Application Mail.Read" -RecipientAdministrativeUnitScope $AdminUnitId

If the customer already manages mailboxes with a management scope, replace the last parameter with

-CustomResourceScope

plus the scope's name. Check: neither command reports an error. No error does not prove the ID or scope is correct—that verification is saved for Step 5.

Step 5: Prove the app is blocked where it should be

Run

Test-ServicePrincipalAuthorization

. This cmdlet bypasses the cache and gives immediate results; whereas permission changes for real applications may take 30 minutes to 2 hours to take effect, depending on when the application was last used.

Test-ServicePrincipalAuthorization -Identity $AppId -Resource 'invoices@test-domain'
Test-ServicePrincipalAuthorization -Identity $AppId -Resource 'out-of-scope@test-domain'

Check: In the output of each run, look for

Application Mail.Read

role. The role must be effective on

invoices@

and not effective on the other mailbox. If it works on both, suspect the scope is too broad; if it works on neither, re-verify the IDs and scope.

Graph calls made immediately after a permission change, whether they succeed or fail, prove nothing. So wait for the cache window to pass, then re-run step 2 to get a fresh token.

Don't take the code from step 3 as-is for this test. It only outputs the length of

value

, and when denied it shows the same

message_count: 0

, identical to an empty mailbox. The code below preserves the HTTP status code and error code.

RESP=$(mktemp)
for MAILBOX in 'invoices@test-domain' 'out-of-scope@test-domain'; do
  URL="https://graph.microsoft.com/v1.0/users/$MAILBOX/messages?\$top=1&\$select=id"
  STATUS=$(curl -s -o "$RESP" -w '%{http_code}' \
    -H "Authorization: Bearer $TOKEN" "$URL")
  echo "$MAILBOX | HTTP $STATUS | $(jq -r '"message_count=\(.value | length) error=\(.error.code // "none")"' "$RESP")"
done
rm -f "$RESP"

Check:

invoices@

This line must be

HTTP 200

、

message_count=1

、

error=none

. The out-of-scope line must show a non-200 HTTP status code and a specific error code. If it shows

HTTP 200

and reads the mail, go back to the consent cleanup in step 4.

The out-of-scope line is the key evidence. Save the exact HTTP status code and error code, and hand them to the customer's IT team.

Two traps that make you think you're done

The first trap is taking the ID from the App registrations page, because you just registered the app there. The values shown on that page differ from Enterprise applications; if you use them,

New-ServicePrincipal

will fail.

The second trap is assuming a clean

Test-ServicePrincipalAuthorization

result is enough. This cmdlet doesn't account for permissions granted separately in Entra, so it only reflects the RBAC side. That's exactly why the real Graph call test in step 5 cannot be skipped.

What to bring to the meeting with the customer's IT team

Application permissions always require admin consent, so you can't do this alone. Bring a one-pager to the IT meeting: the permissions requested, why lower-privilege options aren't sufficient, the list of in-scope mailboxes, how to revoke access, and the HTTP status code and error code returned by the out-of-scope mailbox.

This skill is also great resume material. Instead of writing "integrated Microsoft Graph," state that you scoped the app to specific mailboxes and how you verified it. When current Forward Deployed Engineer (FDE) job descriptions mention enterprise data, this is a story worth preparing for interviews.

The next time a customer asks what your agent can read, the best answer is to show them the one time it was denied.

Was this article helpful?

Thanks for your feedback!

6 sources

Next on the roadmap · Phase 2: Full-stack engineering skills Copy last week verbatim—it may be more accurate than the customer's forecast model. Build a naive baseline first, then backtest on data the model hasn't seen; don't let training-set error decide scheduling.