QA
Beginner LevelAuthentication & Authorization

What are API Keys and when are they appropriate for service-to-service authentication?

❓ Interview Prompt: Explain API Key prefixing, hashing before DB storage, scopes, revocation, and use cases vs OAuth 2.0.

API Keys are unique secret strings (e.g. 'sk_live_9921...') assigned to software projects or developer accounts to identify and authenticate incoming API requests.

Storage Best Practices:

1
Never Store Plaintext API Keys: Just like passwords, store only SHA-256 hashes of API keys in the database.
2
Prefixing: Include a identifiable prefix (e.g. 'sk_live_' or 'pk_test_') to allow automated secret scanning tools (GitHub Secret Scanning) to detect leaked keys in public code repositories.

When to Use:

Ideal for developer API access, CLI tools, and simple machine-to-machine integrations. Use OAuth 2.0 when acting on behalf of delegate end-users.

Code Implementation Example

typescript
import crypto from 'crypto';

function generateApiKey(): { apiKey: string; keyHash: string; keyPrefix: string } {
  const rawSecret = crypto.randomBytes(24).toString('hex');
  const apiKey = "sk_live_" + rawSecret;
  const keyPrefix = apiKey.slice(0, 12); // "sk_live_a1b2"
  const keyHash = crypto.createHash('sha256').update(apiKey).digest('hex');

  return { apiKey, keyHash, keyPrefix }; // Return raw secret ONLY ONCE to user!
}
💡Generating prefixed API keys and SHA-256 database hashes.
🎯 Interview Key Takeaway

Prefix API keys for secret scanner detection and store only SHA-256 key hashes in database tables.

#API Keys#Hashing#Secrets#Machine-to-Machine#Beginner
Back to all Authentication & Authorization Questions→

More Authentication & Authorization Interview Questions

Beginner LevelAuthentication & Authorization

Compare JWT Token Authentication versus Stateful Sessions, and explain OAuth 2.0 PKCE flow.

Beginner LevelAuthentication & Authorization

What is the fundamental difference between Authentication (AuthN) and Authorization (AuthZ)?

Beginner LevelAuthentication & Authorization

Why should passwords never be stored in plain text and how do bcrypt and Argon2id work?