😇

A2A での認証認可を理解する

に公開
2026/08/28

概要

Agent2Agent Protocol(以下A2A) は現在 Linux Foundation 傘下の AI Agent 同士のコミュニケーションを可能にする Open な Protocol です。

https://github.com/a2aproject/A2A

ざっくり言えば、AI Agent が外部で公開されていた際に、その AI Agent と自分が作成した AI Agent が協調して動くための仕様、例えば通信方法や要件などを決めたものです。

A2A を使うと、マルチエージェントのような仕組みを作ろうとしたときに、様々な言語やフレームワーク、実行基盤で実装されていても協調ができることになります。また、外部のエージェントが何で動いているかは知らずに利用ができます。

A2A の仕様については以下にまとまっています。

https://a2a-protocol.org/latest/specification/

今回はその仕様の中で認証認可についてまとめます。

実装したコードは以下においております。

https://github.com/SatohJohn/a2a-auth-instruction?tab=readme-ov-file

想定読者

  • A2A について調べている人
  • ADK で AI Agent を作ったことがある人
  • Multi Agent なシステムを作りたい人
  • Security について考えている人

得られること

  • Agent を使った認証について勘所を掴める

    • 例については、まだ未対応なライブラリで無理やり対応している点もあるため利用するうえでは注意を払ってください。

環境

名前 version
A2A specification v0.3.0 (DRAFT v1.0)
google-adk[a2a] 1.21.0
google-auth 2.45.0

いきなりまとめ

認証認可の流れ

A2A における認証認可は、以下のように定義されています。

https://a2a-protocol.org/latest/specification/#7-authentication-and-authorization

認証に関しては securityScheme での説明されている部分が一番わかり易いかと思います。

今回は Google ID で OIDC を使う処理の流れは以下のようになります。

この場合は 例えば、AWS 上で動くエージェントが、AWS の署名付きリクエストを Google の STS に送り、Google Cloud のリソースにアクセスできるトークンと交換する流れに近いです。

実装例

FastAPI で A2A の上記の流れを簡易的に実際に書いてみます。

実装としては以下の3つがイメージ近いです。

main.py
SECRET_KEY = "dummy-secret-key-for-demo"  # 署名用鍵(デモ用)
AGENT_CARD_ENDPOINT = "/.well-known/agent-card.json"
RPC_ENDPOINT = "/agent/rpc"
server.py
import jwt
from fastapi import FastAPI, Header, HTTPException, Request
from typing import Optional, Dict

from main import AGENT_CARD_ENDPOINT, RPC_ENDPOINT, SECRET_KEY

app = FastAPI(title="Remote Agent Service")

# 1. Discovery: agent-card.json を公開するエンドポイント
@app.get(AGENT_CARD_ENDPOINT)
def get_agent_card():
    return {
        "name": "WeatherAgent",
        "description": "天候情報を提供するエージェント",
        "version": "1.0.0",
        "securitySchemes": {
            "google_oidc": {
                "type": "openIdConnect",
                "openIdConnectUrl": "https://accounts.google.com/.well-known/openid-configuration",
                "description": "Use Workload Identity to obtain a Google ID Token."
            }
        },
        "capabilities": {
            "streaming": False,
            "pushNotifications": False
        },
        "defaultInputModes": ["text/plain"],
        "defaultOutputModes": ["text/plain"],
        "skills": [
            {
                "id": "get_weather",
                "name": "get_weather",
                "description": "指定された場所の天候情報を取得します。",
                "tags": ["weather"]
            }
        ]
    }

# 5. Validation: トークンの検証ロジック
def validate_token(auth_header: str) -> Dict:
    if not auth_header.startswith("Bearer "):
        raise HTTPException(status_code=401, detail="Invalid auth scheme")
    
    token = auth_header.split(" ")[1]
    
    try:
        # ここで署名、有効期限(exp)、発行者(iss)、対象者(aud)を検証
        # ※デモのため HS256 と固定鍵を使用していますが、実際は公開鍵基盤(JWKS)を使います
        payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"], audience="remote-agent-service")
        return payload
    except jwt.ExpiredSignatureError:
        raise HTTPException(status_code=401, detail="Token expired")
    except jwt.InvalidTokenError:
        raise HTTPException(status_code=401, detail="Invalid token")

# Task Execution の受け口 (JSON-RPC)
@app.post(RPC_ENDPOINT)
async def json_rpc_endpoint(request: Request, authorization: Optional[str] = Header(None)):
    if not authorization:
        raise HTTPException(status_code=401, detail="Authorization header missing")
    
    # 5. Validation の実行
    user_info = validate_token(authorization)
    print(f"[Server] Token Validated. User: {user_info['sub']}")

    # JSON-RPC リクエストの解析
    body = await request.json()
    method = body.get("method")
    params = body.get("params", {})
    req_id = body.get("id")

    # タスクの実行 (擬似ロジック)
    result = None
    if method == "get_weather":
        location = params.get("location", "Tokyo")
        result = f"The weather in {location} is Sunny."
    else:
        return {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": req_id}

    return {"jsonrpc": "2.0", "result": result, "id": req_id}

get_agent_card で AgentCard を組み立てます。

上記の例だと、必須項目と securitySchemes だけを利用しています。

client.py
from main import SECRET_KEY, AGENT_CARD_ENDPOINT, RPC_ENDPOINT
import time
import jwt
import requests

REMOTE_AGENT_URL = "http://localhost:8000"

class ClientAgent:
    def __init__(self, remote_url):
        self.remote_url = remote_url
        self.auth_config = None

    def run_flow(self):
        print("\n--- Agent2Agent Flow Start ---")
        
        # Step 1: Discovery
        self._discovery()
        
        # Step 2: Negotiation
        auth_scheme = self._negotiation()
        
        # Step 3: Token Acquisition
        token = self._token_acquisition(auth_scheme)
        
        # Step 4: Task Execution
        self._task_execution(token)

    def _discovery(self):
        print("[1. Discovery] Fetching agent-card.json...")
        resp = requests.get(f"{self.remote_url}{AGENT_CARD_ENDPOINT}")
        self.agent_card = resp.json()
        print(f"   -> Found Agent: {self.agent_card['name']}")

    def _negotiation(self):
        print("[2. Negotiation] Analyzing securitySchemes...")
        schemes = self.agent_card.get("securitySchemes", {})
        
        # 自身が対応可能な認証方式を選択 (ここでは 'google_oidc' を探す)
        if "google_oidc" in schemes:
            print("   -> Selected Auth Scheme: Google OIDC")
            return schemes["google_oidc"]
        else:
            raise Exception("No supported authentication scheme found.")

    def _token_acquisition(self, auth_scheme):
        print("[3. Token Acquisition] Exchanging credentials for token...")
        
        response = requests.get(auth_scheme["openIdConnectUrl"])  # OIDC メタデータ取得

        # --- OAuth 2.0 Token Exchange (RFC 8693) の擬似実装 ---
        # 実際には 現在の認証情報を使い、「相手のエージェント(audience)」向けのトークンを要求(作成)します。
        
        current_time = int(time.time())
        mock_token_payload = {
            "iss": response.json()["issuer"],
            "sub": "client-agent-001",          # 自身のID
            "aud": "remote-agent-service",      # 相手のエージェントID (Token Exchangeで指定)
            "iat": current_time,
            "exp": current_time + 3600,         # 1時間有効
            "scope": "agent.read"
        }
        
        # トークン生成(本来はIdPが行う処理)
        token = jwt.encode(mock_token_payload, SECRET_KEY, algorithm="HS256")
        print(f"   -> Token Acquired: {token[:15]}... (truncated)")
        return token

    def _task_execution(self, token):
        print("[4. Task Execution] Sending JSON-RPC request...")
        
        headers = {
            "Authorization": f"Bearer {token}",  # Bearer ヘッダーの付与
            "Content-Type": "application/json"
        }
        
        payload = {
            "jsonrpc": "2.0",
            "method": "get_weather",
            "params": {"location": "Shibuya"},
            "id": 1
        }
        
        resp = requests.post(f"{self.remote_url}{RPC_ENDPOINT}", json=payload, headers=headers)
        
        if resp.status_code == 200:
            print(f"   -> Response: {resp.json()}")
        else:
            print(f"   -> Error: {resp.status_code} {resp.text}")

if __name__ == "__main__":
    # クライアントフローの実行
    client = ClientAgent(REMOTE_AGENT_URL)
    client.run_flow()

_negotiation でどの sheme を利用するかを決定します。

_task_execution の処理が実際に AI Agent として通信を行います。

Agent Development Kit(ADK) + Google Cloud で実装する

上記は AI Agent ではないので、イメージつきにくいかも知れません。

そのため、ADK を使った AI Agent ではどうやって実装するのか。またユーザからの入力の場合どうなるのかについて考えていきたいと思います。

以下のような構成を考えます

.
├── README.md
├── agents
│   ├── client
│   │   └── agent.py
│   └── server
│       ├── agent.json
│       └── agent.py
├── pyproject.toml
└── uv.lock

client と server は以下にあるものを流用してきます。

https://github.com/google/adk-python/tree/main/contributing/samples/a2a_root

そのためコード自体の重要な部分だけ大まかな部分だけ載せます。

client/agent.py
prime_agent = RemoteA2aAgent(
    name="prime_agent",
    description="Agent that handles checking if numbers are prime.",
    agent_card=(
        f"http://localhost:8001/a2a/server{AGENT_CARD_WELL_KNOWN_PATH}" # リモートエージェントの AgentCard の提供場所
    ),
)

root_agent = Agent(
    model="gemini-2.5-flash",
    name="root_agent",
    sub_agents=[roll_agent, prime_agent],
    tools=[example_tool],
    ...
)
server/agent.py
root_agent = Agent(
    model='gemini-2.5-flash',
    name='check_prime_agent',
    ...
)
server/agent.json
{
    "capabilities": {},
    "defaultInputModes": [
        "text/plain"
    ],
    "defaultOutputModes": [
        "application/json"
    ],
    ...
    "url": "http://localhost:8001/a2a/server",
    "version": "1.0.0"
}

ADK で a2a のリモートエージェントを提供する方法としては2つありますが、今回は adk api_server --a2a のパターンを使います。

リモートエージェント用の API 起動
adk api_server --a2a --port 8001 agents
クライアントエージェントの用の画面起動
adk web agents

http://localhost:8000 で立ち上がっている web ページにてクライアントエージェントに対して Roll a 10-sided die and check if it's prime. のように投げてみると以下のように返答があるはずです。

ここまでで一旦の ADK の A2A 通信をする Agent は作成できました。

A2A の認証をつける

リモートエージェントに securitySchemes をもたせます。今回は、Google を IdP を利用するものとします。

そのため、Google Cloud にて以下のように OAuth クライアント ID を作っておきます。

ここで取得した Client ID, Client Secret を環境変数にセットして利用します。

ユーザの認証情報を扱うため、ユーザ委譲としてリモートエージェントがかなり強めの権限を持つことができるため、注意が必要です(ただ、ユーザのカレンダーや情報を用いるためには必要な形ではあります)。

上記のシーケンスにおける認証情報を含んだ json は以下のようになります。

server/agent.json
{
    ...
    "securitySchemes": {
        "agent_auth": {
            "type": "oauth2",
            "flows": {
                "authorizationCode": {
                    "authorizationUrl": "https://accounts.google.com/o/oauth2/v2/auth",
                    "tokenUrl": "https://oauth2.googleapis.com/token",
                    "scopes": {
                        "openid": "ユーザーの識別子(sub)を取得",
                        "email": "メールアドレスを取得",
                        "profile": "プロフィール情報を取得"
                    }
                }
            }
        }
    },
    ...
}

実際にこれを使った処理を書いていきます。

クライアントエージェント

クライアントエージェントにおいては adk web では確認ができないため、FastAPI と自前のチャット画面を用意します。面倒なので Gemini に作ってもらいます。

FastAPI としては以下のように記載します。

トップページ(/)にアクセスすると idtoken がない場合に認証が走るようになっています。

認証に使う情報は AgentCard から取得しています。ただ、一旦 type=oauth2 のものだけを実装しています。

戻ってきた際に /callback にアクセスが来るのでその際に idtoken を保存します。

app.py
import os
import requests
from urllib.parse import urlencode
from pydantic import BaseModel
import uvicorn
from fastapi import FastAPI, Request, status
from fastapi.responses import RedirectResponse
from fastapi.templating import Jinja2Templates
from agent import root_agent as agent, prime_agent
from google.adk.sessions import InMemorySessionService
from google.adk.runners import Runner
from google.adk.agents.run_config import RunConfig
from google.genai import types
from environs import Env
from google.adk.agents.remote_a2a_agent import RemoteA2aAgent
from a2a.types import OAuth2SecurityScheme

env = Env()
env.read_env()

app = FastAPI()

class Message(BaseModel):
    text: str

session_service = InMemorySessionService()
ID_TOKEN_COOKIE_NAME = "id_token"

APP_NAME = "a2a_sample_app"
USER_ID = "user_1"
SESSION_ID = "session_001" # Using a fixed ID for simplicity
REDIRECT_URI = "http://localhost:8080/callback"

session = session_service.create_session_sync(
    app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID
)
runner = Runner(agent=agent, app_name=APP_NAME,
                session_service=session_service)

# テンプレートエンジンの設定
templates = Jinja2Templates(directory="templates")

async def get_auth_config():
    """Fetches the OAuth2 authentication flow configuration from the sub-agent's agent card. 複数ある場合には未対応"""
    auth_flow = {}
    for sub_agent in agent.sub_agents:
        # sub agent をあさってやる
        if not isinstance(sub_agent, RemoteA2aAgent):
            continue
        # 先に実施しておかないと agentcard の中身がないため無理やり実施
        await sub_agent._ensure_resolved()
        if prime_agent._agent_card is not None and prime_agent._agent_card.security_schemes:
            for scheme_name in prime_agent._agent_card.security_schemes:
                d = prime_agent._agent_card.security_schemes[scheme_name]
                if isinstance(d.root, OAuth2SecurityScheme):
                    print(f"Scheme: {scheme_name}, Type: {d.root.type}")
                    if d.root.flows.authorization_code:
                        print(d.root.flows.authorization_code.authorization_url)
                        auth_flow = {
                            "authorization_url": d.root.flows.authorization_code.authorization_url,
                            "token_url": d.root.flows.authorization_code.token_url,
                            "scopes": d.root.flows.authorization_code.scopes,
                        }
    return auth_flow

@app.get("/")
async def index(request: Request):
    auth_flow = await get_auth_config()
    if auth_flow == {} or request.cookies.get(ID_TOKEN_COOKIE_NAME):
        print("id token found in cookies.")
        return templates.TemplateResponse("index.html", {"request": request})

    scopes = auth_flow["scopes"]
    if isinstance(scopes, dict):
        scopes = " ".join(scopes.keys())
    elif isinstance(scopes, list):
        scopes = " ".join(scopes)
    
    params = {
        "client_id": os.environ.get("GOOGLE_CLIENT_ID", "YOUR_CLIENT_ID"),
        "redirect_uri": REDIRECT_URI,
        "response_type": "code",
        "scope": scopes,
        "access_type": "offline",
        "state": "state_parameter_passthrough_value",
        "include_granted_scopes": "true",
    }
    auth_url = f"{auth_flow['authorization_url']}?{urlencode(params)}"
    return RedirectResponse(url=auth_url)
    
@app.get("/callback")
async def callback(request: Request):
    code = request.query_params.get("code")
    state = request.query_params.get("state")
    
    auth_flow = await get_auth_config()
    if not auth_flow:
        return {"error": "No auth flow configuration found."}
    
    token_url = auth_flow.get("token_url")
    if not token_url:
        return {"error": "No token URL found in auth flow."}
    
    data = {
        "client_id": os.environ.get("GOOGLE_CLIENT_ID", "YOUR_CLIENT_ID"),
        "client_secret": os.environ.get("GOOGLE_CLIENT_SECRET", "YOUR_CLIENT_SECRET"),
        "code": code,
        "grant_type": "authorization_code",
        "redirect_uri": REDIRECT_URI,
    }
    
    response = requests.post(token_url, data=data)
    if response.status_code != 200:
        return {"error": "Failed to obtain tokens.", "details": response.text}
    token_response = response.json()
    redirect_resp = RedirectResponse(url="/", status_code=status.HTTP_302_FOUND)
    redirect_resp.set_cookie(
        key=ID_TOKEN_COOKIE_NAME,
        value=token_response["id_token"],
        httponly=True,
        secure=False,
        samesite="lax",
        max_age=3600, # 実際はリフレッシュトークンの有効期限に合わせる
        path="/"
    )
    return redirect_resp

@app.post("/call")
async def call(message: Message, request: Request):
    content = types.Content(role="user", parts=[types.Part(text=message.text)])
    final_response_text = "Sorry, I couldn't process that."

    id_token = request.cookies.get(ID_TOKEN_COOKIE_NAME)
    run_config = None
    # A2A でのメタデータを送るために custom_metadata にいれてやる
    if id_token:
        run_config = RunConfig(custom_metadata={"id_token": id_token})

    try: 
        async for event in runner.run_async(user_id=USER_ID,
                                                 session_id=SESSION_ID,
                                                 new_message=content,
                                                 run_config=run_config):
            print(f"Event ID: {event.id}, Author: {event.author}")

            if event.is_final_response():
                if (
                    event.content
                    and event.content.parts
                    and event.content.parts[0].text
                ):
                    final_response_text = event.content.parts[0].text.strip()
                    print(f"==> Final Agent Response: {final_response_text}")
                else:
                    print(
                        "==> Final Agent Response: [No text content in final event]")
    
    except Exception as e:
        print(f"ERROR during agent run: {e}")
        return {"response": f"Error: {str(e)}"}
    
    return {"response": final_response_text}

ここまではToolを使った普通の認証と変わらない多くは変わらないと思います。

ただ、Runner を作り RunConfig に custom_metadata を使い context に入れています。これにより後続で利用できるようになります。

agent.py
def auth_provider(context: InvocationContext, message: A2AMessage) -> Dict[str, Any]:
    if context.run_config and context.run_config.custom_metadata:
        # context に入っている token を引っ張ってきて a2a_request_metadata に入るように調整をする
        token = context.run_config.custom_metadata.get("id_token")
        if token:
            return {"headers": {"Authorization": f"Bearer {token}"}}
    return {}

prime_agent = RemoteA2aAgent(
    name="prime_agent",
    description="This agent cannot be used without authentication. Agent that handles checking if numbers are prime.",
    agent_card=(
        f"http://localhost:8001/a2a/server{AGENT_CARD_WELL_KNOWN_PATH}"
    ),
    a2a_request_meta_provider=auth_provider,
)

RemoteA2aAgent では a2a_request_meta_provider にて先程 context につめたものを取ってきて入れています。これにより A2A 通信時にメッセージにメタデータで送られます。

https://github.com/google/adk-python/blob/07bb1647588a781e701257c4c379736537029ea0/src/google/adk/agents/remote_a2a_agent.py#L539-L546

ここまで作成したものを以下のように動かします

uvicorn app:app --port=8080

リモートエージェント

リモートエージェントでは run_config を見れるようにするために before_〇〇_callback を利用します。今回は before_agent_callback

これにより先程送信に使われたメタデータが参照できます。

agent.py
def check_if_agent_should_run(callback_context: CallbackContext) -> Optional[types.Content]:
    agent_name = callback_context.agent_name
    current_state = callback_context.state.to_dict()
    if callback_context.run_config is None:
        return types.Content(
            parts=[types.Part(text=f"Error: Agent {agent_name} requires authentication (headers missing).")],
            role="model"
        )

    custom_metadata = callback_context.run_config.custom_metadata or {}
    print(f"[Callback] metadata is {custom_metadata}.")

    # Check for A2A headers in custom_metadata
    if "a2a_metadata" not in custom_metadata and "headers" not in custom_metadata["a2a_metadata"]:
        print(f"[Callback] Auth Error: 'a2a:headers' not found in custom_metadata.")
        return types.Content(
            parts=[types.Part(text=f"Error: Agent {agent_name} requires authentication (headers missing).")],
            role="model"
        )
    list = custom_metadata["a2a_metadata"]["headers"].get("Authorization", "").split(" ")
    if len(list) != 2 or list[0] != "Bearer" or not list[1]:
        print(f"[Callback] Auth Error: Invalid Authorization header format.")
        return types.Content(
            parts=[types.Part(text=f"Error: Agent {agent_name} requires valid authentication (invalid token).")],
            role="model"
        )
    token = list[1]
    
    try:
        id_info = id_token.verify_oauth2_token(
            token, 
            requests.Request(), 
            audience=os.environ.get("GOOGLE_CLIENT_ID")
        )
        print(f"[Callback] Token verified successfully. User: {id_info.get('email')}")
    except ValueError as e:
        print(f"[Callback] Token verification failed: {e}")
        return types.Content(
            parts=[types.Part(text=f"Error: Agent {agent_name} authentication failed: Invalid token.")],
            role="model"
        )
    except Exception as e:
        print(f"[Callback] Token verification error: {e}")
        return types.Content(
            parts=[types.Part(text=f"Error: Agent {agent_name} authentication error.")],
            role="model"
        )

    print(f"[Callback] State condition not met: Proceeding with agent {agent_name}.")
    return None


root_agent = Agent(
    model='gemini-2.5-flash',
    name='check_prime_agent',
    ...
    before_agent_callback=check_if_agent_should_run,
)

この callback の中で実際に token に問題があるかどうかを判断します。

問題なければ、そのまま処理が実行されて動く形です。

こちらの動かし方は前回と同じ様に動かします。

adk api_server --a2a --port 8001 agents

まとめ

A2A の認証認可の流れと実装についてまとめてみました。

やってみると色々勉強にもなります。また Gemini と壁打ちしながらだと思考整理が進みやすいと思います。

ADK を使ったあたりはかなり無理矢理やっていると思います。

そのため、今後 ADK にて a2a の securitySchemes をみて動く実装が入ってくればここの処理はいらなくなるでしょう。

とはいえ、認証認可の流れを理解するうえでは十分ですし、しばらくは token は a2a_request_meta_provider + before_〇〇_callback でやるしかないのかなとも思いました。実装的にもソレぐらいしか見当たらない。。。

参考

https://github.com/a2aproject/A2A

https://auth0.com/blog/auth0-google-a2a/

https://github.com/google/adk-python/tree/main/contributing/samples/a2a_auth

Discussion