# Organization connections

> Authorize a Google Workspace or Microsoft 365 domain once, add its mailboxes as accounts, and open Microsoft 365 shared mailboxes.

URL: https://docs.workwae.com/guides/organizations

An organization connection lets a Google Workspace or Microsoft 365 administrator authorize Workwae once. You then list the directory and add mailboxes by address. Each becomes an account that syncs, sends and announces account events like one a user connected, without any user signing in.

## Choose an access method

| | Google Workspace delegation | Microsoft 365 app-only |
| --- | --- | --- |
| `kind` | `google_delegation` | `microsoft_app` |
| Credential | Your service account key | Your own app registration per cloud (client secret or certificate), or Workwae's app where Workwae runs one for that cloud |
| Administrator grants | Domain-wide delegation of the service account's client id, in the Admin console | Admin consent to the app |
| Required access | `gmail.modify` | `Mail.ReadWrite`, `Mail.Send` |
| Optional access | Calendar (on by default), contacts, `gmail.settings.sharing` (with `groupsEnabled`), `admin.directory.user.readonly` (with a directory admin) | `Calendars.ReadWrite`, `MailboxSettings.Read`, `Contacts.ReadWrite`, `User.Read.All` |

For a single Microsoft 365 shared mailbox, a [user's own grant](#shared-mailboxes) is enough. Gmail has no delegated shared mailboxes: use domain-wide delegation there, and see [Google Groups](#google-groups) for a group address.

A connection's `status` tracks whether it works:

| `status` | Meaning |
| --- | --- |
| `pending_consent` | No Microsoft directory has consented yet. |
| `unverified` | Registered, or its credential or scopes changed, and not tested since. |
| `active` | The last test or consent passed. |
| `failing` | The last test failed; `statusDetail` names the failed check. |

A missing optional permission limits only calendar, contacts or the directory; mail keeps syncing. For Google, the administrator must authorize every scope the connection lists, or no token is issued.

## Google Workspace delegation

### Register the connection

Send the service account's JSON key file. Workwae checks and seals it, and returns the `clientId` and the `google.scopes` to authorize, in the Admin console's order.

```bash tab="cURL"
jq -n --rawfile key service-account.json '{
  kind: "google_delegation",
  name: "Acme Workspace",
  domain: "acme.com",
  serviceAccountKey: $key,
  calendarEnabled: true,
  contactsEnabled: true,
  directoryAdmin: "it-admin@acme.com"
}' | curl -X POST "https://api.workwae.com/v1/org-connections" \
  -H "Authorization: Bearer $WORKWAE_API_KEY" \
  -H "content-type: application/json" \
  -d @-
```

```ts tab="TypeScript"
const connection = await workwae.orgConnections.create({
  kind: "google_delegation",
  name: "Acme Workspace",
  domain: "acme.com",
  serviceAccountKey, // the JSON key file's contents
  calendarEnabled: true,
  contactsEnabled: true,
  directoryAdmin: "it-admin@acme.com",
});
```

| Field | Meaning |
| --- | --- |
| `domain` | The Workspace primary domain, whose directory is listed. |
| `calendarEnabled` | Also authorize Google Calendar. Default `true`. |
| `contactsEnabled` | Also authorize Google Contacts. Default `false`. |
| `directoryAdmin` | A Workspace admin to impersonate for listing the directory; adds `admin.directory.user.readonly`. Omit it to add mailboxes by address only. |

Without calendar or contacts authorized, that sync fails for these accounts while mail keeps working. A key that is not a usable service account key answers 400 `invalid_service_account_key`.

### Have the administrator authorize it

In the Google Admin console, under Security > API controls > Domain-wide delegation, the administrator adds `connection.clientId` with every scope in `connection.google.scopes`.

### Test the connection

The test requests a token the way accounts will and reports each check. It impersonates `user`, or the directory admin by default; with neither, it answers 400 `user_required`.

```bash tab="cURL"
curl -X POST "https://api.workwae.com/v1/org-connections/$CONNECTION_ID/test" \
  -H "Authorization: Bearer $WORKWAE_API_KEY" \
  -H "content-type: application/json" \
  -d '{ "user": "ada@acme.com" }'
```

```ts tab="TypeScript"
const result = await workwae.orgConnections.test({ connectionId, user: "ada@acme.com" });
for (const check of result.checks) {
  if (!check.isOk) console.warn(check.name, check.detail);
}
```

A failed required check (`isRequired`) fails the test and leaves the connection `failing`.

Then [add mailboxes](#mailboxes).

## Microsoft 365 app-only access

A Microsoft connection names its cloud: `global` (worldwide, including GCC; the default), `gcc-high`, `dod` or `china` (21Vianet). Sign-in and Graph calls stay in that cloud.

> **Warning: No app-only mail sync in 21Vianet**
>
> Graph in 21Vianet has no message delta yet, so app-only mail sync does not run there. Connect those mailboxes over IMAP and SMTP with each user's Microsoft sign-in ([IMAP with OAuth](/guides/imap#xoauth2)).

### Register the connection

`credential` names the app: `{ "type": "platform" }` for Workwae's app, or your own registration with `client_secret` (`clientId`, `clientSecret`) or `certificate` (`clientId`, a PEM `certificate` and its unencrypted PKCS#8 `privateKey`).

```bash tab="cURL"
curl -X POST "https://api.workwae.com/v1/org-connections" \
  -H "Authorization: Bearer $WORKWAE_API_KEY" \
  -H "content-type: application/json" \
  -d '{
  "kind": "microsoft_app",
  "name": "Contoso (GCC High)",
  "cloud": "gcc-high",
  "credential": { "type": "client_secret", "clientId": "'"$CLIENT_ID"'", "clientSecret": "'"$CLIENT_SECRET"'" }
}'
```

```ts tab="TypeScript"
const connection = await workwae.orgConnections.create({
  kind: "microsoft_app",
  name: "Contoso (GCC High)",
  cloud: "gcc-high",
  credential: { type: "client_secret", clientId, clientSecret },
});
```

- The connection starts `pending_consent`. With your own app already consented in the directory, pass its `directoryId` instead; the connection starts `unverified` and you go straight to the test.
- `connection.microsoft.permissions` lists the Graph application permissions to grant, required ones first.
- A platform connection refuses `directoryId` (400 `directory_id_not_allowed`), and a cloud Workwae runs no app in answers 400 `provider_not_configured`. A bad certificate or key answers 400 `invalid_certificate`.

### Get admin consent

With your own app, start consent through the API and send a directory administrator to `consentUrl`. The browser returns to your `redirectUri` (on the [allowlist](/guides/connect#redirect-uris)) with `status`, `connection_id`, `error` and your `state`. The connection records the consenting directory and is tested.

Register the connection's `microsoft.redirectUri` as a Web redirect URI on the app registration. With `useConnectDomain` on the connection (on create or `PATCH`), consent runs on your [connect domain](/guides/oauth-apps#connect-domain) instead of `api.workwae.com`.

```bash tab="cURL"
curl -X POST "https://api.workwae.com/v1/org-connections/$CONNECTION_ID/consent" \
  -H "Authorization: Bearer $WORKWAE_API_KEY" \
  -H "content-type: application/json" \
  -d '{ "redirectUri": "https://app.example.com/admin/consent-done", "state": "tenant-7" }'
```

```ts tab="TypeScript"
const { consentUrl } = await workwae.orgConnections.consent({
  connectionId: connection.id,
  redirectUri: "https://app.example.com/admin/consent-done",
  state: "tenant-7",
});
```

Consent to Workwae's own app is started from the console only (403 `session_required` through the API), so the directory is taken from the administrator who actually signed in.

Errors on return include `access_denied`, `consent_failed`, `consent_unverified`, `directory_mismatch` and `directory_already_connected` (another platform connection holds the directory). Starting consent on a connect domain that is not active answers 409 `connect_domain_inactive`.

### Test the connection

Consent runs a test itself. Run `POST /v1/org-connections/{connectionId}/test` again after changing the credential; before any consent it answers 409 `consent_required`.

## Add mailboxes

Both kinds list their directory and add mailboxes the same way.

- `GET /v1/org-connections/{connectionId}/directory-entries` pages through the directory: up to 200 entries a page (default 100), `query` matching the start of names and addresses. Each entry's `accountId` names the account already added for it. A `nextCursor` is good for an hour, on this connection only.
- Listing needs `User.Read.All` (Microsoft) or a directory admin (Google).
- `POST /v1/org-connections/{connectionId}/accounts` adds up to 100 mailboxes per call, with optional `settings` for the new accounts.

```bash tab="cURL"
curl -X POST "https://api.workwae.com/v1/org-connections/$CONNECTION_ID/accounts" \
  -H "Authorization: Bearer $WORKWAE_API_KEY" \
  -H "content-type: application/json" \
  -d '{ "mailboxes": [{ "email": "support@acme.com" }, { "email": "sales@acme.com" }] }'
```

```ts tab="TypeScript"
import { paginate } from "@workwae/sdk";

const mailboxes = [];
for await (const entry of paginate(workwae.orgConnections.directoryEntries, {
  connectionId,
  query: "support",
})) {
  if (entry.accountId) continue; // already an account
  mailboxes.push({ email: entry.email, externalRef: entry.id });
}

const { items } = await workwae.orgConnections.addAccounts({ connectionId, mailboxes });
for (const added of items) {
  if (added.status === "failed") console.warn(added.email, added.error?.reason);
}
```

Each mailbox is checked through the connection first (Google: a delegated token for it; Microsoft: its inbox). Every address gets its own result, in request order: `created`, `exists` (a live account was already there) or `failed` with the reason the API would answer:

| Reason | Meaning |
| --- | --- |
| `invalid_grant` | No such user. |
| `consent_revoked` | The scopes or permissions are not granted. |
| `provider_forbidden`, `provider_not_found` | No mailbox access. |
| `plan_limit_accounts` | The plan's account limit was reached part way through; the mailboxes before it are created. |
| `plan_required` | The workspace has no plan and is not its owner's Free workspace; no mailbox is created. |

## Shared mailboxes

Open a Microsoft 365 shared mailbox as an account of its own, through the grant of an account whose user can open it. Shared mailboxes need the shared mailboxes module on in the workspace (403 `plan_module_unavailable`).

### Connect the delegating user with shared access

Connect the user's account with `options.sharedMailboxesEnabled` in a [connect flow](/guides/connect#hosted). It asks for `Mail.ReadWrite.Shared` and `Mail.Send.Shared`, plus the shared calendar and contacts permissions when those are on.

### Open the shared mailbox

```bash tab="cURL"
curl -X POST "https://api.workwae.com/v1/accounts/$USER_ACCOUNT_ID/shared-mailboxes" \
  -H "Authorization: Bearer $WORKWAE_API_KEY" \
  -H "content-type: application/json" \
  -d '{ "email": "billing@contoso.com" }'
```

```ts tab="TypeScript"
const billing = await workwae.sharedMailboxes.create({
  accountId: userAccountId,
  email: "billing@contoso.com",
});
```

The account reads the mailbox over Graph, or over Exchange IMAP when the delegating account uses IMAP.

| Error | Meaning |
| --- | --- |
| 400 `scope_missing` | The delegating account's grant lacks the shared scopes. Reconnect it with `options.sharedMailboxesEnabled`. |
| 400 `shared_mailbox_unsupported` | The delegating account is Gmail, password IMAP, itself shared or organization-authenticated, or the mailbox is its own. |
| 409 `account_exists` | The mailbox is already an account authenticated another way. |
| 422 `shared_mailbox_inaccessible` | The user cannot open the mailbox: no access, no such mailbox, or the login is refused. |

If the delegating account is deleted, the shared mailbox moves to `reauth_required` with `delegate_missing`.

## Google Groups

Add a Google Group such as `support@acme.com` as an account of its own (`provider: "gmail"`, `email` is the group address). Google has no API to read a group, so Workwae reads and sends through the mailbox of a member of the group, the relay, using the connection's delegation token. Groups need the shared mailboxes module on in the workspace (403 `plan_module_unavailable`).

Requirements:

- A `google_delegation` connection with `groupsEnabled: true`, and `gmail.settings.sharing` authorized in the Admin console. Workwae uses it to create the group's send-as alias on the relay.
- A relay: a licensed Workspace user who is a member of the group and receives each email sent to it.
- A group in the relay's domain, so Google accepts the alias without verification (400 `group_unsupported` otherwise).

```bash tab="cURL"
curl -X POST "https://api.workwae.com/v1/org-connections/$CONNECTION_ID/groups" \
  -H "Authorization: Bearer $WORKWAE_API_KEY" \
  -H "content-type: application/json" \
  -d '{ "email": "support@acme.com", "relayEmail": "alex@acme.com", "displayName": "Support" }'
```

```ts tab="TypeScript"
const support = await workwae.orgConnections.addGroup({
  connectionId,
  email: "support@acme.com",
  relayEmail: "alex@acme.com",
  displayName: "Support",
});
```

What the account holds:

- Only mail delivered to the relay through the group (its `List-Id` header) and mail sent as the group from the relay's mailbox, including drafts. The rest of the relay's mailbox is never synced or downloaded.
- Sends use the group as `From`. When the original sender's domain has a DMARC policy, Google Groups rewrites `From` to `"Name via Support" <support@acme.com>`. If Gmail's DMARC check passed for the group's domain, Workwae shows the original sender (`X-Original-Sender`) as `from`, so replies go to them.
- The relay's system folders only (Inbox, Sent, Drafts, Spam, Trash, Important). Its own labels are not shown, and labels cannot be created, renamed or deleted through the account (400 `group_unsupported`).
- No calendar and no contacts.
- Mail the group holds for moderation, or sends to spam, never reaches its members and so never reaches the account.
- Workwae checks the send-as alias when the account's sync starts and before each send, and never recreates one an administrator removed: the sync stops with `group_alias_missing` (retried with backoff) and sends fail. Adding the group again recreates it.
- Adding the group again with the same relay restores it. To use another relay, delete the account and add the group again.
- Deleting the account leaves the send-as alias on the relay's Gmail; remove it there if you no longer want it.

| Error | Meaning |
| --- | --- |
| 400 `group_unsupported` | The connection is not Google domain-wide delegation, or the address is not a group Workwae can add. |
| 400 `scope_missing` | The connection lacks `gmail.settings.sharing`. Turn on `groupsEnabled` and authorize the scope. |
| 409 `account_exists` | The address is already an account, or a group account read through another relay. |
| 409 `group_alias_unverified` | Google left the send-as alias pending verification, typically because the group is outside the domain. |
| 422 `group_relay_inaccessible` | Workwae cannot open the relay's mailbox: no such user, no license, or delegation refused. |

## When access changes

- When an administrator withdraws authorization, the affected accounts move to `reauth_required` with `consent_revoked`, and `account.reauth_required` is sent.
- Once access is restored, a passing test returns them to `active` and sends `account.connected` with `reauthorized: true`.
- Accounts added through a connection belong to it: a user sign-in cannot take them over. Fix the connection, then test it.
- Replacing a credential or the authorized scopes (`PATCH /v1/org-connections/{connectionId}`) makes the connection `unverified` until the next test.
- A connection cannot be deleted while live accounts use it (409 `connection_in_use`). Delete its accounts first.

Every route is in the [Organization connections](/reference/organization-connections) and [Shared mailboxes](/reference/shared-mailboxes) references.
