Skip to content

API Key Authentication — Implementing API Key Auth for Services

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you'll learn about Api Key Authentication. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

API key authentication provides a simple, scalable authentication mechanism for programmatic access to APIs.

// API key generation and validation
const crypto = require('crypto');

function generateApiKey() {
  const raw = crypto.randomBytes(32).toString('base64url');
  const prefix = 'scan_';
  const key = prefix + raw;
  const hash = crypto.createHash('sha256').update(key).digest('hex');

  // Store hash, return raw key once
  return { key, hash };
}

async function validateApiKey(req, res, next) {
  const apiKey = req.headers['x-api-key'];
  if (!apiKey) return res.status(401).json({ error: 'API key required' });

  const hash = crypto.createHash('sha256').update(apiKey).digest('hex');
  const keyRecord = await db.apiKeys.findOne({ hash });

  if (!keyRecord) return res.status(401).json({ error: 'Invalid API key' });
  if (keyRecord.expires_at && keyRecord.expires_at < new Date()) {
    return res.status(401).json({ error: 'API key expired' });
  }
  if (!keyRecord.is_active) return res.status(401).json({ error: 'API key revoked' });

  req.apiKeyRecord = keyRecord;
  next();
}

// Key scoping
const keyRecord = {
  name: 'CI/CD Pipeline',
  scopes: ['scan:create', 'scan:read'],
  rate_limit: { requests: 1000, per: 'hour' },
  ip_restrictions: ['203.0.113.0/24']
};

API keys should be treated as credentials and stored securely using hashing with individual key identification.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro