Skip to main content

ApiKeyService

Package: @nauth-toolkit/core Type: Service

Manages the API key lifecycle and validates keys presented on requests. A key authenticates as its owning user. Available when apiKeys.enabled is true.

import { ApiKeyService } from '@nauth-toolkit/nestjs';

Overview​

  • Keys are stored as SHA-256 hashes; the plaintext is returned once at creation.
  • Expiry is mandatory at creation (a number of days or null for never, subject to config).
  • Optional per-key IP allowlists (IPs / IPv4 CIDR ranges); an empty list means any IP.
  • Route access is opt-in — see the API Keys guide for @AllowApiKey() / @DenyApiKey().
Authorization

This service does not enforce endpoint authorization. Protect management routes with your own guard, and use the decorators/helpers to control which routes accept API-key auth.

Every method takes a request DTO and returns a response DTO, and validates the DTO at runtime so Express/Fastify callers are protected too.

Self-service methods (identity from auth context)​

These act on the currently authenticated user — resolved from request context. They take no user identifier.

createKey(dto)​

Creates a key for the current user and returns the plaintext once.

const { key, apiKey } = await apiKeyService.createKey({
name: 'CI pipeline',
expiresInDays: 90, // required: number of days, or null for never
allowedIps: ['203.0.113.0/24'], // optional IP allowlist
});

dto is a CreateApiKeyDTO. Returns CreateApiKeyResponseDTO — { key, apiKey } where key is the plaintext (shown once).

listKeys()​

Returns ListApiKeysResponseDTO — { apiKeys } (sanitized; never the secret).

updateKey(dto)​

Updates the label and/or IP allowlist (UpdateApiKeyDTO). The secret and expiry are immutable. Returns ApiKeyResponseDTO.

revokeKey(dto)​

Soft-disables a key (RevokeApiKeyDTO; retained for audit). Returns { success: true }.

deleteKey(dto)​

Permanently deletes a key (DeleteApiKeyDTO). Returns { success: true }.

Admin methods (target user by sub)​

Protect these with admin authentication. They act on a user identified by sub and, for creation, bypass allowUserCreation.

await apiKeyService.adminCreateKey({ sub, expiresInDays: 90, allowedIps: ['203.0.113.0/24'] });
await apiKeyService.adminListKeys({ sub });
await apiKeyService.adminUpdateKey({ sub, keyId, allowedIps: ['203.0.113.5'] });
await apiKeyService.adminRevokeKey({ sub, keyId });
await apiKeyService.adminDeleteKey({ sub, keyId });

Validation (internal)​

validateKey(rawKey, callerIp?)​

Validates a presented key by looking up its hash and resolves the owner. Throws a precise NAuthException on failure (invalid/expired/IP-blocked) — used internally by the guard/handler.

const { keyId, sub } = await apiKeyService.validateKey(rawKey, callerIp);

Errors​

API_KEY_INVALID · API_KEY_EXPIRED · API_KEY_IP_NOT_ALLOWED · API_KEY_CREATION_DISABLED · API_KEY_LIMIT_REACHED · API_KEY_EXPIRY_REQUIRED · API_KEY_INDEFINITE_NOT_ALLOWED · API_KEY_EXPIRY_TOO_LONG — see the API Keys guide.