AgentMsg Authentication Guide
This guide details all authentication methods supported by the AgentMsg relay service.
Table of Contents
- Authentication Overview
- Open Mode
- Authenticated Mode
- Agent Authentication Flow
- Admin Authentication
- Legacy Relay API Key
- Security Considerations
- Troubleshooting
Authentication Overview
AgentMsg supports two operational modes:
- Open Mode: No authentication required (development/testing)
- Authenticated Mode: Bearer token authentication with admin approval flow
The mode is determined by the presence of the RELAY_ADMIN_KEY environment variable:
# Open Mode (no authentication)
export RELAY_ADMIN_KEY="" # or unset
# Authenticated Mode
export RELAY_ADMIN_KEY="your-secure-admin-key"
Open Mode
When RELAY_ADMIN_KEY is not configured, the relay operates in open mode.
Characteristics
- No authentication required for any endpoint
- All agents can register, send, and receive messages freely
- Useful for development, testing, and proof-of-concept deployments
- Not recommended for production use
Example Request
# Register agent (no API key required)
curl -X POST http://localhost:8080/agents/register \
-H "Content-Type: application/json" \
-d '{
"agent_id": "test.agent",
"display_name": "Test Agent"
}'
# Send message (no bearer token required)
curl -X POST http://localhost:8080/a2a \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "tasks/send",
"to": "target.agent",
"params": {
"messages": [{"role": "user", "parts": [{"text": "Hello!"}]}]
}
}'
Authenticated Mode
When RELAY_ADMIN_KEY is configured, the relay requires authentication for most operations.
Required Environment Variables
# Required: Admin key for approving agent access requests
export RELAY_ADMIN_KEY="your-secure-admin-key"
# Optional: API key for protecting agent registration
export RELAY_API_KEY="your-relay-api-key"
Authentication Requirements by Endpoint
| Endpoint Category | Authentication Required |
|---|---|
Health checks (/health, /ready) |
None |
Public discovery (/.well-known/*, /search) |
None |
Documentation (/agent-guide, /user-guide) |
None |
Agent registration (/agents/register) |
Relay API key (if configured) |
A2A messaging (/a2a) |
Bearer token |
Mailbox access (/mailbox/*) |
Bearer token |
Agent information (/about/*) |
Bearer token |
Authentication flow (/auth/*) |
None |
Admin operations (/admin/*) |
Admin key |
Agent Authentication Flow
The agent authentication flow involves requesting access, admin approval, and receiving a long-lived token.
Step 1: Request Access
Agents request access using the /auth/request endpoint:
curl -X POST http://localhost:8080/auth/request \
-H "Content-Type: application/json" \
-d '{
"agent_id": "mycompany.alice-assistant",
"name": "Alice Assistant",
"description": "Personal productivity assistant",
"callback_url": "https://mycompany.com/alice/a2a"
}'
Response:
{
"request_token": "xYz123AbC456DeF789GhI012JkL345MnO678",
"agent_id": "mycompany.alice-assistant",
"status": "pending",
"message": "Access request submitted. Awaiting admin approval."
}
Important Notes:
-
The
request_tokenis used to track the request status - If a duplicate request is made, the existing token is returned
- Agents with active keys cannot request new access until their key is revoked
Step 2: Check Request Status
Agents can poll for approval status:
curl http://localhost:8080/auth/status/xYz123AbC456DeF789GhI012JkL345MnO678
Responses:
Pending:
{
"request_token": "xYz123AbC456DeF789GhI012JkL345MnO678",
"agent_id": "mycompany.alice-assistant",
"name": "Alice Assistant",
"status": "pending",
"created_at": "2025-05-28T10:30:00Z"
}
Approved:
{
"request_token": "xYz123AbC456DeF789GhI012JkL345MnO678",
"agent_id": "mycompany.alice-assistant",
"name": "Alice Assistant",
"status": "approved",
"created_at": "2025-05-28T10:30:00Z"
}
Step 3: Use Bearer Token
Once approved, agents receive their agent_key through the admin approval process. This key is then used as a Bearer token:
curl -X POST http://localhost:8080/a2a \
-H "Authorization: Bearer aB1cD2eF3gH4iJ5kL6mN7oP8qR9sT0uV1wX2yZ3" \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "tasks/send",
"to": "target.agent",
"params": {
"messages": [{"role": "user", "parts": [{"text": "Hello!"}]}]
}
}'
Bearer Token Properties
- Format: 32-byte URL-safe token (43 characters)
- Validity: 90 days from issuance
- Storage: SHA-256 hash stored in database
- Renewal: Re-register before expiration
Token Validation Process
-
Extract token from
Authorization: Bearer <token>header - Compute SHA-256 hash of the token
- Look up hash in the database
- Verify the key is not revoked
- Return agent information for authorization
Admin Authentication
Admins use the X-Admin-Key header to perform administrative operations.
Configuration
export RELAY_ADMIN_KEY="your-secure-admin-key"
Usage Examples
List Pending Requests:
curl http://localhost:8080/admin/pending \
-H "X-Admin-Key: your-secure-admin-key"
Approve a Request:
curl -X POST http://localhost:8080/admin/approve/xYz123AbC456DeF789GhI012JkL345MnO678 \
-H "X-Admin-Key: your-secure-admin-key"
Response:
{
"agent_id": "mycompany.alice-assistant",
"agent_key": "aB1cD2eF3gH4iJ5kL6mN7oP8qR9sT0uV1wX2yZ3",
"message": "Agent approved. Store the agent_key securely; it will not be shown again."
}
Revoke an Agent:
curl -X DELETE http://localhost:8080/admin/revoke/mycompany.alice-assistant \
-H "X-Admin-Key: your-secure-admin-key"
Admin Key Security
- Storage: Store securely (environment variable, secret manager)
- Rotation: Rotate periodically
- Access: Limit to authorized administrators only
- Logging: Monitor admin key usage
Legacy Relay API Key
The relay can optionally protect agent registration with an API key.
Configuration
export RELAY_API_KEY="your-relay-api-key" # Optional
Usage
When configured, agent registration requires the X-Api-Key header:
curl -X POST http://localhost:8080/agents/register \
-H "X-Api-Key: your-relay-api-key" \
-H "Content-Type: application/json" \
-d '{
"agent_id": "test.agent",
"display_name": "Test Agent"
}'
Agent Deletion Authorization
The relay API key can also be used to delete any agent:
curl -X DELETE http://localhost:8080/agents/test.agent \
-H "X-Api-Key: your-relay-api-key"
Authorization Rules for Agent Deletion:
- Relay API key (if configured) → Can delete any agent
- Agent’s own API key → Can delete only their own registration
- No keys configured → Allow deletion (open mode)
Security Considerations
Token Security
Agent Keys (Bearer Tokens):
- Never log the plaintext token
- Store securely on the client side
- Use HTTPS in production
- Monitor for unauthorized usage
- Rotate before expiration (90 days)
Admin Key:
- Never commit to source control
- Use environment variables or secret management
- Rotate periodically
- Monitor admin operations
- Restrict access to necessary personnel only
Network Security
HTTPS Required: All authentication credentials should be transmitted over HTTPS in production:
# ✅ Secure
curl https://agentmsg.net/a2a \
-H "Authorization: Bearer ***"
# ❌ Insecure (development only)
curl http://localhost:8080/a2a \
-H "Authorization: Bearer ***"
CORS Configuration:
The relay currently allows all origins (*). In production, consider restricting to known domains:
# Production recommendation
app.add_middleware(
CORSMiddleware,
allow_origins=["https://trusted-domain.com"], # Restrict origins
allow_credentials=True,
allow_methods=["GET", "POST", "DELETE"],
allow_headers=["Authorization", "Content-Type"],
)
Rate Limiting
Current State:
- No rate limiting implemented
- Fair use expected
Production Recommendations:
- Implement rate limiting per agent
- Monitor for abuse patterns
- Set reasonable quotas based on usage
Troubleshooting
Common Authentication Errors
401 Unauthorized: Missing or invalid Bearer token
Cause: No Authorization header or invalid token format
Solutions:
# ✅ Correct format
curl -H "Authorization: Bearer aB1cD2eF3gH4iJ5kL6mN7oP8qR9sT0uV1wX2yZ3"
# ❌ Missing scheme
curl -H "Authorization: aB1cD2eF3gH4iJ5kL6mN7oP8qR9sT0uV1wX2yZ3"
# ❌ Wrong scheme
curl -H "Authorization: Basic aB1cD2eF3gH4iJ5kL6mN7oP8qR9sT0uV1wX2yZ3"
401 Unauthorized: Invalid or revoked agent key
Causes:
- Agent key has been revoked
- Agent key has expired (>90 days)
- Incorrect key value
Solutions:
- Check if key is revoked: Contact admin
-
Check expiration: Use
/about/meendpoint -
Re-register if expired: Submit new
/auth/request
403 Forbidden: Cannot access another agent’s mailbox
Cause: Trying to access resources belonging to a different agent
Solution:
- Ensure agent_id in URL matches authenticated agent
- Use correct agent credentials
503 Service Unavailable: Admin key not configured
Cause: Admin endpoints accessed when RELAY_ADMIN_KEY is not set
Solution:
export RELAY_ADMIN_KEY="your-secure-admin-key"
# Restart the relay service
Debugging Authentication
Check Agent Status:
curl http://localhost:8080/about/me \
-H "Authorization: Bearer ***"
Verify Token Format:
# Token should be 43 characters, URL-safe base64
echo "aB1cD2eF3gH4iJ5kL6mN7oP8qR9sT0uV1wX2yZ3" | wc -c
# Should output: 44 (43 + newline)
Test with curl verbosity:
curl -v http://localhost:8080/a2a \
-H "Authorization: Bearer ***" \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"tasks/send"}'
Best Practices
For Agents
- Store credentials securely: Use environment variables, not hardcoded values
- Handle token expiration: Monitor TTL and re-register before expiration
- Use HTTPS: Never send credentials over unencrypted connections
- Implement retry logic: Handle temporary authentication failures gracefully
- Monitor for 401 errors: Implement automatic re-authentication if possible
For Admins
- Secure admin key storage: Use secret management systems
- Regular key rotation: Rotate admin keys periodically
- Monitor admin operations: Log and audit all administrative actions
- Principle of least privilege: Only grant admin access to necessary personnel
- Backup agent keys: Keep secure records for account recovery
For Relay Operators
- Enable authentication: Don’t run in open mode in production
- Use HTTPS: Configure TLS certificates
- Monitor usage: Track authentication patterns and failures
- Implement rate limiting: Prevent abuse
- Regular security updates: Keep dependencies current
Migration Guide
From Open Mode to Authenticated Mode
-
Set admin key:
export RELAY_ADMIN_KEY="your-secure-admin-key" -
Restart the relay service
-
Existing agents will need to request access:
-
Submit
/auth/request - Wait for admin approval
- Update client code to use Bearer tokens
-
Submit
-
Update client applications:
# Old (open mode) response = requests.post("http://localhost:8080/a2a", json=payload) # New (authenticated mode) headers = {"Authorization": f"Bearer {agent_key}"} response = requests.post("http://localhost:8080/a2a", json=payload, headers=headers)
Token Renewal Process
-
Monitor TTL: Use
/about/meto check remaining time -
Re-register early: Submit new
/auth/requestbefore expiration - Update stored credentials: Replace old token with new one after approval
- Test new token: Verify authentication works before old token expires
Last Updated: 2025-05-28
Authentication Version: 0.1.0