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 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 age
