Authenticating an MCP Server to an External API

While working on my personal garage software, I extracted the part that finds car parts into its own app, bonneref.fr. The Garage App has an MCP server that Claude Code, Claude Desktop or Goose connect to, and its catalogue tools now had to proxy their calls to the Parts App. Both are my entry for the Symfony AI & MCP hackathon. This post shows how I did it, starting with the version I got wrong.
The naive approach: token passthrough#
The MCP client gets its token the standard way: POST /mcp without a token answers a 401 pointing at the protected resource metadata (RFC 9728), the client discovers the authorization server, registers itself with dynamic client registration (RFC 7591) and runs the code flow. The token it gets back is bound to the resource it asked for (RFC 8707), so its aud is the Garage App’s /mcp URL.
Then the Garage App needed the catalogue. The quickest path was to read the incoming Authorization header and copy it to the Parts App request:
if (null !== $bearer = $this->token->get() ?? BonnerefToken::fromRequest($this->requests->getMainRequest())) {
$headers['Authorization'] = 'Bearer '.$bearer;
}
It works, and the Parts App even knows who the user is. But look at what it needed on both sides.
On the Parts App, the token’s audience is the Garage App’s MCP resource, not the Parts App. Since both apps check aud (the MCP authorization spec says servers “MUST validate that access tokens were issued specifically for them”), I had to add a dedicated firewall that also accepted someone else’s audiences:
# DEBT: mpa forwards its caller's bearer, so the GET catalogue routes mpa calls also accept mpa's audiences
CATALOGUE_PASSTHROUGH_AUDIENCES=<atelier client id>,https://garage.bonneref.fr/mcp,https://garage.soyuka.me/mcp
So the Parts App accepts tokens that were not issued for it. Any token minted for the Garage App (or its stage tunnel, or its dashboard) is now good on the Parts App too. That’s exactly the audience check we just put in place, with a hole in it.
On the Garage App it was worse. Agent turns run asynchronously in a Messenger worker, where there is no request to read a header from. So the token went into the queued message (RunAgentTurn::$accessToken) and a BonnerefToken service held it for the length of the turn. User bearer tokens sitting in a Postgres queue table, retried, dead-lettered, readable by whoever reads the failed transport.
The MCP spec has a name for this. In its security best practices, token passthrough is an anti-pattern: the server “MUST NOT accept or transit any other tokens”. The reasons listed are the ones above: the downstream API’s audience and rate limiting controls get bypassed, the audit trail says the user called the Parts App directly when it was the Garage App, and a stolen token is worth more because it works in more places.
The right way: Server to Server authentication#
The server-to-server hop is the server talking, so the server gets its own credential. That’s plain OAuth 2.0 client credentials (RFC 6749 §4.4): I created a Casdoor application mpa-service with the client credentials grant only, and the Garage App mints its token from the issuer’s discovered token_endpoint:
final readonly class BonnerefServiceToken
{
public const int EXPIRY_MARGIN = 300;
public function get(): string
{
return $this->cache->get($this->cacheKey(), $this->mint(...));
}
public function forget(): void
{
$this->cache->delete($this->cacheKey());
}
private function mint(ItemInterface $item): string
{
$data = $this->http->request('POST', $this->tokenEndpoint(), ['body' => [
'grant_type' => 'client_credentials',
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
]])->toArray();
$item->expiresAfter($data['expires_in'] - min(self::EXPIRY_MARGIN, intdiv($data['expires_in'], 2)));
return $data['access_token'];
}
}
The real class also turns Casdoor errors into transient or definitive upstream failures, without quoting the response body since it may echo the secret.
The token is cached in cache.app until a few minutes before it expires, so the worker, an HTTP request and an MCP tool call all share it. Nothing about the user’s token is queued anymore, RunAgentTurn simply lost its accessToken property.
Owner transfer#
With a service token, the Parts App knows that the Garage App is calling but not for which user. It still needs the user: quotas are per owner (plate lookups cost money upstream, 60 per hour per person), and they don’t work if every call comes from the same service account.
So we send the user in a header, next to the token:
$headers = [
'X-Bonneref-Owner' => $this->owner->require(),
'Authorization' => 'Bearer '.$this->token->get(),
];
$response = $this->http->request('GET', $path, ['query' => $query, 'headers' => $headers]);
if (401 === $response->getStatusCode()) {
$this->token->forget();
}
OwnerContext is the authenticated owner of the current tool call (the email claim, already validated by the Garage App’s own firewall). No owner in context, no request leaves. A 401 from the Parts App drops the cached token so the next call mints a fresh one, which covers a revoked credential or a key rotation.
I know what you’re thinking: a header anyone can set? It’s only trusted next to a token that proves the caller is the Garage App. That’s the whole point of the next part.
Trusting the owner header#
The Parts App’s catalogue firewall now uses a token handler that dispatches on azp, the client the token was issued to:
final readonly class ServiceTokenHandler implements AccessTokenHandlerInterface
{
public const string OWNER_HEADER = 'X-Bonneref-Owner';
public function getUserBadgeFrom(#[\SensitiveParameter] string $accessToken): UserBadge
{
$claims = $this->verifier->verify($accessToken);
if ($this->clientId !== ($claims['azp'] ?? null)) {
return $this->users->getUserBadgeFrom($accessToken);
}
$audience = $claims['aud'] ?? [];
if (!\in_array($this->clientId, \is_array($audience) ? $audience : [$audience], true)) {
throw $this->refused('The mpa service token was not issued for its own client.');
}
if ($this->subject !== ($claims['sub'] ?? null)) {
throw $this->refused('The token of the mpa service application is not its client credentials token.');
}
$owner = $this->requests->getCurrentRequest()?->headers->get(self::OWNER_HEADER);
if (null === $owner || \strlen($owner) > 254 || false === filter_var($owner, \FILTER_VALIDATE_EMAIL, \FILTER_FLAG_EMAIL_UNICODE)) {
throw $this->refused(\sprintf('The mpa service must name one owner email in %s.', self::OWNER_HEADER));
}
return new UserBadge($owner, null, ['email' => $owner]);
}
}
A few details that matter:
- Any token that is not the service’s goes to the regular user handler, with its organization pin and verified email check, and the header is never read. A user can’t name somebody else.
subis pinned too (admin/mpa-service). In Casdoor the same application can also issue user tokens through other grants, and those must not be mistaken for the client credentials one.- The service token is only known to this firewall:
GETon exactly the routes the Garage App calls, never/mcp. If the secret leaks, it opens a read-only catalogue, not the Parts App’s agent or its uploads. - The
UserBadgecarries the owner email, so the rate limiter keys on the person exactly like it does for a direct call.
And CATALOGUE_PASSTHROUGH_AUDIENCES is gone. The Parts App accepts tokens issued for itself (its own front and MCP resource) and one service identity, that’s it.
So, its just a fancy impersonation ?#
Somewhat, and it’s a deliberate tradeoff. The Parts App trusts the Garage App to tell the truth about the owner, since the Garage App already authenticated that user. The alternative is OAuth 2.0 token exchange (RFC 8693): the Garage App trades the user’s token for a new one with aud set to the Parts App and the user as subject. That’s the textbook answer for delegation and it keeps the user cryptographically in the token. Casdoor doesn’t do it, and for two apps I operate myself the trust relationship already exists, so a header behind a pinned service identity is honest about what it is. If the Parts App ever gets third-party consumers, token exchange is where I’d go.
What I would not do anymore is the passthrough. It’s the one that looks free, and it quietly pushes your audience check, your queue and your audit log in the wrong direction. When your MCP server calls something, it’s your server calling: give it its own credential, and say who it’s calling for.