Production-grade guide to agent credential management covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
Agent Credential Management is the practice of securely storing, retrieving, rotating, and validating credentials used by AI agents to authenticate with external services. It matters when agents must access databases, APIs, cloud storage, message queues, or third-party platforms—especially when credentials are sensitive, frequently changing, or shared across multiple agents. Credentials are the identity layer of agent systems, and failure to manage them leads to silent failures: agents that can’t connect, timeouts that go unnoticed, and configuration drift across environments.
Credentials are defined as a structured payload with at least an id, type, value, and metadata. The type determines the credential’s use: api-key, oauth2, jwt, basic, ssh-key, client-certificate, database-connection-string. The value contains the actual credential data, and metadata includes expires, description, owner, and environment.
To create a credential, use a standard HTTP PUT request to a credential registry endpoint:
PUT /api/credentials/{id}
Content-Type: application/json
{
"id": "db-primary-prod",
"type": "database-connection-string",
"value": "postgresql://user:[email protected]:5432/warehouse?sslmode=require",
"metadata": {
"expires": "2025-12-31T23:59:59Z",
"description": "Primary warehouse database for production workloads",
"owner": "[email protected]",
"environment": "prod"
}
}
The id must be globally unique and used to reference the credential across agents. The registry returns 201 Created on success, with the full credential in the response body.
Agents retrieve credentials via a simple HTTP GET:
GET /api/credentials/db-primary-prod
Authorization: Bearer {agent-token}
On success, the response is:
{
"id": "db-primary-prod",
"type": "database-connection-string",
"value": "postgresql://user:[email protected]:5432/warehouse?sslmode=require",
"metadata": {
"expires": "2025-12-31T23:59:59Z",
"description": "Primary warehouse database for production workloads",
"owner": "[email protected]",
"environment": "prod"
}
}
If the credential is not found, the registry returns 404 Not Found with a body:
{
"error": "CredentialNotFound",
"message": "No credential with id 'db-primary-prod' exists"
}
Agents use credentials through a standard credential provider interface. An agent written in Python, for example, uses a get_credential(id: str) function that internally calls the registry:
import requests
def get_credential(id: str) -> dict:
url = f"https://registry.example.com/api/credentials/{id}"
headers = {"Authorization": "Bearer " + agent_token}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
elif response.status_code == 404:
raise CredentialNotFound(response.json()["message"])
else:
raise RuntimeError(f"Unexpected status: {response.status_code} - {response.text}")
try:
db_creds = get_credential("db-primary-prod")
conn_string = db_creds["value"]
db = connect_to_database(conn_string)
except CredentialNotFound as e:
log_error(f"Agent failed to retrieve credential: {e}")
The agent may cache the credential locally for performance, but must validate freshness on each use.
Each credential includes an expires timestamp in ISO 8601 format. Agents should validate this timestamp before use:
from datetime import datetime
def is_credential_valid(credential: dict) -> bool:
now = datetime.utcnow()
expiry = datetime.fromisoformat(credential["metadata"]["expires"])
return now < expiry
Agents that fail to validate expiry silently use stale credentials, leading to connection failures when the underlying service rotates keys. A common failure mode is a credential that expires at midnight but is not refreshed until the next agent run—resulting in 24 hours of downtime.
When credentials change (e.g., a new API key is issued), agents are notified via a credential rotation event. The process is:
value for an existing id. PUT /api/credentials/db-primary-prod
Content-Type: application/json
{
"id": "db-primary-prod",
"type": "database-connection-string",
"value": "postgresql://user:[email protected]:5432/warehouse?sslmode=require",
"metadata": {
"expires": "2026-12-31T23:59:59Z",
"description": "Primary warehouse database for production workloads",
"owner": "[email protected]",
"environment": "prod"
}
}
expires time, allowing a smooth transition.Agents may require different levels of access. A credential can include a roles array in metadata:
{
"id": "api-warehouse-prod",
"type": "api-key",
"value": "sk-abc123-def456-ghi789",
"metadata": {
"expires": "2025-12-31T23:59:59Z",
"roles": ["read", "write", "admin"],
"environment": "prod"
}
}
An agent checks roles before performing actions:
def requires_role(credential: dict, required_role: str) -> bool:
return required_role in credential["metadata"].get("roles", [])
# Example usage
if not requires_role(db_creds, "write"):
log_error("Agent lacks write access to warehouse database")
When a credential is updated, the registry maintains version history. Each update creates a new version record:
{
"id": "api-warehouse-prod",
"version": 3,
"type": "api-key",
"value": "sk-abc123-def456-ghi789",
"metadata": {
"expires": "2025-12-31T23:59:59Z",
"roles": ["read", "write"],
"environment": "prod"
},
"created_at": "2024-07-15T14:30:00Z",
"updated_at": "2024-07-15T14:30:00Z"
}
Agents may use version to fetch a specific version:
GET /api/credentials/api-warehouse-prod?version=2
The registry returns the credential as it was at version 2, including all metadata and value. If no version exists, it returns 404 Not Found.
Credentials are stored in a secure registry with at least AES-256 encryption at rest. The value field is encrypted using a key derived from a master key. The registry exposes a key_id in the credential metadata:
{
"id": "api-warehouse-prod",
"type": "api-key",
"value": "sk-abc123-def456-ghi789",
"metadata": {
"expires": "2025-12-31T23:59:59Z",
"key_id": "k-2024-07-14",
"roles": ["read", "write"]
}
}
The key_id references a key in a key management system (KMS). Agents can fetch the key using a GET /api/kms/{key_id} endpoint:
GET /api/kms/k-2024-07-14
Authorization: Bearer {kms-token}
Response:
{
"key_id": "k-2024-07-14",
"algorithm": "AES-256-GCM",
"material": "base64-encoded-encryption-key",
"created_at": "2024-07-14T10:00:00Z",
"rotated_at": "2024-07-14T10:00:00Z"
}
The agent uses the material to decrypt the value field before use.
Agents may retrieve credentials from multiple registries. A configuration file defines a list of credential sources:
{
"credential_sources": [
{
"type": "http",
"url": "https://registry.example.com",
"auth": {
"type": "bearer",
"token": "agent-token-abc123"
}
},
{
"type": "file",
"path": "/etc/agent/credentials.json"
},
{
"type": "kubernetes",
"namespace": "ai-agents",
"secret_name": "agent-credentials"
}
]
}
On startup, the agent attempts to load credentials from all sources, preferring the first successful one.
404 Not Found but continues execution, using a default credential. This leads to subtle failures: data written to a non-existent database, logs sent to a missing API.401 Unauthorized when the agent tries to use the credential, but the agent does not retry or log the failure.environment, roles, or expires but finds them missing or misnamed. A common error is expires in ISO 8601 format but with a trailing Z that is not parsed correctly.key_id in the credential does not match any key in the KMS. The agent fails to decrypt the value field, leading to invalid or null credentials.When no dedicated registry exists, credential management can be implemented using standard tools:
kubectl with Kubernetes Secrets# Create a secret from a credential file
kubectl create secret generic db-primary-prod \
--from-file=credential.json \
--namespace=ai-agents
# Apply to cluster
kubectl apply -f - << EOF
apiVersion: v1
kind: Secret
metadata:
name: db-primary-prod
namespace: ai-agents
type: Opaque
data:
value: cG9zdGZyZWV0c2VjdXJlOi8vY29yZS5leGFtcGxlLmNvbTovNTQzMi93YXJrZm9yZmFjdGlvbi5zZW5zaW5n?sslmode=require
metadata: ewogICJleHBpcmVzIjogIjIwMjUtMTItMzFUMjM6NTk6NTlaIiwKICAgImRlc2NyaWJ0aW9uIjogIlByb2R1Y3Rpb24gZm9yIGZvcmVudG9uIGJ1c2luZXNzIiwKICAgIm91cmVzIjogWyJyZWFkIiwgIndyaXRlIiwgImFkbWluIl0sCiAgICJlbmZyb25tZW50IjogInByb2QiCn0K
EOF
curl for Manual Credential Operations# Create a credential
curl -X PUT \
-H "Content-Type: application/json" \
-H "Authorization: Bearer 3456789012345678" \
-d '{
"id": "api-warehouse-prod",
"type": "api-key",
"value": "sk-abc123-def456-ghi789",
"metadata": {
"expires": "2025-12-31T23:59:59Z",
"roles": ["read", "write", "admin"]
}
}' \
https://registry.example.com/api/credentials/api-warehouse-prod
# Retrieve a credential
curl -H "Authorization: Bearer 3456789012345678" \
https://registry.example.com/api/credentials/api-warehouse-prod
psql to Verify Credential Storage-- Check credential table structure
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = 'credentials';
-- Query for all active production credentials
SELECT id, value, metadata->>'expires' as expires
FROM credentials
WHERE (metadata->>'environment') = 'prod'
AND (metadata->>'expires') > NOW()
ORDER BY metadata->>'created_at' DESC;
systemctl to Manage Credential RefreshersA credential refresher service runs as a systemd unit:
[Unit]
Description=Agent Credential Refresher
After=network.target
[Service]
Type=simple
User=agent
ExecStart=/usr/bin/python3 /opt/agent/refresh_creds.py
Restart=always
RestartSec=30
[Install]
WantedBy=multi-user.target
The refresher runs every 30 minutes, fetching all credentials, validating expiry, and logging any issues:
import logging
import requests
def refresh_all_credentials():
url = "https://registry.example.com/api/credentials"
headers = {"Authorization": "Bearer refresher-token"}
response = requests.get(url, headers=headers)
if response.status_code != 200:
logging.error(f"Failed to fetch credentials: {response.status_code} - {response.text}")
return
credentials = response.json()
for cred in credentials:
if not is_credential_valid(cred):
logging.warning(f"Credential {cred['id']} is expired: {cred['metadata']['expires']}")
else:
logging.info(f"Valid credential: {cred['id']}")
refresh_all_credentials()
expires timestamps.id as the primary key for all credential operations.value using KMS and track key_id.roles to control access and enforce permissions.kubectl, curl, and psql.This page was rewritten on 13 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy