# Authentication

Groundmail authenticates API requests with a Bearer credential: an **API key** (`gm_…`) for servers and CI, a short-lived **OAuth access token** (`gm_oat_…`) for the CLI and agents, or, from Azure, a **managed identity** token with no key at all. All of them carry [scopes](#scopes) that limit what they can do.

## Obtain a key

1. Open the [dashboard](https://app.groundmail.dev).
2. Go to **API Keys → Create**.
3. Copy the secret — it is shown **once**.

```bash
export GROUNDMAIL_API_KEY=gm_your_key_here
```

Keep keys server-side only. Never ship them in browser bundles or public repos.

The API answers browser (CORS) requests from one site only: the [API explorer](https://docs.groundmail.dev/api-explorer) on these docs, where you can try a request with your own key. Your own web pages can't call it with a key, so send requests from your server. (The [OAuth endpoints](https://docs.groundmail.dev/ai/mcp) used to sign in are the exception: browser-based clients can call them from anywhere.)

Give each key only the access it needs: choose **Full**, **Send only**, **Read only** or custom scopes when you create it, and optionally limit sending to specific verified domains. See [API keys](https://docs.groundmail.dev/api-keys).

## Request header

Send the key on every management and send request:

```bash
curl https://api.groundmail.dev/emails \
  -H "Authorization: Bearer $GROUNDMAIL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "from": "you@yourdomain.com",
    "to": "user@example.com",
    "subject": "Hello",
    "html": "<p>It works.</p>"
  }'
```

### Node SDK

```javascript
import { Groundmail } from 'groundmail'

const client = new Groundmail(process.env.GROUNDMAIL_API_KEY)
```

### CLI

```bash
export GROUNDMAIL_API_KEY=gm_your_key_here
npx -y --package=groundmail-cli -- groundmail emails send \
  --from you@yourdomain.com \
  --to user@example.com \
  --subject "Hello" \
  --html "<p>It works.</p>"
```

## Azure managed identity (no API key)

Workloads on Azure (Container Apps, App Service, Functions, AKS workload identity, VMs) can authenticate with their managed identity instead of a key: the app gets a short-lived Microsoft Entra access token from Azure and sends it as `Authorization: Bearer <token>`. Click **Connect Azure** under **API keys → New credential → Azure managed identity** (a tenant admin approves the Groundmail app once in Microsoft's sign-in), deploy with `DefaultAzureCredential` and the scope `https://api.groundmail.dev/.default`, and approve the identity in the dashboard after its first call, with the same access options as a key. Nothing to store or rotate. The CLI route (`az ad sp create` and registering the identity by its IDs) still works.

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

const credential = new DefaultAzureCredential()
const client = new Groundmail({ getToken: () => credential.getToken('https://api.groundmail.dev/.default') })
```

Setup, C# and Python code, and troubleshooting: [Authenticate from Azure with managed identity](https://docs.groundmail.dev/authentication/azure-managed-identity). The SMTP relay still uses SMTP credentials.

## OAuth for the CLI and agents

`groundmail login` signs the CLI in with OAuth instead of a permanent key: you approve it in the browser, choose the workspace, and see the scopes it asks for. It receives an access token that lasts an hour and a refresh token that rotates on every use (90 days without use and it expires). Revoke any sign-in under **Settings → CLIs & agents**.

```bash
groundmail login --scope emails:send,domains:read
curl https://api.groundmail.dev/domains -H "Authorization: Bearer $(groundmail auth token)"
```

Other tools can use the same flow, the OAuth 2.0 Device Authorization Grant (RFC 8628):

| Endpoint | |
|----------|---|
| Metadata | `GET https://app.groundmail.dev/.well-known/oauth-authorization-server` |
| Start | `POST https://api.groundmail.dev/oauth/device_authorization` with `client_id`, `scope` |
| Poll / refresh | `POST https://api.groundmail.dev/oauth/token` (`grant_type=urn:ietf:params:oauth:grant-type:device_code` or `refresh_token`) |
| Revoke | `POST https://api.groundmail.dev/oauth/revoke` with `token` |
| User info | `GET https://api.groundmail.dev/oauth/userinfo` with the access token |

### Identity scopes: `openid` and `email`

An OAuth client that only needs to know who signed in can ask for `openid` and `email`. They grant no access to a workspace: a token with only these scopes can call the user info endpoint and nothing else (every other endpoint answers `403 insufficient_scope`). Ask for them together with API scopes (`openid email emails:send`) to get both. A request that names no scope at all still gets `full`; a request for only `openid` and `email` never does.

```bash
curl https://api.groundmail.dev/oauth/userinfo -H "Authorization: Bearer $ACCESS_TOKEN"
# {"sub":"…","email":"ada@example.com","email_verified":true}
```

`sub` is a stable user id. `email` and `email_verified` come with the `email` scope. Signing in to Groundmail requires a verified email address.

A refresh token works once. Presenting one that was already used revokes the whole sign-in, since only a copy of it could be presenting it. See the [CLI](https://docs.groundmail.dev/cli) page for the commands.

The [hosted MCP server](https://docs.groundmail.dev/ai/mcp) signs clients in the same way, with the authorization code flow (PKCE): the person approving picks the scopes the client gets, and the connection appears under **Settings → CLIs & agents** with its scopes, where it can be revoked.

## Two-factor sign-in for the dashboard

Turn on two-factor under **Settings → Profile → Two-factor authentication**: scan the QR code with an authenticator app (1Password, Google Authenticator, Authy or any app that supports time-based codes), enter the 6-digit code it shows, and save your 10 recovery codes. From then on, every sign-in to the dashboard asks for a code after your password, email code, Google, GitHub, GitLab or AgentID sign-in. Tick **Don't ask again on this device for 30 days** to skip it on a computer you trust.

- **Lost your phone?** Sign in with a recovery code instead. Each one works once; get a new set under **Settings → Profile** (it asks for a current code from your app). If you've lost the recovery codes too, email support@groundmail.dev and we'll verify it's you before turning it off.
- **Teams:** owners can turn on **Settings → Team → Require two-factor** once they use it themselves. Members who haven't set it up are asked to before they can use the dashboard. The Team page shows who has it on.
- **`groundmail login` and MCP clients** sign in through the same browser page, so they ask for the code too. API keys, OAuth access tokens and SMTP credentials keep working as before: two-factor protects signing in, not each API call.

We email you when two-factor is turned on or off, and when a recovery code is used to sign in.

## Scopes

| Scope | Allows |
|-------|--------|
| `full` | Everything, including API keys, SMTP credentials, automations and integrations |
| `emails:send` | Send, batch, schedule, cancel and resend emails; send events |
| `emails:read` | List and read sent and received emails |
| `domains:read` | List domains and read their DNS records and status |
| `domains:write` | Add, verify, configure and delete domains (includes `domains:read`) |
| `webhooks:write` | Create, read, update and delete webhooks; send test events |
| `templates:write` | Create, read, update, publish and delete templates and assets |
| `suppressions:write` | Read, add and remove suppressions |
| `account:read` | Workspace details, deliverability and mail server status |
| `mailboxes:read` | List [mailboxes](https://docs.groundmail.dev/mailboxes) and read their threads, messages and attachments |
| `mailboxes:write` | Create, update, forward and delete mailboxes, and label and mark their mail (includes `mailboxes:read`) |
| `mailboxes:send` | Send and reply from mailboxes. Separate from the other two, so a key can read without being able to send |

API keys created before scopes existed keep their access: `full` keys are `full`, and `sending` keys are `emails:send` + `emails:read`.

A credential without the scope a request needs gets **403** with `code: "insufficient_scope"` and the scope it needs:

```json
{
  "error": {
    "message": "This API key lacks the `domains:write` scope. Create a key with that scope in Settings → API keys.",
    "code": "insufficient_scope",
    "required_scope": "domains:write",
    "details": { "required_scope": "domains:write", "granted_scopes": "emails:send" }
  }
}
```

The response also carries `WWW-Authenticate: Bearer error="insufficient_scope", scope="domains:write"`.

## Base URLs

| Surface | URL |
|---------|-----|
| API | `https://api.groundmail.dev` |
| Dashboard | `https://app.groundmail.dev` |

## Unauthorized responses

Missing or invalid keys, expired or revoked access tokens, and Azure managed identity tokens that fail any check return **401** with:

```json
{
  "error": {
    "message": "Unauthorized"
  }
}
```

See [Errors](https://docs.groundmail.dev/errors) for the full error shape.
