Contents
Better Auth can issue OAuth tokens that let AI agents such as Claude operate your app as the logged-in user. Microsoft Entra ID continues to handle login, while the app enforces resource restrictions, scopes, and revocation.
Key Points#
- Keep Entra ID tokens on the server and issue separate tokens for the MCP endpoint.
- Require PKCE and an explicit
resourcethat matches the MCP URL. - Validate consent when issuing tokens and on every MCP request, and block access when the client is disconnected.
- Pin the Better Auth version because the additional checks described here depend on internal implementation details.
Separate Login from Authorization#
Establish two independent trust boundaries. Entra ID authenticates users through SSO, while Better Auth authorizes AI clients to access the app. The MCP server accepts only app-issued tokens, not Entra ID tokens.
Set a single, exact URL, such as https://example.com/mcp, as the OAuth resource. This identifies the token’s intended recipient. Manage AI client registration and consent in the app so users can disconnect clients without changing the Entra ID app registration.
The implementation presented here targets Better Auth 1.7.12 and the MCP 2026-07-28 metadata profile. Treat the behavior below as version-specific and verify it against your installed packages before adopting the configuration.
Configure the OAuth Flow#
Add mcp() and cimd() alongside the existing socialProviders.microsoft configuration. Configure loginPage, consentPage, and resource, allow authorization_code and refresh_token, and expose items:read, items:write, and offline_access. Set disableJwtPlugin: true to use opaque access tokens, and retain storeTokens: "hashed". In Hono, route /api/auth/* and /.well-known/* to the Better Auth handler.
The connection proceeds in this order.
1. The MCP endpoint returns 401 with a WWW-Authenticate header containing the resource_metadata URL. 2. The client discovers the authorization server and either identifies itself using Client ID Metadata Documents (CIMD) or registers through /oauth2/register using dynamic client registration (DCR). 3. The client requests authorization with a PKCE challenge and the exact MCP resource. The app preserves the signed OAuth query throughout the Entra ID login, then displays the consent screen. 4. After approval, the client exchanges the authorization code for an access token and a refresh token.
When handing off to login, pass the entire signed query, including sig, as oauth_query. On the consent screen, display the requested scopes and redirect host alongside the client name. The registered name is self-reported and does not prove identity.
Add Checks Before Issuing Tokens#
The implementation presented here adds four restrictions to Better Auth’s defaults.
- Require a resource during authorization. Reject
/oauth2/authorizewithinvalid_targetunlessresourceexactly matches the MCP URL. Otherwise, requests that omit the resource can still obtain resource-specific tokens later. - Register only public clients. For unauthenticated DCR, require
token_endpoint_auth_method: "none". Under RFC 7591, the default when omitted isclient_secret_basic. - Apply redirect rules to both paths. Allow HTTPS redirects and HTTP loopback redirects. Validate DCR metadata during registration and CIMD redirects in
validateRedirectUri. CIMD does not pass through the registration endpoint. - Recheck consent before exchanging tokens. Reject authorization codes and refresh tokens with
invalid_grantif the original consent no longer exists.
Place these checks in hooks.before, except for CIMD redirect validation. Inspect the same parameter source the plugin reads. Use the body for registration; for authorization, use the body for the initial POST and the query for GET requests and login continuation. Checking both indiscriminately could allow validation to pass using parameters the plugin ignores.
CIMD also causes the server to access a client-controlled URL. Require public HTTPS destinations and reject loopback and special-purpose addresses. Use a fetch implementation that handles DNS resolution and redirects safely. Checking only the initial URL is insufficient.
Enforce Access Control and Disconnection#
At /mcp, authenticate using Bearer tokens only. Hash the token and check its expiration, revocation, exact resource match, and continued consent in the database. Reject DPoP-bound tokens on this Bearer-only route. Pass the validated user, client, scopes, and expiration time to the MCP handler.
Use opaque tokens so database checks can block access immediately. Require items:write for write tools, and call the same service layer as the web interface to keep ownership checks and input validation consistent. Tool annotations describe behavior; they do not enforce permissions. Exclude irreversible operations from the initial toolset.
Implement disconnection as a single transaction that deletes consent, access tokens, and refresh tokens. Retain the shared client record. Disable plugin endpoints the app does not need, such as alternative consent deletion paths and /get-access-token. Deletion alone cannot prevent a concurrent refresh from writing another token, so consent checks on each request remain necessary.
Understand the Remaining Limitations#
Timestamp-based consent checks cannot distinguish operations within the same second. Revocation, concurrent refreshes, and renewed consent may cause an old authorization to be considered valid. A consent generation identifier provides a more reliable distinction. The configuration presented here also retains a 30-second refresh retry grace period that accepts reuse of the immediately preceding refresh token.
Disabling an Entra ID account does not automatically revoke app-issued tokens. Add revocation handling in the app. Test whether actual clients’ Origin headers comply with your policy, and because the hooks depend on internal data structures, pin the Better Auth version and test authorization, refresh, and disconnection.
Next Steps#
Add an integration test that verifies both existing access tokens and refresh tokens are rejected after a client is disconnected.
Source: https://zenn.dev/sakagi/articles/8caa896e649005
Contents
