Backend API Key Security — Securing API Key Authentication
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you'll learn about Backend Api Key Security. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
API key security ensures programmatic access credentials are protected from theft, misuse, and exposure.
// Secure API key management
class ApiKeyManager {
constructor() {
this.keyPrefix = 'scan_';
this.hashAlgorithm = 'sha256';
}
generateApiKey(name, permissions, options = {}) {
const rawKey = crypto.randomBytes(32).toString('base64url');
const keyId = crypto.randomUUID();
const prefixedKey = `${this.keyPrefix}${rawKey}`;
const hash = crypto.createHash(this.hashAlgorithm).update(prefixedKey).digest('hex');
const keyRecord = {
keyId,
name,
hash,
permissions,
createdAt: new Date().toISOString(),
expiresAt: options.expiresAt || null,
maxUses: options.maxUses || null,
useCount: 0,
lastUsed: null,
ipRestrictions: options.ipRestrictions || [],
isActive: true
};
return { key: prefixedKey, record: keyRecord };
}
async validateApiKey(apiKey) {
if (!apiKey || !apiKey.startsWith(this.keyPrefix)) {
return { valid: false, reason: 'Invalid key format' };
}
const hash = crypto.createHash(this.hashAlgorithm).update(apiKey).digest('hex');
const keyRecord = await this.findByHash(hash);
if (!keyRecord) return { valid: false, reason: 'Key not found' };
if (!keyRecord.isActive) return { valid: false, reason: 'Key deactivated' };
if (keyRecord.expiresAt && new Date(keyRecord.expiresAt) < new Date()) {
return { valid: false, reason: 'Key expired' };
}
if (keyRecord.maxUses && keyRecord.useCount >= keyRecord.maxUses) {
return { valid: false, reason: 'Key usage limit exceeded' };
}
// Update usage
await this.recordUsage(keyRecord.keyId);
return { valid: true, keyRecord };
}
async rotateKey(keyId) {
const existing = await this.getKeyRecord(keyId);
if (!existing) throw new Error('Key not found');
// Deactivate old key
await this.deactivateKey(keyId);
// Generate new key with same permissions
return this.generateApiKey(existing.name, existing.permissions, {
ipRestrictions: existing.ipRestrictions
});
}
async deactivateKey(keyId) {
// Store in Redis with TTL for validation cache
await redis.set(`deactivated_key:${keyId}`, 'true', 'EX', 86400);
// Update database
await db.apiKeys.update({ keyId }, { isActive: false, deactivatedAt: new Date() });
}
}
// API key validation middleware
async function apiKeyMiddleware(req, res, next) {
const apiKey = req.headers['x-api-key'] || req.query.api_key;
if (!apiKey) return res.status(401).json({ error: 'API key required' });
const result = await apiKeyManager.validateApiKey(apiKey);
if (!result.valid) {
return res.status(401).json({ error: 'Invalid API key', reason: result.reason });
}
req.apiKey = result.keyRecord;
next();
}
Secure API key management prevents key exposure through hashing, rotation, and usage tracking.
← Previous
Backend Security Compliance — Meeting Security Compliance Standards
Next →
Backend Secure Cookie Configuration — Hardening Cookie-Based Sessions
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro