# Microsoft

## Implemented flow

The mock implements the **Microsoft identity platform v2.0 authorization code
flow**, including OIDC discovery, signed ID tokens, userinfo, refresh tokens and
an end-session endpoint. It supports `common`, `organizations`, `consumers`, tenant
IDs and domain authorities, with work, school, personal and guest identities.
Authorization responses can use `query`, `fragment` or `form_post`.

Hybrid and implicit flows, client credentials, device code and on-behalf-of grants
are not implemented. SPA registration rules, v1.0 endpoints, sovereign clouds and
Entra External ID / B2C are not modeled. Microsoft Graph is limited to OIDC
userinfo; photos, mail and other Graph APIs are not served.

Sources: [authorization code flow](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow),
[OIDC](https://learn.microsoft.com/en-us/entra/identity-platform/v2-protocols-oidc),
[scopes and permissions](https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc).

## OpenID Connect (OIDC)

This provider supports OpenID Connect (OIDC), which adds signed ID tokens to OAuth
2.0 so your app can verify the signed-in user's identity. Mockatoo publishes OIDC
discovery and signing keys for this provider. See the
[Hono + oauth4webapi example](https://github.com/mockatoo/examples/blob/main/oauth4webapi-hono/src/app.tsx)
for a minimal authorization code flow with discovery and ID-token validation,
including this provider's differences, without an auth abstraction.

## Using the connector

```ts
// Better Auth: pass the same options you give socialProviders.microsoft
import { mockMicrosoft } from "@mockatoo/connect-better-auth";
const microsoft = { clientId: process.env.MICROSOFT_CLIENT_ID!,
                    clientSecret: process.env.MICROSOFT_CLIENT_SECRET!,
                    tenantId: "common" };
export const auth = betterAuth({
  socialProviders: process.env.NODE_ENV === "production" ? { microsoft } : {},
  plugins: process.env.NODE_ENV === "production" ? [] : [mockMicrosoft(microsoft)],
});

// Auth.js
import MicrosoftEntraID from "next-auth/providers/microsoft-entra-id";
import { MockMicrosoftEntraID } from "@mockatoo/connect-authjs";
providers: [process.env.NODE_ENV === "production" ? MicrosoftEntraID() : MockMicrosoftEntraID()],
```

- **API scopes are accepted without registration.** Any scope matching
  `api://{id}/Scope`, an HTTPS App ID URI, or `{api-client-id}/Scope` can be used.
  This cannot validate your API registration or permissions. Graph permission
  names are checked against the published list, without checking app approval.
  An authorization request can name only one resource.
- Your own API receives a signed v2.0 JWT access token. Graph access tokens are
  opaque. Configure validators with the mock issuer and keys; check the audience
  difference documented below before relying on a successful mock validation.
- **Neither connector returns a profile picture.** Auth.js replaces its default
  profile mapping to skip the Graph photo fetch; pass a custom `profile` mapping
  to the connector if you use one.
- ID tokens omit `email_verified`, so Better Auth treats the email as unverified.
  Handle missing email and avoid assuming that matching emails allow linking.
- Preserve the tenant setting. Better Auth uses `oid` for identity; Auth.js uses
  the app-specific `sub`. Guests have a separate identity in each tenant.
- Request `offline_access` for refresh tokens. Refreshing returns a new refresh
  token, and the old refresh token remains usable.
- Auth.js requires an HTTPS mock origin for its tenant discovery. A local app's
  Node process must trust the local mock certificate. With `form_post`, account
  for state cookies omitted on cross-site POSTs by `SameSite=Lax`.

## Special test addresses

Log in as `you+<tag>@example.com` with your own account's password to get a distinct, stable test user. Tags combine with dots, such as `you+hd.unverified@example.com`. Any other tag, such as `you+1@example.com`, is just another user; see [Email tags](../email-tags.md).

| Tag | Behavior | |
| --- | --- | --- |
| `unverified` | `email_verified: false` (GitHub: primary email `verified: false`; Discord: `verified: false`; LinkedIn: `"false"` in the ID token) | [Example](https://github.com/mockatoo/examples/blob/main/better-auth-next/tests/tags/unverified.spec.ts) |
| `renamed` | Same user ID (`sub`, Microsoft `oid`, GitHub, Discord, X and Facebook `id`) as the address without `+renamed`, different email | [Example](https://github.com/mockatoo/examples/blob/main/better-auth-next/tests/tags/renamed.spec.ts) |
| `noname` | No name (Google: also no `given_name`/`family_name`; GitHub: `name: null`; Discord: `global_name: null`) | [Example](https://github.com/mockatoo/examples/blob/main/better-auth-next/tests/tags/noname.spec.ts) |
| `personal` | Personal Microsoft account; refused when the app's tenant is `organizations` or a tenant ID (unless also `guest`) | [Example](https://github.com/mockatoo/examples/blob/main/better-auth-next/tests/tags/personal.spec.ts) |
| `noemail` | No `email` claim, like an account without a mailbox (Discord: `email: null` and `verified: false`; LinkedIn: a member who signed up with a phone number; X: no `confirmed_email`; Facebook: the user declines the `email` permission, which `debug_token`'s scopes then leave out) | [Example](https://github.com/mockatoo/examples/blob/main/better-auth-next/tests/tags/noemail.spec.ts) |
| `guest` | Invited guest of a single-tenant app's tenant: `tid` is that tenant, `idp` the home tenant, and `oid` is new in each tenant | [Example](https://github.com/mockatoo/examples/blob/main/better-auth-next/tests/tags/guest.spec.ts) |
| `outsider` | Not in a single-tenant app's tenant: refused with `AADSTS50020` | [Example](https://github.com/mockatoo/examples/blob/main/better-auth-next/tests/tags/outsider.spec.ts) |
| `revoked` | Sign-in works; every refresh returns `invalid_grant` (GitHub: `bad_refresh_token`, and only with `offline_access`; X: `invalid_request`) | [Example](https://github.com/mockatoo/examples/blob/main/better-auth-next/tests/tags/revoked.spec.ts) |
| `mfa` | Sign-in works; every refresh returns `invalid_grant` with `AADSTS50076` and a claims challenge, as if MFA is now required | [Example](https://github.com/mockatoo/examples/blob/main/better-auth-next/tests/tags/mfa.spec.ts) |
| `throttled` | Sign-in works; every refresh returns 429 with `Retry-After` | [Example](https://github.com/mockatoo/examples/blob/main/better-auth-next/tests/tags/throttled.spec.ts) |
| `badcode` | The code exchange fails (`invalid_grant`; GitHub: `bad_verification_code`; LinkedIn and X: `invalid_request`; Facebook: `Invalid verification code format.`) | [Example](https://github.com/mockatoo/examples/blob/main/better-auth-next/tests/tags/badcode.spec.ts) |
| `down` | The token endpoint returns 503 | [Example](https://github.com/mockatoo/examples/blob/main/better-auth-next/tests/tags/down.spec.ts) |
| `flaky` | The first exchange of each code returns 503; a retry succeeds | [Example](https://github.com/mockatoo/examples/blob/main/better-auth-next/tests/tags/flaky.spec.ts) |
| `slow` | Token responses are delayed (10 seconds) | [Example](https://github.com/mockatoo/examples/blob/main/better-auth-next/tests/tags/slow.spec.ts) |
| `blocked` | After login, Google's "Access blocked" or Microsoft's "Need admin approval" page | [Example](https://github.com/mockatoo/examples/blob/main/better-auth-next/tests/tags/blocked.spec.ts) |

## Known differences



### This provider

| Difference | Effect |
| --- | --- |
| Any syntactically valid API scope (`api://{id}/Scope`, an HTTPS App ID URI, or `{api-client-id}/Scope`) is accepted. Known Graph permissions are accepted without checking app registration or admin approval. | Hides an unregistered API, nonexistent API permission, or missing app consent. Graph permission names are still validated. |
| Only v2.0 authorization code and refresh grants are served. Hybrid, implicit, client credentials, device code and on-behalf-of flows are refused. | Cannot exercise daemons, device sign-in, hybrid clients or API-to-API calls. |
| Only public-cloud v2.0 authority paths are served. v1.0, sovereign clouds and Entra External ID / B2C endpoints are not modeled. | Cannot exercise apps configured for those authorities. |
| The shared client models a web application. Token exchange does not enforce SPA registration, mandatory SPA PKCE or cross-origin redemption rules. | Hides problems that Microsoft rejects for a SPA registration. |
| Conditional access and throttling do not occur spontaneously. `+mfa` makes every refresh return a claims challenge; `+throttled` makes every refresh return 429. | Use the tags to exercise reauthentication and retry handling; ordinary sign-in does not validate tenant policies. |
| The profile photo comes from `graph.microsoft.com`, which can't be redirected, so both connectors skip it. For Auth.js the connector replaces the profile mapping with one that doesn't fetch the photo. | Hides problems in photo handling, and a custom Auth.js `profile` must be passed to the connector. |
| Access tokens for the app's own API are always v2.0, and `aud` is the App ID URI unless the scope names the API by its client ID. Real Microsoft issues v1.0 tokens (`iss: https://sts.windows.net/{tid}/`) unless the API's registration asks for v2.0, and a v2.0 `aud` is always the API's client ID. | Hides an API that validates `iss` or `aud` in a way real tokens won't pass. |
| Tokens carry no app roles, groups or optional claims (`verified_primary_email`, `xms_edov`, `upn`, `sid`). Better Auth marks the email verified when `verified_primary_email` is present. | Hides role and group checks, and email verification or account linking that depends on optional claims. |
| One signing key, never rotated, published without `x5t`, `x5c` or `issuer`. Real Microsoft publishes several keys with those fields and rotates them. | Hides missing key-rotation handling; breaks validators that use `x5c` or the key's `issuer` (for example Microsoft.IdentityModel). |

### Shared mock limits

| Difference | Effect |
| --- | --- |
| ID tokens are issued to the shared mock client. Native bundle IDs and native client registrations are not modeled. | Hides a native audience setting that does not match your production registration. |
| Refresh tokens do not expire from age or inactivity, even when a response advertises `refresh_token_expires_in`. Rotation and revocation still apply where supported; `+revoked` forces refresh failure. | Hides failures after long periods without sign-in. Use `+revoked` to exercise expired or revoked grant handling. |
| Any `http`/`https` callback URL is accepted, including `localhost`. Apple refuses `http` and `localhost`, and Microsoft refuses `http` except for `localhost`, whatever the app registered. | Hides a callback URL the real provider refuses outright. |
| Everyone uses one shared client (`mockatoo` / `mockatoo-secret`). The connectors replace your production client ID and secret, Apple's signed client secret, and Microsoft's client assertion. | Hides wrong production credentials or a broken client-secret setup. |
| The login form and the consent screen appear on every sign-in; there is no remembered session. `prompt=none` fails for Google (`interaction_required`) and Microsoft (`login_required`), and Discord and LinkedIn, which skip consent for a returning user (LinkedIn even with `prompt=consent`), always ask again. | Breaks silent sign-in that works with a real signed-in user. |
| Issuers and signing keys are the mock's (for example `https://app.mockatoo.globalunderdog.com/google`, not `https://accounts.google.com`). Discord's authorization responses carry `iss=https://app.mockatoo.globalunderdog.com/discord`, not `https://discord.com`. | Breaks code that hardcodes a real issuer or key URL. |
| Tokens are only valid at the mock. Real provider APIs (Google APIs, Microsoft Graph, GitHub's `api.github.com`, Discord's `discord.com/api`, LinkedIn's `api.linkedin.com`, X's `api.x.com`, Facebook's `graph.facebook.com`) reject them, and the mock doesn't serve those APIs beyond what sign-in needs. | Breaks app features that call the provider's API after sign-in. |
| A special address (`you+tag@…`) is a different test user with the same password. Apps that strip `+tags` from emails will merge them into one user. | Breaks special addresses in such apps. |
