Skip to content

Server ClientAuthenticator requires client_id in token body, rejecting valid client_secret_basic requests (RFC 6749 §2.3.1) #3545

Open

Description

@andrewmaturo

Summary

The server-side ClientAuthenticator reads client_id only from the token request form body and raises invalid_client: "Missing client_id" when it is absent — even when the client authenticated correctly via HTTP Basic (Authorization: Basic base64(client_id:client_secret)). Per RFC 6749 §2.3.1, a client using client_secret_basic sends its client_id and client_secret in the Authorization header and MAY omit them from the body. Servers advertising client_secret_basic in token_endpoint_auth_methods_supported therefore reject spec-compliant clients (e.g. clients that use Basic and do not duplicate client_id into the body).

Location

src/mcp/server/auth/middleware/client_auth.py, authenticate_request:

form_data = await request.form()
client_id = form_data.get("client_id")
if not client_id:
    raise AuthenticationError("Missing client_id")
...
if client.token_endpoint_auth_method == "client_secret_basic":
    ...
    basic_client_id, request_client_secret = decoded.split(":", 1)
    basic_client_id = unquote(basic_client_id)
    if basic_client_id != client_id:   # only cross-checks; never used as fallback
        raise AuthenticationError("Client ID mismatch in Basic auth")

client_id from the Basic header is only used to cross-check a body-supplied value; it is never used as a fallback source. So a request with credentials solely in the Basic header fails before the client is even looked up.

Steps to reproduce

  1. Register a client with token_endpoint_auth_method=client_secret_basic.
  2. POST /token with grant_type=authorization_code, Authorization: Basic base64(client_id:client_secret), and no client_id/client_secret in the form body.
  3. Response: 401 {"error":"invalid_client","error_description":"Missing client_id"}.

Sending the same credentials via client_secret_post (in the body) works.

Expected

When Authorization: Basic is present, the authenticator should derive client_id from the header if it is absent from the body (RFC 6749 §2.3.1), then verify the secret as it does today.

Notes

This is the mirror image of client-side PR #3536 (which stops MCP clients from putting client_id in the body under client_secret_basic). With that client-side change, compliant clients will send client_id only in the Basic header — which this server-side code rejects. The two need to agree.

Observed on mcp 1.27.0.

Activity

  1. added
    v2
    v1
    on Sep 18, 2026
  2. 0xamlab commented on Sep 19, 2026

    @0xamlab

    Confirmed on current main: authenticate_request raises Missing client_id before the Basic header is ever parsed, so a client_secret_basic client that sends credentials only in the Authorization header — which #3536 now makes MCP clients do — is rejected, contrary to RFC 6749 §2.3.1. Proposed fix in src/mcp/server/auth/middleware/client_auth.py: parse the Basic header up front (leniently, so a stray or malformed header still only errors for clients actually registered with client_secret_basic), fall back to the Basic-derived client_id when the form body omits it, keep the existing body-vs-header mismatch check and secret verification unchanged, and keep returning Missing client_id when neither source provides one (preserving the current 401 contract). Tests: add a /token integration test next to test_client_secret_basic_authentication proving header-only credentials succeed; the existing tests already cover the body path and the mismatch failure. Since this is labeled v1+v2, I'd target main per CONTRIBUTING and can also prepare a v1.x backport if you'd like one. If an outside PR is welcome for this, please assign the issue to me and I'll open it immediately. (Disclosure: contributing on behalf of thyn-ai, with AI assistance; I can explain and defend every line of the change.)

  3. AlmogCohen commented on Sep 23, 2026

    @AlmogCohen

    Another real-world client hitting this: Vercel Connect (managed MCP connectors). It registers by DCR, picks client_secret_basic from the server's advertised token_endpoint_auth_methods_supported, and, per RFC 6749 §2.3.1, sends the client id only in the Authorization: Basic header. ClientAuthenticator rejects the authorization-code exchange with invalid_client: Missing client_id before it reads the header. Reproduced on mcp 1.28.0 (via FastMCP 3.x) and still present in the client_auth.py of 2.2.0.

    We worked around it by making CIMD registration work on our server, so Connect registers as a public client (none + PKCE) and never takes the Basic path. But any DCR client that follows the RFC hits this, while the server advertises client_secret_basic as supported.

  4. added
    bug
    on Oct 8, 2026
  5. nestdaddy commented on Nov 24, 2026

    @nestdaddy

    One more real-world client hitting this: Glama's connector health checks. It registers by DCR, picks client_secret_basic from the advertised methods, and sends the client id only in the Authorization: Basic header. Every hourly check failed with invalid_client: Missing client_id for days, while /authorize and consent worked fine. Still present in mcp 2.3.0 (the latest on PyPI today).

    Until this is fixed upstream, we run a small ASGI middleware in front of streamable_http_app(): for POST /token and POST /revoke with a Basic header and no client_id in the form, it copies the client id from the header into the form body and fixes content-length. The SDK still verifies the secret as before. Results after the change: Basic without body client_id → invalid_grant for a fake code (client auth passes), wrong secret → 401 Invalid client_secret, client_secret_post unchanged.

    Full middleware, a one-line curl test to check your own server, and the logs are written up here: https://nestdaddy.com/blog/mcp-python-sdk-rejects-client-secret-basic

    Happy to test a fix branch against a live server with real DCR clients if that helps.

  6. ApacheWang commented on Nov 25, 2026

    @ApacheWang

    Hi maintainers, I'd like to request assignment to work on #3545 per CONTRIBUTING.md.

    Root cause verified on main:

    1. ClientAuthenticator.authenticate_request() (src/mcp/server/auth/middleware/client_auth.py:54-57) requires form_data.get("client_id") before checking Authorization: Basic ..., rejecting RFC 6749 §2.3.1 client_secret_basic requests that pass client_id only in the Basic header.
    2. Even after authenticating via Basic header, TokenHandler.handle() (src/mcp/server/auth/handlers/token.py:120-129) validates raw dict(form_data) against AuthorizationCodeRequest (:27), RefreshTokenRequest (:41), and JwtBearerRequest (:55), which all require a non-optional client_id: str in the form body.

    Proposed minimal fix & test plan:

    1. Parse Authorization: Basic in ClientAuthenticator.authenticate_request() when present (URL-decoding both client_id and client_secret per RFC 6749 §2.3.1), resolve client_id from Basic or form body, enforce mismatch rejection when both are supplied, and still validate against the client's registered token_endpoint_auth_method (client_secret_basic requires Basic header; client_secret_post / none continue to require form client_id, preserving constant-time secret comparison and expiration checks).
    2. Make client_id optional (str | None = None) in the grant request models in token.py (or validate against the already-authenticated client_info.client_id), and check /revoke (handlers/revoke.py) which shares ClientAuthenticator so both endpoints behave consistently.
    3. Add regression tests in tests/server/mcpserver/auth/test_auth_integration.py / tests/interaction/auth/test_authorize_token.py covering client_secret_basic authorization-code exchange and token refresh without client_id in the form body, plus mismatch rejection, client_secret_post, none, and /revoke parity (100% branch coverage).

    Happy to align on any preference for token.py / revoke.py before opening the PR.

  7. ameer-agent-dev commented on Dec 1, 2026

    @ameer-agent-dev

    I verified this on main across both files in the /token authentication path:

    1. ClientAuthenticator.authenticate_request() (src/mcp/server/auth/middleware/client_auth.py:55-57) reads form_data.get("client_id") and raises Missing client_id before inspecting Authorization: Basic, rejecting RFC 6749 §2.3.1 client_secret_basic requests that omit client_id from the form body.
    2. AuthorizationCodeRequest, RefreshTokenRequest, and JwtBearerRequest (src/mcp/server/auth/handlers/token.py:27, 41, 55) require client_id: str, and TokenHandler.handle() checks auth-code and refresh-token ownership against token_request.client_id (token.py:145, 206) instead of the authenticated client_info.client_id.

    Approach I tested locally:

    • In client_auth.py: guard form_data.get("client_id") with isinstance(..., str) against Starlette UploadFile, parse Authorization with case-insensitive basic matching (RFC 9110), resolve client_id from the Basic header or form body (rejecting mismatches when both are sent), and after provider.get_client(client_id) enforce client.token_endpoint_auth_method so client_secret_basic rejects dual client_secret in header + body (RFC 6749 §2.3) and client_secret_post/none reject Authorization: Basic downgrades.
    • In token.py: change client_id to str | None = None on all three request models and verify ownership against client_info.client_id.
    • Add unit and /token route tests in tests/server/auth/middleware/test_client_auth.py (104/104 passing under tests/server/auth/, ruff check . clean, pyright clean on src/mcp/server/auth/ and tests/server/auth/).

    One question on target branch before opening anything: should a fix target main (v2) only, or do you also want a backport to v1.x given the v1 label?

  8. pamaxis commented on Dec 2, 2026

    @pamaxis

    Another production report, plus one constraint that affects the shape of the fix.

    What we hit

    We run a remote MCP server with DCR on FastMCP 3.4.6 / mcp 1.29.0. Within a few days, one widely used hosted MCP client moved its token requests to HTTP Basic with no client_id in the body. From then on every code exchange and every refresh from that client got 401 Missing client_id, while /authorize and the callback kept working, so its users could sign in but never got a connection. Nothing had changed on the server.

    Reproduction

    One file, no server needed. It still fails on mcp 2.3.0, on 1.30.0 and on main (77001c9).

    $ uv run --no-project --with mcp==2.3.0 python repro.py
    mcp 2.3.0
    Basic header, no client_id in body -> 401 {"error":"invalid_client","error_description":"Missing client_id"}
    Basic header + client_id in body   -> 400 {"error":"invalid_grant","error_description":"authorization code does not exist"}
    

    Expected: both requests pass client authentication and end in invalid_grant for the unknown code (RFC 6749 section 2.3.1: with HTTP Basic the client identifier travels in the header). On 1.30.0 the first line is the same with "error":"unauthorized_client".

    repro.py
    import asyncio
    import base64
    from importlib.metadata import version
    
    from mcp.server.auth.handlers.token import TokenHandler
    from mcp.server.auth.middleware.client_auth import ClientAuthenticator
    from mcp.shared.auth import OAuthClientInformationFull
    from starlette.requests import Request
    
    CLIENT = OAuthClientInformationFull(
        client_id="abc",
        client_secret="s3cret",
        token_endpoint_auth_method="client_secret_basic",
        redirect_uris=["https://client.example.com/callback"],
    )
    GRANT = b"grant_type=authorization_code&code=x&code_verifier=x&redirect_uri=https%3A%2F%2Fclient.example.com%2Fcallback"
    
    
    class Provider:
        async def get_client(self, client_id: str) -> OAuthClientInformationFull | None:
            return CLIENT if client_id == CLIENT.client_id else None
    
        async def load_authorization_code(self, client: OAuthClientInformationFull, code: str) -> None:
            return None  # unknown code: a request that passes client authentication ends in invalid_grant
    
    
    def token_request(body: bytes) -> Request:
        headers = [
            (b"content-type", b"application/x-www-form-urlencoded"),
            (b"authorization", b"Basic " + base64.b64encode(b"abc:s3cret")),
        ]
    
        async def receive() -> dict[str, object]:
            return {"type": "http.request", "body": body, "more_body": False}
    
        scope = {"type": "http", "method": "POST", "path": "/token", "query_string": b"", "headers": headers}
        return Request(scope, receive)
    
    
    async def main() -> None:
        provider = Provider()
        handler = TokenHandler(provider, ClientAuthenticator(provider))  # type: ignore[arg-type]
        print("mcp", version("mcp"))
        for label, body in [
            ("Basic header, no client_id in body", GRANT),
            ("Basic header + client_id in body  ", GRANT + b"&client_id=abc"),
        ]:
            response = await handler.handle(token_request(body))
            print(f"{label} -> {response.status_code} {bytes(response.body).decode()}")
    
    
    asyncio.run(main())

    What the fix needs, from our case

    • Both client_auth.py and handlers/token.py. The three grant models require client_id: str in the body and the handler compares it with the code's and the refresh token's client, so fixing only the authenticator turns the 401 into a 400 invalid_request. Same finding as in OAuth TokenHandler should check Authorization header for client credentials #1315.
    • The header fallback must not be limited to clients registered as client_secret_basic. Our stored clients are none: FastMCP 3.4.6 OAuthProxy confirms client_secret_basic and issues a secret at registration, but stores every DCR client as a public client (bug: FastMCP server advertises client_secret_basic but fails token exchange when HTTP Basic Auth is used PrefectHQ/fastmcp#4600). The client follows the registration response and sends Basic; the server only needs the client_id out of the header. A fix that keeps requiring a body client_id for none clients, as proposed in the two comments above, leaves those servers broken for every client that is already registered.
    • A v1.x backport, if you can. FastMCP 3.4.x requires mcp<2, so that is the line many deployed servers would pick this up from.

    An approach that works for us

    When the body has no client_id and the request carries a Basic header, take the client_id from the header for the client lookup. In the token handler, fill a missing body client_id from the authenticated client. The per-method checks stay as they are: a client_secret_basic client still has its secret verified and a body/header mismatch still fails, a client_secret_post client that sends Basic only is still rejected, and a malformed header still ends in Missing client_id.

    I have this as a tested patch against main: 21 lines added across the two files, and five test cases next to test_client_secret_basic_authentication, three of which fail without the change. The full test suite passes and both files keep 100% line and branch coverage. I can open it as a PR if you would take an outside one, or test a maintainer branch against a live server.

    src diff
    --- a/src/mcp/server/auth/handlers/token.py
    +++ b/src/mcp/server/auth/handlers/token.py
    @@ -118,9 +118,13 @@ class TokenHandler:
             try:
    -            form_data = await request.form()
                 # TODO(Marcelo): Can someone check if this `dict()` wrapper is necessary?
    -            token_request = token_request_adapter.validate_python(dict(form_data))
    +            form_data = dict(await request.form())
    +            if not form_data.get("client_id"):
    +                # The client is authenticated at this point. Under client_secret_basic its
    +                # client_id may be in the Authorization header only (RFC 6749 Section 2.3.1).
    +                form_data["client_id"] = client_info.client_id
    +            token_request = token_request_adapter.validate_python(form_data)
             except ValidationError as validation_error:
    --- a/src/mcp/server/auth/middleware/client_auth.py
    +++ b/src/mcp/server/auth/middleware/client_auth.py
    @@ -16,6 +16,16 @@ class AuthenticationError(Exception):
    +def _basic_client_id(auth_header: str) -> str | None:
    +    """Return the client_id of an `Authorization: Basic` header, or None if it is malformed."""
    +    try:
    +        decoded = base64.b64decode(auth_header[6:]).decode("utf-8")
    +    except ValueError:  # binascii.Error and UnicodeDecodeError are both ValueErrors
    +        return None
    +    client_id, separator, _ = decoded.partition(":")
    +    return unquote(client_id) if separator else None
    +
    +
     class ClientAuthenticator:
    @@ -53,6 +63,11 @@ class ClientAuthenticator:
             form_data = await request.form()
             client_id = form_data.get("client_id")
    +        auth_header = request.headers.get("Authorization", "")
    +        if not client_id and auth_header.startswith("Basic "):
    +            # RFC 6749 Section 2.3.1: a client authenticating with HTTP Basic sends its
    +            # client_id in the Authorization header and may omit it from the request body.
    +            client_id = _basic_client_id(auth_header)
             if not client_id:
                 raise AuthenticationError("Missing client_id")
    @@ -61,7 +76,6 @@ class ClientAuthenticator:
             request_client_secret: str | None = None
    -        auth_header = request.headers.get("Authorization", "")

    Not covered: /revoke. RevocationRequest requires client_id and client_secret in the body, so a Basic-only revocation fails validation even once authentication passes.

    Our current workaround is the one already described above: copy the client id from the Basic header into the form before the SDK handler runs.

    Disclosure: written with AI assistance. We hit this bug in production; I ran the reproduction and reviewed the text and the patch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugv1v2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions