Authentication
Secure agent access with authentication and authorization
Authentication
Secure your SwiftClaw agents with robust authentication and authorization.
API Key Authentication
Generate API Keys
# Generate new API key
swiftclaw keys create my-agent --name production
# Output:
# API Key: sk_live_abc123...
# Keep this key secure!Use API Keys
# Authenticate requests
curl https://api.swiftclaw.io/agents/my-agent/invoke \
-H "Authorization: Bearer sk_live_abc123..." \
-d '{"message": "Hello"}'Rotate API Keys
# List keys
swiftclaw keys list my-agent
# Rotate key
swiftclaw keys rotate my-agent --key sk_live_abc123...
# Revoke key
swiftclaw keys revoke my-agent --key sk_live_old123...OAuth 2.0
Configure OAuth
{
"auth": {
"type": "oauth2",
"provider": "auth0",
"clientId": "your-client-id",
"clientSecret": "your-client-secret",
"scopes": ["read:agents", "write:agents"]
}
}OAuth Flow
from swiftclaw import Agent, OAuth2
# Initialize OAuth
oauth = OAuth2(
client_id="your-client-id",
client_secret="your-client-secret",
redirect_uri="https://yourapp.com/callback"
)
# Get authorization URL
auth_url = oauth.get_authorization_url()
# Exchange code for token
token = await oauth.exchange_code(code)
# Use token
agent = Agent(auth_token=token)JWT Authentication
Generate JWT
import jwt
from datetime import datetime, timedelta
def generate_token(user_id: str):
payload = {
"user_id": user_id,
"exp": datetime.utcnow() + timedelta(hours=1),
"iat": datetime.utcnow()
}
return jwt.encode(
payload,
"your-secret-key",
algorithm="HS256"
)Verify JWT
@agent.middleware
async def verify_jwt(request):
token = request.headers.get("Authorization").split(" ")[1]
try:
payload = jwt.decode(
token,
"your-secret-key",
algorithms=["HS256"]
)
request.user_id = payload["user_id"]
except jwt.ExpiredSignatureError:
raise Unauthorized("Token expired")
except jwt.InvalidTokenError:
raise Unauthorized("Invalid token")Role-Based Access Control (RBAC)
Define Roles
{
"roles": {
"admin": {
"permissions": ["read", "write", "delete", "manage"]
},
"developer": {
"permissions": ["read", "write"]
},
"viewer": {
"permissions": ["read"]
}
}
}Enforce Permissions
@agent.require_permission("write")
async def update_agent(config):
await agent.update(config)
@agent.require_role("admin")
async def delete_agent():
await agent.delete()User Authentication
Authenticate Users
from swiftclaw import Agent
agent = Agent(name="my-agent")
@agent.on_message
async def handle_message(message, user):
# Verify user is authenticated
if not user.is_authenticated:
return "Please sign in first"
# Check user permissions
if not user.has_permission("use_agent"):
return "You don't have permission to use this agent"
return await agent.generate(message.content)Session Management
# Create session
session = await agent.create_session(user_id="user123")
# Use session
@agent.on_message
async def handle_message(message, session):
# Session automatically tracked
return await agent.generate(
message.content,
context=session.history
)
# End session
await agent.end_session(session.id)Multi-Factor Authentication (MFA)
Enable MFA
# Enable MFA for agent
swiftclaw security mfa enable my-agent
# Require MFA for sensitive operations
swiftclaw security mfa require my-agent --operations delete,updateVerify MFA
@agent.require_mfa
async def sensitive_operation():
# MFA verification required
await agent.delete_data()IP Whitelisting
Configure IP Whitelist
{
"security": {
"ipWhitelist": {
"enabled": true,
"addresses": [
"203.0.113.0/24",
"198.51.100.42"
]
}
}
}Dynamic IP Whitelist
# Add IP address
swiftclaw security whitelist add my-agent --ip 203.0.113.50
# Remove IP address
swiftclaw security whitelist remove my-agent --ip 203.0.113.50
# List whitelisted IPs
swiftclaw security whitelist list my-agentWebhook Authentication
Verify Webhook Signatures
import hmac
import hashlib
def verify_webhook(payload: bytes, signature: str, secret: str):
expected = hmac.new(
secret.encode(),
payload,
hashlib.sha256
).hexdigest()
return hmac.compare_digest(signature, expected)
@agent.webhook
async def handle_webhook(request):
signature = request.headers.get("X-SwiftClaw-Signature")
if not verify_webhook(request.body, signature, webhook_secret):
raise Unauthorized("Invalid signature")
# Process webhook
await process_event(request.json())Service-to-Service Authentication
mTLS (Mutual TLS)
{
"security": {
"mtls": {
"enabled": true,
"clientCert": "/path/to/client.crt",
"clientKey": "/path/to/client.key",
"caCert": "/path/to/ca.crt"
}
}
}Service Accounts
# Create service account
swiftclaw accounts create my-service \
--type service \
--permissions read,write
# Generate credentials
swiftclaw accounts credentials my-serviceAudit Logging
Track authentication events:
# View auth logs
swiftclaw logs my-agent --filter auth
# View failed login attempts
swiftclaw logs my-agent --filter auth.failed
# Export audit log
swiftclaw audit export my-agent --period 30dBest Practices
1. Use Strong API Keys
# Generate secure keys
swiftclaw keys create my-agent --length 642. Rotate Credentials Regularly
# Set rotation policy
swiftclaw security rotation my-agent --interval 90d3. Implement Rate Limiting
{
"security": {
"rateLimit": {
"enabled": true,
"requests": 100,
"window": "1m"
}
}
}4. Monitor Authentication
# Set up alerts
swiftclaw alerts create \
--agent my-agent \
--metric failed-auth \
--threshold 10 \
--window 5m5. Use HTTPS Only
{
"security": {
"enforceHttps": true,
"hsts": {
"enabled": true,
"maxAge": 31536000
}
}
}Never Commit Secrets: Store API keys and secrets in environment variables or secret managers.
Next Steps
How is this guide ?
Last updated on