Skip to content
Blog

Authenticating A2A Traffic Between Organizations

A practical guide to securing Agent2Agent (A2A) traffic across organizational boundaries: declaring securitySchemes in the Agent Card, OAuth 2.0 client credentials, extended cards, mid-task auth-required flows, and push-notification webhook security.

Published on • November 16, 2026

AI Assistant

Two organizations want their agents to collaborate, and the first question in the security review is never about model quality: who is calling, with what credential, and what are they allowed to do? If your A2A deployment answers “it’s an API key in a shared vault,” the integration stalls - and rightly so, because cross-organizational agent traffic is ordinary machine-to-machine traffic wearing a new badge: internet-reachable endpoints, autonomous callers, long-running tasks, and server-initiated webhooks.

The Agent2Agent (A2A) protocol anticipated this. It does not invent an auth system - the specification explicitly treats agents as “standard enterprise applications, relying on established web security practices” - but it gives authentication a discovery surface (the Agent Card’s securitySchemes), a negotiation surface (per-request credentials), and a task-level surface (TASK_STATE_AUTH_REQUIRED for mid-task authorization). In this tutorial you will wire all three, end to end.

Prerequisites

  • Python 3.11+ with httpx (pip install httpx)
  • An A2A server implementation (the Python SDK is pip install a2a-sdk) or the reference samples from the A2A repository
  • An OAuth 2.0 authorization server you control (Keycloak, Auth0, Entra ID) - or its test double for local work
  • Basic OAuth 2.0 client-credentials familiarity

The Three Authentication Surfaces in A2A

Before code, fix the model. A2A splits authentication into three moments, each with its own spec-mandated mechanism:

  1. Discovery time - the server declares how it wants to be authenticated in the public Agent Card via securitySchemes (apiKey, httpBearer, oauth2, openIdConnect, or mtls) plus a security requirement listing which scopes apply.
  2. Request time - the client acquires credentials out-of-band (A2A does not define a token endpoint flow beyond pointing at OAuth metadata) and presents them in protocol-appropriate headers on every JSON-RPC call.
  3. Task time - inside a running task, the agent may need further authorization (a token to call another API, human approval for a destructive action). The protocol represents this as the TASK_STATE_AUTH_REQUIRED task state: the agent pauses the task and asks the client to supply a credential.

A fourth surface - notification time - applies when the server calls your webhook: push notifications require the server to authenticate to your endpoint and you to verify what came back.

Step 1: Declare the Security Contract in the Card

Authentication starts with advertisement. A server declares its schemes and requirements in /.well-known/agent-card.json:

{
  "name": "Vendor B Freight Agent",
  "url": "https://agent.vendor-b.example/rpc",
  "capabilities": {"extendedAgentCard": true, "pushNotifications": true},
  "securitySchemes": {
    "partnerOAuth": {
      "oauth2SecurityScheme": {
        "flows": {
          "clientCredentials": {
            "tokenUrl": "https://auth.vendor-b.example/oauth/token",
            "scopes": {
              "quote:read": "Read quotes",
              "quote:write": "Create quotes"
            }
          }
        }
      }
    },
    "serviceKey": {
      "apiKeySecurityScheme": {
        "in": "HEADER",
        "name": "X-Api-Key",
        "description": "Legacy partner integration only"
      }
    }
  },
  "security": [{"partnerOAuth": ["quote:write"]}],
  "skills": [
    {"id": "quote-ocean", "name": "Ocean Freight Quote", "description": "..."}
  ]
}

Two design points that matter in a multi-organization setting:

  • Multiple schemes are allowed; the security array states the default requirement. Prefer listing OAuth 2.0 as the default and keeping an API key scheme only for legacy partners you cannot migrate yet. The card is where you encode that policy.
  • Scheme discovery replaces out-of-band docs. A client that reads the card knows the token URL, the scopes, and the header name. A wiki page does not get a vote.

If the public card should stay a thin discovery surface, flip on capabilities.extendedAgentCard: true and publish the full contract - extra skills, internal endpoints, stricter requirements - only to authenticated callers (Step 4).

Step 2: Client Credentials, the Cross-Org Default

For server-to-server agent traffic, OAuth 2.0 client credentials is the right default: no user involved, short-lived tokens, per-partner scoping, revocable. The client reads the scheme from the card, fetches a token, and attaches it:

import time

import httpx

class PartnerAuth:
    def __init__(self, token_url: str, client_id: str, client_secret: str,
                 scopes: list[str]):
        self._token_url = token_url
        self._creds = {"client_id": client_id, "client_secret": client_secret,
                       "grant_type": "client_credentials",
                       "scope": " ".join(scopes)}
        self._token: str | None = None
        self._expires_at: float = 0.0

    async def token(self, client: httpx.AsyncClient) -> str:
        if self._token and time.monotonic() < self._expires_at - 30:
            return self._token
        r = await client.post(self._token_url, data=self._creds, timeout=15)
        r.raise_for_status()
        body = r.json()
        self._token = body["access_token"]
        self._expires_at = time.monotonic() + float(body.get("expires_in", 3600))
        return self._token

Details that survive contact with production:

  • Refresh proactively (the -30 second skew) so a token expiring mid-SendMessage does not fail a long task.
  • Scope per partner and per skill. The agent whose only job is creating quotes gets quote:write, not *. Scope reduction is the cheapest blast-radius control you have.
  • Rotate credentials on an agreed schedule and treat the card’s tokenUrl as configuration you re-read, not a constant baked into builds.

Step 3: Present Credentials on Every Request

With the token in hand, every JSON-RPC call carries the standard bearer header:

async def send_to_agent(rpc_url: str, auth: PartnerAuth, text: str) -> dict:
    payload = {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "SendMessage",
        "params": {"message": {"role": "ROLE_USER",
                                "parts": [{"type": "text", "text": text}]}},
    }
    async with httpx.AsyncClient(timeout=60) as client:
        token = await auth.token(client)
        r = await client.post(rpc_url, json=payload,
                              headers={"Authorization": f"Bearer {token}"})
        if r.status_code == 401:
            # token revoked or clock skew: force refresh once, then give up
            auth._token = None
            token = await auth.token(client)
            r = await client.post(rpc_url, json=payload,
                                  headers={"Authorization": f"Bearer {token}"})
        r.raise_for_status()
        return r.json()

On the server side, responsibilities per the specification are explicit: authenticate every incoming request against the declared requirements, return binding-appropriate challenge information on rejection (HTTP 401 with WWW-Authenticate for the JSON-RPC binding), and after authentication, authorize based on identity - skill requested, action attempted, OAuth scopes. A2A keeps identity at the protocol layer; your application code never has to parse “who” out of a message body.

Transport is non-negotiable: production deployments MUST use encrypted transport (HTTPS), clients SHOULD verify the server’s TLS certificate against trusted CAs, and mTLS (mtlsSecurityScheme) is a first-class scheme for organizations that already operate a certificate hierarchy - many regulated pairs use mTLS for the channel and OAuth for the authorization.

Step 4: Extended Cards - Authenticate Before You Learn the Full Contract

Some capabilities should be invisible to strangers. With capabilities.extendedAgentCard: true, the public card advertises the minimum; authenticated clients fetch the full card:

async def fetch_extended_card(rpc_url: str, auth: PartnerAuth) -> dict:
    payload = {"jsonrpc": "2.0", "id": 1,
               "method": "GetExtendedAgentCard", "params": {}}
    async with httpx.AsyncClient(timeout=30) as client:
        token = await auth.token(client)
        r = await client.post(rpc_url, json=payload,
                              headers={"Authorization": f"Bearer {token}"})
        r.raise_for_status()
        return r.json()["result"]

Two rules from the spec worth internalizing:

  • If the card does not declare extendedAgentCard, calls to it MUST fail with UnsupportedOperationError; if declared but not configured, ExtendedAgentCardNotConfiguredError. Do not probe blindly - read the flag.
  • Clients SHOULD replace their cached public card with the authenticated version for the duration of the session (or until version changes). The extended card is the authoritative contract for that relationship.

Step 5: Mid-Task Authorization with auth-required

Request-time auth covers calling the agent. It does not cover the agent needing your authorization to finish the work - to call your API, move your money, or touch a resource you own. A2A models this as a task-level state machine transition:

submitted -> working -> auth-required -> working -> completed
                           ^
                           client supplies the credential in-band

When an agent needs authorization it cannot obtain itself, it sets TASK_STATE_AUTH_REQUIRED (with the status message describing what is needed) and the client has two options:

  1. Supply the credential in a follow-up message on the same task - thread taskId and contextId exactly as you would for input-required:
async def supply_credential(rpc_url: str, auth: PartnerAuth,
                            task_id: str, context_id: str, credential: str) -> dict:
    payload = {
        "jsonrpc": "2.0",
        "id": 9,
        "method": "SendMessage",
        "params": {
            "message": {
                "role": "ROLE_USER",
                "task_id": task_id,
                "context_id": context_id,
                "parts": [{"type": "text", "text": credential}],
            }
        },
    }
    async with httpx.AsyncClient(timeout=60) as client:
        token = await auth.token(client)
        r = await client.post(rpc_url, json=payload,
                              headers={"Authorization": f"Bearer {token}"})
        r.raise_for_status()
        return r.json()["result"]
  1. Deliver the credential out-of-band (a separate secure channel). The specification permits the agent to keep active response streams open and resume processing once the credential arrives, without requiring a follow-up message.

In practice, option 1 keeps the audit trail on the task, which is what security reviewers want: every authorization event is a message in the task history, tied to taskId.

Step 6: Secure the Webhook Direction Too

When the card declares capabilities.pushNotifications: true, the server will make outbound HTTP calls to your endpoint - the exact shape SSRF and spoofing exploits are built from. The specification’s requirements split by direction:

Servers (outbound):

  • Do not POST to arbitrary client-supplied URLs: enforce domain allowlists, ownership verification, and egress controls.
  • Authenticate to the webhook as configured - OAuth bearer token, API key, HMAC signature, or mutual TLS (AuthenticationInfo on the push config tells the server which scheme to use).

Receivers (inbound):

  • Verify the notification actually came from your partner server. The reference flow is asymmetric: the server signs a JWT (iss, aud, iat, exp, jti, plus the task id) with its private key and publishes keys at a JWKS endpoint; you resolve the key from the JWT header’s kid, verify, and validate claims.
  • Reject stale timestamps and replayed nonces/jti values.
  • After verification, do not trust the notification body - use it only as a trigger to GetTask over an authenticated channel and read the authoritative state.
def verify_notification(jwt_str: str, jwks: dict, audience: str,
                        seen_jti: set[str], max_age_s: int = 300) -> dict:
    header, claims, signature = parse_and_verify_jwt(jwt_str, jwks)  # JWS over the payload
    now = time.time()
    assert claims["aud"] == audience
    assert abs(now - claims["iat"]) < max_age_s
    if claims["jti"] in seen_jti:
        raise ValueError("replay detected")
    seen_jti.add(claims["jti"])
    return claims

A Server-Side Enforcement Example

Declarations are worthless without enforcement. In the Python SDK’s server stack, authentication hooks sit in front of request handling; conceptually every request passes one gate:

async def enforce_auth(req: dict, declared_schemes: dict) -> Principal:
    auth_header = current_http_headers.get("authorization", "")
    if not auth_header.startswith("Bearer "):
        raise AuthenticationError("missing bearer token")  # -> JSON-RPC auth error
    principal = await introspect_or_verify(auth_header.removeprefix("Bearer "))
    required = required_scopes_for(req["method"], req["params"])
    missing = required - set(principal.scopes)
    if missing:
        raise AuthorizationError(f"missing scopes: {sorted(missing)}")
    return principal

Fail closed, map rejections to the binding’s authentication error shape with challenge information, and log taskId + principal together so cross-org incidents can be reconciled on both sides.

Putting It All Together

A production-grade cross-org auth loop:

  1. Read the partner’s card; parse securitySchemes and security.
  2. Obtain client-credentials tokens per the declared scheme; cache with proactive refresh.
  3. Attach Authorization on every JSON-RPC call; verify TLS server identity.
  4. Fetch the extended card after authentication and cache it per the spec’s replacement rule.
  5. Handle TASK_STATE_AUTH_REQUIRED by continuing the same task with the requested credential.
  6. For push notifications: allowlist and authenticate outbound, verify JWT/JWKS and reject replays inbound.
  7. Rotate per-partner credentials on schedule; audit every task against its principal.

Conclusion & Next Steps

A2A’s authentication story is refreshingly conventional - TLS, OAuth 2.0, API keys, mTLS - and genuinely well-surfaced: the card makes the security contract discoverable, the request layer makes it enforceable, and auth-required makes mid-task authorization a normal branch instead of an error. The cross-organizational win is that neither side has to document their auth in a PDF: it is all in the card, machine-readable and versioned.

Homework:

  • Author securitySchemes for one internal agent and verify a fresh client can authenticate with nothing but the card.
  • Implement the auth-required round trip in a test and assert the credential appears in the task history.
  • Add JWKS-based push-notification verification with a replay cache and test a replayed JWT is rejected.

Sources: A2A Protocol repository (google/A2A), A2A Protocol Specification - Security Objects and Authentication, A2A Enterprise Features