API Keys & Authentication
Secure your Redis instances with proper key management
API Keys & Authentication Guide
Secure your Redis instances with API keys. Master token authentication, save your keys, and manage multiple keys per instance.
How API Keys Work
Every SwiftCache instance uses API key authentication. When you create an instance, we auto-generate a default key. You must save this key immediately - it's shown only once.
The Golden Rule
Save your API key → It's shown only once → Losing it = access denied
Creating an Instance (and Getting Your Key)
Step 1: Create the Instance
curl -X POST https://api.swiftcache.io/api/v1/instances \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk_live_your_account_key" \
-d '{
"organizationId": "org_abc123",
"name": "my-cache",
"maxMemory": 536870912,
"region": "eu-central"
}'
Step 2: Capture the Default Key
The response includes a createdDefaultKey object:
{
"instance": {
"id": "inst_def456",
"name": "my-cache",
"status": "PROVISIONING",
"hostname": null
},
"createdDefaultKey": {
"id": "key_xyz789",
"name": "my-cache-default",
"plainTextKey": "sc_live_9f8e7d6c5b4a3f2e1d0c9b8a7f6e5d4c",
"createdAt": "2024-03-15T10:30:00Z"
}
}
Step 3: Save the plainTextKey Immediately
The plainTextKey is what you need. Save it in:
- Your password manager (LastPass, 1Password, etc.)
- Your
.envfile (for local development) - Your secrets management system (AWS Secrets Manager, Vault, etc.)
Do not: Share it, commit it to git, or leave it in a terminal window.
# Example: Save to .env for local development
echo "REDIS_API_KEY=sc_live_9f8e7d6c5b4a3f2e1d0c9b8a7f6e5d4c" >> .env
Using Your API Key to Connect
API keys authenticate your requests to SwiftCache. Use them as Bearer tokens.
TypeScript Example
import { createClient } from 'redis';
const apiKey = process.env.SWIFTCACHE_API_KEY; // sc_live_...
const hostname = 'abc123.redis.swiftcache.io';
const client = createClient({
host: hostname,
port: 6379,
password: apiKey, // API key goes here as password
socket: {
reconnectStrategy: (retries) => Math.min(retries * 50, 500)
}
});
client.on('error', (err) => console.log('Redis Client Error', err));
await client.connect();
// Now you can use it
await client.set('key', 'value');
const value = await client.get('key');
console.log(value);
await client.disconnect();
Python Example
import redis
import os
api_key = os.getenv('SWIFTCACHE_API_KEY') # sc_live_...
hostname = 'abc123.redis.swiftcache.io'
# Python redis library authenticates with password parameter
r = redis.Redis(
host=hostname,
port=6379,
password=api_key,
decode_responses=True,
socket_connect_timeout=5,
socket_keepalive=True
)
# Test connection
try:
r.ping()
print("Connected to SwiftCache!")
except redis.ConnectionError as e:
print(f"Connection failed: {e}")
# Use it
r.set('key', 'value')
value = r.get('key')
print(value)
r.close()
Node.js with ioredis
const Redis = require('ioredis');
const apiKey = process.env.SWIFTCACHE_API_KEY;
const hostname = 'abc123.redis.swiftcache.io';
const redis = new Redis({
host: hostname,
port: 6379,
password: apiKey,
retryStrategy: (times) => Math.min(times * 50, 2000)
});
redis.on('connect', () => console.log('Connected to SwiftCache'));
redis.on('error', (err) => console.log('Connection error:', err));
// Use it
await redis.set('key', 'value');
const value = await redis.get('key');
console.log(value);
redis.disconnect();
Raw Connection String Format
Not using a client library? Use this format:
redis://:[API_KEY]@[HOSTNAME]:6379
Example:
redis://:sc_live_9f8e7d6c5b4a3f2e1d0c9b8a7f6e5d4c@abc123.redis.swiftcache.io:6379
Understanding Your API Keys
Key Structure
Every API key has this format:
sc_live_[32-character-hex-string]
- sc_live_ = SwiftCache Live environment prefix
- 32 hex chars = Your unique key ID (cannot be guessed)
Key Properties
When you view a key in the dashboard or API:
{
"id": "key_xyz789",
"name": "my-cache-default",
"createdAt": "2024-03-15T10:30:00Z",
"lastUsed": "2024-03-15T12:45:00Z",
"permissions": ["read", "write"],
"ipWhitelist": [],
"rateLimit": 1000
}
- id = Unique key ID (different from the secret)
- name = Human-readable label you can change
- createdAt = When it was created
- lastUsed = Last time it authenticated successfully
- permissions = What it can do (always read+write for now)
- ipWhitelist = Restrict to specific IPs (empty = any IP)
- rateLimit = Requests per second (1000 = unlimited)
Important: The plainTextKey is never shown again after creation. If you lose it, delete the key and create a new one.
Binding Multiple Keys to One Instance
You can create multiple API keys and bind them all to a single instance. Useful for:
- Different team members needing separate credentials
- Rotating keys without downtime
- Different apps accessing the same cache
Method 1: Create Instance with Existing Keys
If you already have API keys created, bind them when creating the instance:
curl -X POST https://api.swiftcache.io/api/v1/instances \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk_live_your_account_key" \
-d '{
"organizationId": "org_abc123",
"name": "shared-cache",
"maxMemory": 536870912,
"region": "eu-central",
"apiKeyIds": ["key_aaa", "key_bbb", "key_ccc"]
}'
In this case, no createdDefaultKey is returned (you provided your own keys).
Method 2: Create Additional Keys Later
Create a new key that's already bound to the instance:
# First, get all instances to find which ones have space
curl -H "Authorization: Bearer sk_live_your_account_key" \
'https://api.swiftcache.io/api/v1/instances?organizationId=org_abc123'
# Then create the key and manually bind it
# (Use the key creation endpoint - see below)
View All Keys for an Instance
curl -H "Authorization: Bearer sk_live_your_account_key" \
https://api.swiftcache.io/api/v1/instances/inst_def456
# Response includes all bound keys
{
"instance": {
"id": "inst_def456",
"name": "my-cache",
"status": "RUNNING",
"hostname": "abc123.redis.swiftcache.io",
"apiKeys": [
{
"id": "key_xyz789",
"name": "my-cache-default",
"createdAt": "2024-03-15T10:30:00Z"
},
{
"id": "key_abc123",
"name": "app-server-key",
"createdAt": "2024-03-15T11:00:00Z"
}
]
}
}
Rotating Keys (Security Best Practice)
Periodically rotate API keys to minimize damage if one gets compromised.
Rotation Strategy
- Create new key for the instance
- Deploy it to your applications (can happen gradually)
- Monitor that old key isn't used
- Delete old key after confirmation (or after 30 days)
TypeScript Rotation Example
import fetch from 'node-fetch';
async function rotateApiKey(instanceId: string, accountKey: string) {
// Step 1: Create new key bound to instance
const createResponse = await fetch(
`https://api.swiftcache.io/api/v1/instances/${instanceId}/api-keys`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${accountKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: `${new Date().toISOString()}-rotation`
})
}
);
const { createdKey } = await createResponse.json();
console.log('New key created:', createdKey.plainTextKey);
console.log('Old key ID to delete later:', 'key_old_id');
// Step 2: Return new key for deployment
return createdKey.plainTextKey;
// Step 3: After apps are deployed with new key, delete old one:
// await deleteApiKey('key_old_id', accountKey);
}
async function deleteApiKey(keyId: string, accountKey: string) {
const response = await fetch(
`https://api.swiftcache.io/api/v1/api-keys/${keyId}`,
{
method: 'DELETE',
headers: { 'Authorization': `Bearer ${accountKey}` }
}
);
if (response.ok) {
console.log('Key deleted successfully');
}
}
Python Rotation Example
import requests
from datetime import datetime
def rotate_api_key(instance_id, account_key):
# Create new key
response = requests.post(
f'https://api.swiftcache.io/api/v1/instances/{instance_id}/api-keys',
headers={'Authorization': f'Bearer {account_key}'},
json={'name': f'{datetime.now().isoformat()}-rotation'}
)
response.raise_for_status()
new_key = response.json()['createdKey']
print(f"New key: {new_key['plainTextKey']}")
# Return for deployment
return new_key['plainTextKey']
def delete_api_key(key_id, account_key):
response = requests.delete(
f'https://api.swiftcache.io/api/v1/api-keys/{key_id}',
headers={'Authorization': f'Bearer {account_key}'}
)
response.raise_for_status()
print("Key deleted")
Lost Your Key? Here's What to Do
If you lost your API key and can't remember it:
-
Delete the old key (irreversible)
curl -X DELETE \ -H "Authorization: Bearer sk_live_your_account_key" \ https://api.swiftcache.io/api/v1/api-keys/key_xyz789 -
Create a new key for the instance
curl -X POST \ -H "Authorization: Bearer sk_live_your_account_key" \ -H "Content-Type: application/json" \ -d '{"name": "replacement-key"}' \ https://api.swiftcache.io/api/v1/instances/inst_def456/api-keys -
Immediately save the plainTextKey from response
-
Update all applications to use the new key
-
Test that everything still works
Time required: ~5-10 minutes of downtime if you update gradually
Security Best Practices
Do's
- Save keys securely - Use password managers or secrets management systems
- Use environment variables - Load from
.envor secrets, never hardcode - Rotate regularly - Every 90 days is reasonable
- Use one key per app - Easier to rotate and audit
- Monitor lastUsed - Detect unusual patterns
Don'ts
- Never commit keys to git - Even in private repos, it's leaked in history
- Never share in Slack/email - Use secure channels for secret distribution
- Never log keys - They might end up in log files
- Never put in configs - Config files get copied between servers
- Never use default keys in production - Create unique keys for each environment
Example: Secure .env Usage
# .env (in .gitignore)
SWIFTCACHE_API_KEY=sc_live_9f8e7d6c5b4a3f2e1d0c9b8a7f6e5d4c
# .gitignore
.env
.env.local
.env.*.local
// app.js
require('dotenv').config();
const apiKey = process.env.SWIFTCACHE_API_KEY;
if (!apiKey) {
throw new Error('SWIFTCACHE_API_KEY not set in .env');
}
// Use apiKey
Environment-Specific Keys
Create different keys for different environments:
# .env.local (development, never committed)
SWIFTCACHE_API_KEY=sc_live_dev_xxxxx
# Production (stored in AWS Secrets Manager)
# Loaded via: aws secretsmanager get-secret-value --secret-id SwiftCache/Prod/ApiKey
Troubleshooting Authentication
Error: "Authentication required"
Error: Authentication required (401)
Cause: Missing or invalid API key
Fix:
// Wrong
client = createClient({ host, port }); // No password!
// Right
client = createClient({ host, port, password: apiKey });
Error: "Invalid authentication token"
Error: Invalid authentication token (401)
Causes:
- Key is malformed or corrupted
- Key was deleted
- Using test key in production (or vice versa)
Fix:
- Verify key starts with
sc_live_ - Check it's not truncated or modified
- Create a new key if old one is corrupted
Error: "Access denied"
Error: WRONGPASS invalid username-password pair (ACL error)
Cause: Wrong key for this instance
Fix:
# Get instance details to see what keys are bound
curl -H "Authorization: Bearer sk_live_xxx" \
https://api.swiftcache.io/api/v1/instances/inst_abc123
# Check that you're using one of the apiKeys listed in response
Connection times out
Error: connect ETIMEDOUT
Causes:
- Hostname is wrong
- Instance is still PROVISIONING
- Network/firewall issue
Fix:
# Check instance is RUNNING
curl -H "Authorization: Bearer sk_live_xxx" \
https://api.swiftcache.io/api/v1/instances/inst_abc123
# If PROVISIONING, wait longer
# If RUNNING, verify hostname is correct
# If network issue, check firewall rules
API Key in Code Examples
Throughout SwiftCache docs you'll see:
curl -H "Authorization: Bearer sk_live_your_api_key_here"
Replace sk_live_your_api_key_here with your actual key:
- Starts with
sc_live_ - 40+ characters long
- Saved when you created the instance
Summary
API keys are how SwiftCache authenticates your requests. Remember:
- Save immediately after instance creation
- Never lose it - shown only once
- Use as password in Redis clients
- Rotate regularly for security
- Keep confidential - treat like passwords
- Create multiple keys for different apps/teams
Your API key is the master credential for your Redis instance. Guard it carefully!