$120 tested Claude codes · real before/after data · Full tier $15 one-timebuy --sheet=15 →
$Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. download --free →
clskills.sh — terminal v2.4 — 2,347 skills indexed● online
[CL]Skills_
Authenticationintermediate

API Key Auth

Share

Create API key authentication system

Works with OpenClaude

You are a backend authentication engineer. The user wants to create a complete API key authentication system with generation, validation, storage, and rate limiting.

What to check first

  • Verify you have a database setup (PostgreSQL/MongoDB) with write permissions
  • Run npm list express dotenv bcrypt to confirm authentication dependencies are installed
  • Check that your environment supports storing secrets (.env file or secrets manager)

Steps

  1. Create an API keys table with columns: id, key_hash, user_id, name, created_at, last_used, is_active, rate_limit
  2. Generate cryptographically secure random keys using crypto.randomBytes(32).toString('hex')
  3. Hash keys before storage using bcrypt with salt rounds of 10 to prevent plaintext exposure
  4. Create middleware to extract API key from Authorization: Bearer <key> header
  5. Implement key validation by hashing the incoming key and comparing against stored hash
  6. Add rate limiting per API key using in-memory store or Redis with sliding window counters
  7. Track last_used timestamp on every successful authentication for audit trails
  8. Return proper HTTP status codes: 401 for missing/invalid keys, 429 for rate limit exceeded

Code

import express from 'express';
import crypto from 'crypto';
import bcrypt from 'bcrypt';
import dotenv from 'dotenv';

dotenv.config();
const app = express();

// In-memory rate limit store (use Redis in production)
const rateLimitStore = new Map();

// Simulated database (replace with real DB client)
const apiKeysDb = new Map();

// Generate new API key
export async function generateApiKey(userId, keyName) {
  const rawKey = crypto.randomBytes(32).toString('hex');
  const keyHash = await bcrypt.hash(rawKey, 10);
  
  const keyRecord = {
    id: crypto.randomUUID(),
    key_hash: keyHash,
    user_id: userId,
    name: keyName,
    created_at: new Date(),
    last_used: null,
    is_active: true,
    rate_limit: 1000 // requests per hour
  };
  
  // Store hashed key in database
  apiKeysDb.set(keyRecord.id, keyRecord);
  
  // Return raw key ONLY on creation (never again)
  return {
    key_id: keyRecord.id,
    api_key: rawKey, // Show once to user
    key_name: keyName,
    created_at: keyRecord.created_at
  };
}

// Validate API key middleware
export async function validateApiKey(req, res, next) {
  const authHeader = req.headers.authorization;
  
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Missing API key' });

Note: this example was truncated in the source. See the GitHub repo for the latest full version.

Common Pitfalls

  • Treating this skill as a one-shot solution — most workflows need iteration and verification
  • Skipping the verification steps — you don't know it worked until you measure
  • Applying this skill without understanding the underlying problem — read the related docs first

When NOT to Use This Skill

  • When a simpler manual approach would take less than 10 minutes
  • On critical production systems without testing in staging first
  • When you don't have permission or authorization to make these changes

How to Verify It Worked

  • Run the verification steps documented above
  • Compare the output against your expected baseline
  • Check logs for any warnings or errors — silent failures are the worst kind

Production Considerations

  • Test in staging before deploying to production
  • Have a rollback plan — every change should be reversible
  • Monitor the affected systems for at least 24 hours after the change

Quick Info

Difficultyintermediate
Version1.0.0
AuthorClaude Skills Hub
authapi-keyssystem

Install command:

curl -o ~/.claude/skills/api-key-auth.md https://claude-skills-hub.vercel.app/skills/auth/api-key-auth.md

Related Authentication Skills

Other Claude Code skills in the same category — free to download.

Want a Authentication skill personalized to YOUR project?

This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.