API key authentication for service-to-service calls

8678
0

While JWT works well for user authentication, service-to-service communication often uses simpler API key authentication. I generate cryptographically random API keys using SecureRandom.hex(32) and store them hashed in the database, similar to passwords. Clients send keys via Authorization: Bearer <key> or custom X-API-Key headers. Each key has associated scopes defining permissions, rate limits, and belongs to a specific account or service. I support key rotation by allowing multiple active keys per account. API keys are logged (partially, like key_abc...xyz) for audit purposes. For security, I require HTTPS for all API requests and implement rate limiting per key. Keys can be revoked immediately by deletion from the database.