在AWS上使用X.509 PKI保护AI智能体身份
Securing AI agent identity with X.509 PKI on AWS
AWS Machine Learning Blog发布了一篇教程,介绍了如何使用X.509 PKI在AWS上保护AI智能体身份,包括使用Keyfactor EJBCA和AWS服务实现安全机制。
When AI agents access databases, APIs, and sensitive business operations, establishing cryptographic identity through X.509 public key infrastructure (PKI) becomes a critical requirement. The core challenge is proving which agent made a request, preventing forgery between agents, and confirming that each agent acts only on behalf of an authorized user. Traditional approaches such as sharing API keys between components or passing OAuth tokens through agent chains fall short of the zero-trust requirements that enterprise deployments demand.
Multi-agent AI frameworks increasingly use the Model Context Protocol (MCP) to connect agents to external tools and data sources. MCP defines how a large language model (LLM)-powered agent invokes tools such as database queries or email operations. However, MCP has no built-in authentication standard. It is transport-agnostic by design. This creates a critical gap: Without proper identity mechanisms, any component could impersonate an agent, replay intercepted credentials, or invoke tools without authorization.
In this post, we show you how to address this gap using Keyfactor EJBCA combined with AWS services. EJBCA is a PKI platform that supports high-availability deployment, REST API automation, and Online Certificate Status Protocol (OCSP) validation. The reference architecture uses four complementary security mechanisms. First, signed request envelopes provide cryptographic proof-of-possession on every agent call. Second, user-signed delegation assertions authorize agents without sharing credentials. Third, RFC 8693 audience-scoped tokens limit the scope of exposure from any single token disclosure. Fourth, real-time OCSP revocation checking propagates credential changes immediately across all agents.
The solution uses Amazon Bedrock for LLM inference through the AWS Strands Agents SDK. While this reference architecture uses a database as the protected resource, the same authentication pattern applies to any MCP-compatible tool server. Complete source code for all examples is available in the accompanying GitHub repository.
About Keyfactor EJBCA
Keyfactor provides a widely adopted machine identity management platform used by more than 1,500 enterprise customers worldwide, according to Keyfactor. These organizations span financial services, healthcare, manufacturing, and government. Keyfactor helps organizations establish and maintain cryptographic trust through certificate lifecycle management, PKI operations, and machine identity governance.
EJBCA Enterprise is Keyfactor’s Certificate Authority (CA) and PKI platform, designed for high-availability deployment and REST API automation. Available as an enterprise product, EJBCA provides X.509 certificate issuance, OCSP validation, certificate revocation list (CRL) distribution, and full certificate lifecycle management through both a web console and REST API. EJBCA supports deployment on-premises, in containers, or on Amazon Elastic Compute Cloud (Amazon EC2).
The partnership between AWS and Keyfactor brings together AWS managed services (Amazon Bedrock, AWS Secrets Manager, Amazon Relational Database Service (Amazon RDS)) with PKI infrastructure that supports certificate lifecycle management, automated enrollment, and real-time revocation. This combination addresses a gap in the AI agent ecosystem. While AWS provides the compute, storage, and AI inference layers, Keyfactor provides the cryptographic identity layer that binds agents to verifiable, revocable, short-lived credentials. This joint reference architecture, developed collaboratively by the AWS and Keyfactor engineering teams, demonstrates how to integrate these technologies. You can adapt the patterns shown here to your own multi-agent deployments.
Solution overview
The architecture implements three authentication layers, each addressing a different trust boundary in the agent communication chain. These three layers use the four security mechanisms introduced earlier: signed envelopes for proof-of-possession, delegation assertions for credential-free authorization, audience-scoped tokens for exposure limitation, and OCSP for real-time revocation. The mechanisms combine across layers as shown in the following table.
| Layer | Trust boundary | Mechanism | Validates |
| 1. User Auth | User to System | OAuth + X.509 cert + delegation minting | User identity, credential binding |
| 2. Agent-to-Agent | Agent to Agent | Signed envelopes (PoP + nonce + timestamp) | Caller identity, request freshness, no replay |
| 3. MCP Auth | Agent to Tool Server | Scoped token + envelope + delegation | All identities, authorization chain, OCSP |
Figure 1 shows the three authentication layers and how credentials flow between the user, agents, and the MCP tool server. The diagram illustrates the separation between user credentials (which stay in the login flow), agent credentials (scoped per agent), and the delegation chain that connects them.
Figure 1: Three-layer PKI authentication architecture for AI agent systems on AWS
Figure 2 illustrates the detailed traffic flow during a typical user session. It shows the sequence of authentication steps from login through certificate issuance, agent delegation, tool invocation, and session cleanup.
Figure 2: Authentication traffic flow from user login through agent delegation, tool invocation, and session cleanup
AWS services used
The following AWS services form the foundation of the reference architecture.
| Service | Purpose |
| Amazon Bedrock | LLM inference through Strands Agents SDK |
| Amazon RDS for MySQL | Application database accessed through MCP tools |
| Amazon Simple Email Service (Amazon SES) | Email delivery for the Email Agent |
| AWS Secrets Manager | Secure storage for PKCS12 bundles, tokens, and metadata |
| Amazon EC2 | Hosts Keycloak IDP and EJBCA PKI server |
Solution walkthrough
The following steps walk through each component of the architecture, from initial user login through to session cleanup. Each step builds on the previous one, establishing a chain of trust that connects the human user to the final tool execution.
Prerequisites
- An active AWS account with access to Amazon Bedrock, Amazon RDS for MySQL, Amazon SES, and AWS Secrets Manager.
- Keycloak 26.2 or later (required for RFC 8693 standard token exchange. Previous versions use a legacy exchange that is incompatible).
- Keyfactor EJBCA Enterprise with REST API V1 and an OCSP responder configured.
- EJBCA API administrator certificate (
api-admin.p12) for REST API authentication. - Python 3.9+ development environment.
- Familiarity with X.509 certificates, OCSP, OAuth 2.0, RSA digital signatures, and PKCS#12 key stores.
Step 1: User login, certificate issuance, and delegation minting
The login flow establishes the user’s identity through three mechanisms and then delegates authority to the AI agents without sharing the user’s credentials. This separation is critical: Agents receive proof of authorization without ever holding the user’s private key or full-session OAuth token.
First, the application authenticates the user against Keycloak using an OAuth 2.0 password grant, receiving a full-session access token and refresh token. Immediately after, the application performs an RFC 8693 token exchange to obtain a downscoped token. This token’s audience is restricted to the MCP server. Only this limited token is handed to agents. If it’s inadvertently exposed, it can’t access any other service in the organization.
Second, the application generates an RSA 2048+ key pair locally and submits a Certificate Signing Request (CSR) to EJBCA through the pkcs10enroll REST API endpoint. EJBCA signs the CSR and returns the certificate. The application bundles the certificate and private key into a PKCS12 container and stores it in AWS Secrets Manager. The private key never leaves the application boundary. It is not sent to EJBCA, not shared with agents, and not stored on the filesystem. Three agent certificates are issued using the same CSR-based flow, one per agent role.
Third, the user’s private key signs a delegation assertion. This is a JSON document listing the SHA-256 fingerprints of all three agent certificates, along with the user’s subject name, issuance time, and expiry. This delegation proves that the user authorized these specific agents to act on their behalf. Agents carry this delegation instead of the user’s certificate.
# RFC 8693 Token Exchange - downscope to MCP audience
downscoped_token = keycloak.token_exchange(
original_token, audience="mysql-mcp-server", scope="database:write"
)
# Client-side key generation (user key never leaves this flow)
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
csr = build_csr(private_key, f"CN={username},E={username}@org.com")
user_cert = ejbca.pkcs10enroll(csr, ca_name="UserCA")
# User signs delegation over agent cert fingerprints
delegation = mint_delegation(
username=username,
user_cert_pem=user_cert,
user_key_pem=private_key_pem,
agent_cert_pems=[orch_cert, mysql_cert, email_cert]
)
# Result: {sub, agent_fingerprints[], iat, exp, user_cert_pem, signature_b64}Step 2: Agent-to-agent signed envelopes
When the orchestrator agent routes a request to a sub-agent (such as the MySQL agent or Email agent), it does not simply pass its certificate for identification. Instead, it signs the entire request payload, including the tool name, arguments, a timestamp, and a cryptographically random nonce, using its private key with RSA-PSS-SHA256. The resulting signed envelope provides proof-of-possession. The receiving agent can verify that the caller actually holds the private key corresponding to the presented certificate.
The receiving agent performs six validation checks on the envelope before processing the request:
- Signature verification: Proves the sender possesses the private key (proof-of-possession).
- Timestamp freshness: The envelope must be within
ENVELOPE_MAX_AGE_SECONDS(default 60 seconds) of the current time. - Nonce uniqueness: The
ReplayCacherejects any previously seen nonce, preventing request replay. - CA chain validation: The sender’s certificate must chain to the trusted CA (
UserCA.pem). - Role authorization: The certificate CN’s role suffix must be in
ALLOWED_CALLER_ROLESfor this agent. - OCSP revocation check: A real-time check against EJBCA confirms the certificate has not been revoked.
If the orchestrator needs to re-send the same prompt (for example, after a transient failure), it must create a new envelope with a fresh nonce. Old envelopes can’t be replayed, even by the legitimate sender.
# Orchestrator signs request to sub-agent
envelope = sign_envelope(
payload={"tool": "query_database", "args": {"sql": "SELECT ..."}},
cert_pem=orchestrator_cert_pem,
private_key_pem=orchestrator_key_pem
)
# envelope: {payload_b64, cert_pem, timestamp, nonce, signature_b64, alg}
# Sub-agent verifies (six checks)
verified_payload = verify_envelope(
envelope,
allowed_role="orchestrator-agent",
ca_cert_pem=ca_pem,
replay_cache=cache
)Step 3: MCP server authentication
The MCP server (FastMCP) is the final trust boundary before any database operation runs. It performs four validation checks on every tool invocation, implementing defense-in-depth. Even if one credential is subject to unauthorized access, the remaining checks prevent unauthorized operations.
The authentication sequence:
- Token introspection: A POST to the Keycloak
/token/introspectendpoint verifies the token is active and its audience contains “mcp-server”. A full-session token without the correct audience is rejected. - Envelope verification: The agent’s signed envelope is validated for signature correctness, timestamp freshness, nonce uniqueness, CA chain trust, role match (
mysql-agent), and OCSP non-revocation. - Delegation verification: The user’s delegation assertion is validated. The signature proves the user’s key holder authorized this delegation, the calling agent’s certificate fingerprint appears in the authorized list, and the user’s certificate is checked through OCSP.
- Identity cross-check: The token username, the delegation subject, and the agent certificate CN prefix must all match. This confirms a single consistent identity chain from user through to tool execution.
# MCP Server - Four validation checks
# 1. Token: must be active with correct audience
info = introspect(token)
assert info["active"] and "mcp-server" in info["aud"]
# 2. Envelope: proof-of-possession + freshness + replay + CA + role + OCSP
payload = verify_envelope(envelope, "mysql-agent", ca_pem, replay_cache)
# 3. Delegation: user authorized this agent + user cert not revoked
claims = verify_delegation(delegation, agent_cert_pem, ca_pem)
# 4. Cross-check: consistent identity chain
assert token_username == claims["sub"] == agent_cn.rsplit("_", 1)[0]
# All checks passed - execute tool
result = execute_sql(payload["args"]["sql"])Step 4: Replay prevention
Every signed envelope carries a unique nonce, a 128-bit cryptographically random hex string generated with Python’s secrets module. The ReplayCache is a thread-safe in-memory store that remembers every nonce until its freshness window expires (2x ENVELOPE_MAX_AGE_SECONDS). If the same nonce appears in a second request, the envelope is immediately rejected, even if its signature is valid and the timestamp is fresh.
The timestamp validation complements the nonce check. An envelope’s timestamp must be within ENVELOPE_MAX_AGE_SECONDS (default 60 seconds) of the server’s current time. Together, these mechanisms address four unauthorized access scenarios:
- Recorded replay: An unauthorized user captures a valid envelope and resubmits it later. The nonce was already seen.
- Delayed delivery: An envelope intercepted in transit arrives after the freshness window. The timestamp check fails.
- Stale request reuse: An old envelope cached by a proxy is resubmitted. Both nonce and timestamp checks fail.
- Precomputed forgery: An unauthorized user cannot predict future nonces to pre-sign envelopes.
Step 5: Client-side key generation
A critical security property of this architecture is that private keys are generated locally and never transmitted to any external system. The application generates RSA 2048+ key pairs using the Python cryptography library. It constructs a CSR containing only the public key and subject information, and sends only the CSR to EJBCA through the pkcs10enroll endpoint.
EJBCA validates the CSR, applies the certificate profile (7-day validity, key usage constraints), signs it with the CA key, and returns the issued certificate. The application then bundles the locally held private key with the returned certificate into a PKCS12 container and stores it in AWS Secrets Manager.
This design provides several security properties:
- The user’s private key is used only at login to sign the delegation assertion. It’s never shared with agents.
- Each agent’s private key is used only by that agent to sign envelopes. It’s never shared between agents.
- EJBCA never sees or stores private keys. It operates purely as a certificate authority.
- If Secrets Manager is subject to unauthorized access, the PKCS12 password (stored separately) adds an additional layer.
- Key material can be rotated independently by re-enrolling with a new CSR at next login.
Step 6: Complete logout and credential revocation
Logout triggers a revocation cascade that immediately invalidates all outstanding credentials. The sequence results in no remaining valid credentials after completion:
- Revoke user certificate in EJBCA: This immediately invalidates all outstanding delegations, because delegation verification checks the user’s certificate through OCSP in real time.
- Revoke all three agent certificates: This invalidates all outstanding signed envelopes, since envelope verification includes OCSP.
- Delete all secrets from AWS Secrets Manager: Using
ForceDeleteWithoutRecoveryfor immediate removal with no recovery window. - Terminate Keycloak session: Invalidates the downscoped token through the session termination endpoint.
The revocation cascade is the key security property. Revoking a single user certificate at the PKI layer promptly revokes all downstream agent authority without needing to individually revoke tokens, delete sessions, or contact each agent. OCSP provides the propagation mechanism, and because every request checks OCSP, the effect is immediate.
Security considerations
The design choices in this architecture address several security properties that are important for production multi-agent deployments.
Private key isolation. The user’s private key exists only during the login flow and is used solely to sign the delegation. Agent keys are scoped per-agent and never shared. No key material crosses trust boundaries.
Delegation compared to credential sharing. Agents prove their authority through a cryptographic chain (delegation to agent fingerprint to envelope signature) without ever holding user credentials. If an agent key is exposed, only that agent’s key is revealed, not the user’s.
Audience-scoped tokens. RFC 8693 token exchange produces a token accepted only by the MCP server. An inadvertently disclosed downscoped token cannot authenticate against Keycloak admin APIs, other services, or even a different MCP server instance.
Replay prevention. The combination of per-request nonces and a 60-second freshness window confirms that every request is single-use and time-bound. The ReplayCache is thread-safe and self-cleaning.
Fail-closed design. Every validation failure results in immediate denial. OCSP unreachable: deny. Invalid signature: deny. Expired timestamp: deny. Replayed nonce: deny. Wrong audience: deny. There’s no graceful degradation for security checks.
Revocation cascade. Revoking one user certificate promptly invalidates all delegations, all agent authority, and all outstanding envelopes. This is propagated through real-time OCSP without requiring individual credential cleanup.
Forward-only trust chain. The ALLOWED_CALLER_ROLES map enforces that only orchestrator-agent can call mysql-agent and email-agent. Sub-agents cannot call each other, can’t call upward to the orchestrator, and cannot impersonate the user.
AI governance considerations
The PKI architecture provides built-in behavior boundaries for the AI agents in this system. Production deployments should use Amazon Bedrock Guardrails to enforce content filtering, topic avoidance, and grounding checks on agent responses, alongside the PKI-based access controls described in this post.
- Tool boundaries: The AI agent operates under strict tool constraints. It can only invoke pre-defined MCP tools (
execute_sql,describe_table,list_tables). The agent can’t execute arbitrary code or access resources outside its certificate scope. - Human oversight: All agent actions are logged and auditable. AWS CloudTrail captures AWS API calls, and the MCP server logs every validated tool invocation with the full identity chain (user, agent, timestamp, and operation).
- Data handling: User queries and results stay within the authenticated session boundary. The audience-scoped token confines data access to the specific MCP server instance.
- Certificate-based behavior boundaries: Agents can only invoke tools they hold valid certificates for. An agent without a
mysql-agentcertificate cannot access the database, regardless of what the LLM might generate as instructions.
Extending the architecture
You can extend this architecture to support additional agent types, horizontal scaling, and multi-tenant isolation. The following paragraphs describe the most common extension points.
- To add new agent types, you only need to add an entry in
ALLOWED_CALLER_ROLES. Certificates are automatically issued at login, and the delegation assertion dynamically includes the new agent’s fingerprint. No infrastructure changes are required. - For horizontal scaling, you can deploy EJBCA’s OCSP responder in high-availability mode behind a load balancer. AWS Secrets Manager supports high request rates suitable for this workload. The
ReplayCachecan be backed by Amazon ElastiCache for distributed deployments. - To harden the architecture for production, you can use hardware security module (HSM)-backed EJBCA signing keys through AWS CloudHSM or an on-premises HSM. OCSP response stapling reduces validation latency, and Certificate Transparency logs provide a full audit trail of issued certificates.
- For multi-tenant deployments, you can create per-tenant Certificate Authorities or per-tenant delegation authorities for cryptographic tenant isolation. Combined with per-tenant AWS accounts, this delivers strong isolation between tenants.
- You can also complement PKI-based agent identity with AWS Identity and Access Management (IAM) roles. Use PKI for agent-to-agent authentication and IAM for AWS service authorization. The two systems work independently, providing defense in depth.
Clean up
To avoid ongoing charges, remove the resources created during this walkthrough:
- Delete the Amazon RDS for MySQL instance (or the AWS CloudFormation stack if you used the scripted setup).
- Delete all secrets from AWS Secrets Manager, including user certificates and agent certificates under the
mcp/prefix. - Remove the verified sender email address from Amazon SES.
- Terminate the Amazon EC2 instances running Keycloak and EJBCA (if deployed for this demonstration).
- Revoke and delete all test certificates in EJBCA by using the EJBCA admin console or REST API.
- Remove the Keycloak realm (
mcp-realm) and associated clients. - If you used the scripted setup, run
./scripts/cleanup.sh(Linux) or./scripts/cleanup.bat(Windows) to automate these steps.
Conclusion
In this post, we demonstrated a reference architecture for securing AI agent communications using X.509 PKI with Keyfactor EJBCA and AWS services. The architecture addresses the fundamental identity gap in multi-agent AI systems through four complementary mechanisms:
- Signed request envelopes provide cryptographic proof-of-possession on every inter-agent call, making it significantly harder for an unauthorized party to forge an agent’s identity or replay its requests.
- User-signed delegation assertions decouple authorization from credential sharing. Agents prove they are authorized to act on the user’s behalf without holding the user’s private key or full-session token.
- RFC 8693 audience-scoped tokens limit the scope of exposure from any token disclosure to a single service boundary.
- Real-time OCSP revocation checking confirms that credential revocation takes immediate effect across the entire system. Revoking one user certificate promptly ends all downstream agent authority.
This architecture is framework-agnostic. While we demonstrated it with the AWS Strands Agents SDK and FastMCP, the same PKI patterns apply to LangChain, CrewAI, AutoGen, or any other multi-agent framework that uses tool protocols. As AI agents proliferate and gain access to increasingly sensitive operations, agent identity infrastructure moves from optional to essential.
To get started with this reference architecture, see the accompanying GitHub repository. For more information about the services used, see the following resources:
- Amazon Bedrock
- Amazon Bedrock User Guide
- Keyfactor EJBCA Enterprise
- MCP Specification
- AWS Strands Agents SDK
- Introducing Strands Agents, an Open Source AI Agents SDK (AWS Open Source blog post)
About the authors
Deepakkumar Sharma
Deepakkumar is a Solutions Architect at Amazon Web Services specializing in generative AI, security architecture, and cloud-native application design. He works with enterprise customers to build secure AI systems on AWS and is passionate about bringing cryptographic identity to the AI agent ecosystem.
JD Kilgallin
JD leads the Keyfactor Analytics and AI team specializing in identity and trust management solutions for Agentic AI. He focuses on bringing enterprise PKI capabilities to emerging AI frameworks and multi-agent architectures.
Alex Ament
Alex is an associate Software Engineer on the Keyfactor Analytics and AI team supporting integrations of PKI software with Agentic AI. He contributed the signed envelope, delegation assertion, and replay prevention implementations in this reference architecture.
来源:AWS Machine Learning Blog · aws.amazon.com

