# Authenticate from Azure with managed identity

Azure workloads can call the Groundmail API with their **managed identity**: no API key to store, rotate or leak. Your app asks Azure for a short-lived Microsoft Entra access token and sends it as the Bearer credential. Groundmail checks the token's signature against Microsoft's published keys and matches it to an identity you registered in the dashboard.

It works anywhere Azure gives a workload an identity: Container Apps, App Service, Functions, AKS (workload identity), Virtual Machines and VM scale sets, and pipelines that sign in as a service principal.

> Keyless auth covers the REST API and the SDKs that call it. The [SMTP relay](https://docs.groundmail.dev/smtp) still authenticates with an SMTP credential (`gmsmtp_…`), because SMTP has no way to carry an Entra token.

---

## How it works

1. **Connect Azure.** In the dashboard, open **API keys → New credential → Azure managed identity** and click **Connect Azure**. A Microsoft Entra admin approves the Groundmail app once, in Microsoft's own sign-in, and you come straight back. No CLI.
2. **Deploy your code.** It gets a token for `https://api.groundmail.dev/.default` from its managed identity with `DefaultAzureCredential` and sends `Authorization: Bearer <token>`. No key in config.
3. **Approve the identity that called.** Its first call gets a 401 that says it's waiting for approval, and the identity shows up in the dashboard with its name (for example "orders-api (Container App)"). Pick its access and click **Approve**. From then on its calls go through.

On every request Groundmail checks that:

- the token is signed (RS256) with a key Microsoft publishes for your tenant;
- it was issued by Microsoft Entra ID for your tenant (`https://sts.windows.net/{tenant}/` or `https://login.microsoftonline.com/{tenant}/v2.0`);
- it is within its validity window (`nbf` / `exp`, with two minutes of clock skew);
- its audience is `https://api.groundmail.dev` (or your own App ID URI, if you [use your own app registration](#alternative-your-own-app-registration));
- its tenant ID and object ID match an approved, active identity;
- it is an **app-only** token. Tokens issued to a user (delegated tokens with an `scp` claim) are refused.

Connecting your tenant gives Groundmail no access to your tenant or your data. The only permission the Groundmail app asks for is "Sign users in"; it never signs anyone in or reads anything. Connecting lets Entra issue tokens whose audience is Groundmail, and lets Groundmail show you the identities from your tenant that try to call it. Nothing can send until you approve it, and only identities from tenants you connected ever show up.

Tokens never leave your request and are never stored or logged.

---

## Step 1: connect Azure

In the dashboard, open **API keys**, click **New credential → Azure managed identity**, then **Connect Azure**. Sign in to Microsoft as a tenant admin (Global Administrator, Application Administrator or Cloud Application Administrator) and accept the prompt. You're sent back to the dashboard with the tenant shown as **Connected**.

**Not an admin?** Click **Copy a link to send your admin**. Anyone with the link can connect their tenant to your workspace, without a Groundmail login. The link works once and expires after 7 days; copying a new one cancels the old one.

Connecting adds the Groundmail **enterprise application** (service principal) to your tenant. Afterwards it appears under Microsoft Entra ID → **Enterprise applications** as **Groundmail**.

**Disconnect** removes the connection: identities waiting for approval from that tenant are removed and new ones stop showing up. Identities you already approved keep working until you revoke each one. To remove the app from your tenant too, delete the Groundmail enterprise application in Entra.

**Optional hardening:** to control which identities can get tokens for Groundmail at all, open the Groundmail enterprise application, set **Assignment required** to **Yes** under **Properties**, and assign your managed identities to it with Microsoft Graph (`New-MgServicePrincipalAppRoleAssignment`, using the default access role ID `00000000-0000-0000-0000-000000000000`). Groundmail already accepts only the identities you approve; this adds a second check on the Azure side.

If your tenant can't add third-party apps, [use your own app registration](#alternative-your-own-app-registration) instead.

---

## Step 2: deploy your code

Give the workload a managed identity (a system-assigned one is the simplest; the **Identity** blade of the resource in the portal), and use `DefaultAzureCredential` with the scope `https://api.groundmail.dev/.default`. See the [code examples](#code-examples) below. For a **user-assigned** identity, tell your code which identity to use with its client ID (`AZURE_CLIENT_ID`, or `ManagedIdentityClientId` in .NET).

---

## Step 3: approve the identity that called

Run the code once. The first call returns:

```json
{ "error": { "code": "unauthorized", "message": "This Azure identity is waiting for approval. Approve it in the Groundmail dashboard under API keys, then retry." } }
```

A banner appears at the top of the API keys page while an identity is waiting ("1 Azure identity is waiting for approval", with a **Review** button), and the identity is listed in the table as **Waiting for approval**. It is named after its Azure resource when Azure includes it in the token. Your connected tenant is listed in the same table as an **Azure tenant** row with a **Manage** action. Choose its access (**Send only** is the default and the right choice for most workloads, or **Full** or **Read only**) and click **Approve**. The next call goes through. **Ignore** dismisses it; it stays blocked.

Only valid, app-only tokens for Groundmail from a tenant you connected are listed, at most 20 waiting at a time.

---

## Alternative: set it up by hand (CLI)

The same result without the consent prompt: add the app to your tenant with the CLI and register each identity by its IDs.

**1. Add Groundmail to your tenant** (once per tenant; needs a role such as Application Administrator):

```bash
az ad sp create --id 0146ad5c-4051-4703-aece-e4edf9805d8e
```

Or with PowerShell (Microsoft Graph module):

```powershell
Connect-MgGraph -Scopes "Application.ReadWrite.All"
New-MgServicePrincipal -AppId 0146ad5c-4051-4703-aece-e4edf9805d8e
```

**2. Turn on the workload's managed identity** and note its IDs. For Container Apps:

```bash
az containerapp identity assign -n my-app -g my-rg --system-assigned
az containerapp show -n my-app -g my-rg --query identity.principalId -o tsv   # Object (principal) ID
az account show --query tenantId -o tsv                                        # Directory (tenant) ID
```

The same pattern works for App Service and Functions (`az webapp identity assign`, `az functionapp identity assign`) and VMs (`az vm identity assign`). For a user-assigned identity, use its **Object (principal) ID** (`az identity show -n my-identity -g my-rg --query principalId -o tsv`).

**3. Register the identity in Groundmail:** **API keys → New credential → Azure managed identity → Set it up by hand (CLI)**, and enter:

| Field | Value |
|-------|-------|
| Name | Something you'll recognize, like "Orders service (prod)" |
| Directory (tenant) ID | Your Entra tenant ID |
| Object (principal) ID | The managed identity's object ID, **not** its client ID |
| Client ID (optional) | A user-assigned identity's client ID. When set, the token's `appid` / `azp` must match too |
| Audience | Leave empty. It defaults to `https://api.groundmail.dev`. Only fill it in when you [use your own app registration](#alternative-your-own-app-registration) |
| Access | **Send only** (recommended), **Full** or **Read only**, plus an optional domain limit and tenant, exactly like an [API key](https://docs.groundmail.dev/api-keys) |

Each identity appears in the API keys list with its last use; open **Details** for its code, and **Revoke** stops it working from the next request.

---

## Code examples

Request a token for `https://api.groundmail.dev/.default` and send it as the Bearer credential. Tokens last 60 to 90 minutes; the Azure SDKs cache and refresh them, and so do the Groundmail SDKs below.

### C# (.NET)

```csharp
// dotnet add package Azure.Identity
using System.Net.Http.Headers;
using System.Net.Http.Json;
using Azure.Core;
using Azure.Identity;

var credential = new DefaultAzureCredential();
var scope = new TokenRequestContext(new[] { "https://api.groundmail.dev/.default" });

var http = new HttpClient { BaseAddress = new Uri("https://api.groundmail.dev") };

async Task<HttpResponseMessage> SendAsync(object email)
{
    // DefaultAzureCredential caches the token and refreshes it before it expires.
    AccessToken token = await credential.GetTokenAsync(scope);
    using var request = new HttpRequestMessage(HttpMethod.Post, "/emails") { Content = JsonContent.Create(email) };
    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.Token);
    return await http.SendAsync(request);
}

var response = await SendAsync(new
{
    from = "Acme <no-reply@acme.com>",
    to = "ada@example.com",
    subject = "Reset your password",
    html = "<p>Your reset link: <a href=\"https://acme.com/reset/abc123\">reset</a></p>",
});
response.EnsureSuccessStatusCode();
```

For a user-assigned identity: `new DefaultAzureCredential(new DefaultAzureCredentialOptions { ManagedIdentityClientId = "<client-id>" })`.

### Node.js

```ts
// npm install groundmail @azure/identity
import { DefaultAzureCredential } from '@azure/identity'
import { Groundmail } from 'groundmail'

const credential = new DefaultAzureCredential()

const groundmail = new Groundmail({
  // Called before requests; the SDK caches the token until shortly before it
  // expires, and asks for a fresh one once after a 401.
  getToken: () => credential.getToken('https://api.groundmail.dev/.default'),
})

await groundmail.emails.send({
  from: 'Acme <no-reply@acme.com>',
  to: 'ada@example.com',
  subject: 'Reset your password',
  html: '<p>Your reset link: <a href="https://acme.com/reset/abc123">reset</a></p>',
})
```

`getToken` can return the token string or an object with `token` and `expiresOnTimestamp` (what `credential.getToken()` returns). The `groundmail` package doesn't depend on `@azure/identity`; you pass the function. Needs `groundmail` 0.25.0 or later.

### Python

```python
# pip install groundmail azure-identity
from azure.identity import DefaultAzureCredential
from groundmail import Groundmail

credential = DefaultAzureCredential()

groundmail = Groundmail(
    # Called before requests; cached until shortly before it expires.
    token_provider=lambda: credential.get_token("https://api.groundmail.dev/.default"),
)

groundmail.emails.send(
    from_="Acme <no-reply@acme.com>",
    to="ada@example.com",
    subject="Reset your password",
    html='<p>Your reset link: <a href="https://acme.com/reset/abc123">reset</a></p>',
)
```

`token_provider` can return a string or azure-identity's `AccessToken`. Needs `groundmail` 0.9.0 or later.

### curl, from inside the workload

```bash
# Container Apps, App Service and Functions set IDENTITY_ENDPOINT and IDENTITY_HEADER.
TOKEN=$(curl -s "$IDENTITY_ENDPOINT?api-version=2019-08-01&resource=https://api.groundmail.dev" \
  -H "X-IDENTITY-HEADER: $IDENTITY_HEADER" | jq -r .access_token)

# On a VM, ask the instance metadata service instead:
# curl -s -H "Metadata: true" "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://api.groundmail.dev"

curl -X POST https://api.groundmail.dev/emails \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"from":"no-reply@acme.com","to":"ada@example.com","subject":"Hello","html":"<p>No API key.</p>"}'
```

From a VM or a pipeline signed in with its identity, the Azure CLI works too:

```bash
az login --identity
TOKEN=$(az account get-access-token --resource https://api.groundmail.dev --query accessToken -o tsv)
```

Other languages work the same way: any HTTP client, with the token from your Azure identity library in the `Authorization` header.

---

## Alternative: your own app registration

If your tenant can't add third-party apps, create an app registration that stands for Groundmail in your own tenant and use its App ID URI as the audience instead of `https://api.groundmail.dev`. It needs no secret, certificate, redirect URI or API permissions.

**Azure CLI:**

```bash
APP_ID=$(az ad app create --display-name "Groundmail API" --query appId -o tsv)
az ad app update --id "$APP_ID" --identifier-uris "api://$APP_ID"
az ad sp create --id "$APP_ID"
echo "Audience (App ID URI): api://$APP_ID"
echo "Audience application ID: $APP_ID"
```

**Azure portal:** Microsoft Entra ID → **App registrations** → **New registration** (name it "Groundmail API", single tenant, no redirect URI) → **Expose an API** → **Add** next to Application ID URI and accept `api://<application-id>`. Creating it in the portal also creates its enterprise application (service principal).

Then:

- In the dashboard, choose **Use your own app registration** in the Azure managed identity panel, and enter the App ID URI (for example `api://6d1f2c3a-…`) as the **Audience**. If you set the registration to issue v2.0 tokens, also enter its application (client) ID as **Audience application ID**.
- In your code, request tokens for `api://<application-id>/.default` instead of `https://api.groundmail.dev/.default` (or `resource=api://<application-id>` for the managed identity endpoint).

Use a dedicated app registration. Don't reuse the App ID URI of one of your own APIs: any service that receives tokens for an audience could replay them to every other service that accepts that audience.

---

## Permissions

A registered identity has the same options as an [API key](https://docs.groundmail.dev/api-keys):

- **Access:** Full, Send only, or Read only. Send only is the right choice for most app workloads.
- **Domain limit:** only send from specific verified domains.
- **Tenant:** limit the identity to one of your [tenants](https://docs.groundmail.dev/tenants), so it sends only as that customer.

Sends made with an identity show up under its name in **Emails**, count toward your plan like any other send, and follow the same [rate limits](https://docs.groundmail.dev/sending-limits). Creating and revoking identities is recorded in your workspace's audit log, and the workspace owner gets the same security email as for a new API key.

---

## Local development

`DefaultAzureCredential` falls back to your developer sign-in (Azure CLI, Visual Studio) when there's no managed identity. Tokens issued to a person are **delegated** tokens, which Groundmail refuses on purpose. For local development, either:

- use a test API key (`gm_test_…`) locally and the managed identity in Azure, or
- sign in as a service principal (`az login --service-principal`) and register that service principal's object ID as a separate identity with limited access.

---

## Troubleshooting 401s

Every authentication failure returns the same response, so a caller can't probe which check failed (the one exception is a valid token from a connected tenant that's [waiting for approval](#step-3-approve-the-identity-that-called)):

```json
{ "error": { "code": "unauthorized", "message": "Invalid API key or access token" } }
```

When the token was really issued by Microsoft for a registered identity, the dashboard shows the reason under **Last used** ("Last rejected token: …"). Check, in order:

| Symptom | Fix |
|---------|-----|
| "audience does not match" | Request the token for `https://api.groundmail.dev/.default`, or, with your own app registration, exactly the App ID URI you registered plus `/.default`. If your own registration issues v2.0 tokens, also enter its application (client) ID in **Audience application ID**. |
| "waiting for approval" | Approve the identity under **API keys → Waiting for approval**. |
| No reason shown at all | Groundmail found no approved identity with that tenant ID and object ID, and the tenant isn't connected (so nothing is waiting). [Connect Azure](#step-1-connect-azure), or check you registered the identity's **object (principal) ID**, not its client ID, and that it isn't revoked. |
| "issued to a user" | The token came from a developer sign-in, not the managed identity. See [Local development](#local-development). |
| "has expired" / "not valid yet" | Don't cache tokens yourself past `expiresOn`; let the SDK refresh them. Check the machine's clock. |
| "client ID does not match" | You set a client ID on the identity and the token came from another identity. Clear the field or fix `AZURE_CLIENT_ID`. |
| `AADSTS500011` when requesting the token | The Groundmail app hasn't been added to your tenant yet. [Connect Azure](#step-1-connect-azure), or run `az ad sp create --id 0146ad5c-4051-4703-aece-e4edf9805d8e`. With your own app registration, run `az ad sp create --id <application-id>`. |
| `AADSTS501051` / "not assigned to a role" | You set **Assignment required** on the enterprise application. Assign the managed identity to it. |
| 403 `insufficient_scope` | The token is fine but the identity's access doesn't cover the endpoint. Register it again with the access it needs. |
| 403 `domain_not_allowed` | The identity is limited to other sending domains. |

Tokens are checked against the global Azure cloud (`login.microsoftonline.com`). Azure Government and Azure China tokens aren't accepted yet. [Contact us](mailto:support@groundmail.dev) if you need them.

---

## Related

- [Authentication](https://docs.groundmail.dev/authentication): API keys, OAuth tokens and scopes
- [API keys](https://docs.groundmail.dev/api-keys): access options shared with Azure identities
- [Migrate from Azure Communication Services Email](https://docs.groundmail.dev/migration/azure-communication-services)
