HIGH api key exposurenestjsbearer tokens

Api Key Exposure in Nestjs with Bearer Tokens

Api Key Exposure in Nestjs with Bearer Tokens — how this specific combination creates or exposes the vulnerability

In NestJS applications, Bearer tokens are commonly passed in HTTP headers such as Authorization: Bearer <token>. When these tokens are handled or logged without adequate safeguards, they can be inadvertently exposed. For example, if route handlers, services, or exception filters include the full Authorization header or raw token value in logs, error messages, or API responses, an attacker who can read those logs or responses can obtain the token and use it to impersonate clients.

Another exposure path arises from overly broad CORS configurations in NestJS. If the CORS setup allows origins that should not be trusted, or exposes headers like Authorization to non-trusted frontends, client-side JavaScript may read the response and extract the token. Similarly, misconfigured JSON serialization in NestJS can cause sensitive fields (or entire DTOs) to include token-like values when responses are sent to clients or third-party integrations.

Middleware or interceptors that mirror incoming headers into logs or metadata without redaction also contribute to exposure. A common pattern in NestJS is to attach authorization data to the request context for downstream use; if that context is shared across microservice boundaries or written to a shared cache without encryption, the Bearer token can leak across trust boundaries. Even in unauthenticated public endpoints, if the application echoes back headers for debugging or fails to strip sensitive headers before forwarding requests to upstream services, tokens may be surfaced in responses that should otherwise be anonymous.

These risks are especially relevant when the NestJS application serves both web clients and APIs consumed by third parties. For instance, an improperly configured Swagger/OpenAPI generation setup in NestJS might include security schemes that inadvertently document how tokens are passed, and if combined with debug endpoints, this can aid an attacker in understanding how to target token handling. Because Bearer tokens are typically long-lived compared to session cookies, exposure through logging, serialization, or CORS misconfigurations can lead to extended unauthorized access until token rotation or revocation occurs.

To detect such issues, scanning tools examine how the application processes the Authorization header, whether tokens are reflected in responses or logs, and whether unauthenticated endpoints leak information that could facilitate privilege escalation. They also validate that CORS settings do not expose sensitive headers to untrusted origins and that serialization pipelines do not embed token values in payloads. These checks highlight deviations from secure handling practices for Bearer tokens in NestJS-based APIs.

Bearer Tokens-Specific Remediation in Nestjs — concrete code fixes

Remediation focuses on preventing Bearer token leakage through logging, serialization, and CORS while preserving the necessary use of tokens for authorization.

  • Redact sensitive headers in logging: ensure that request and response logging does not include the Authorization header. In NestJS, you can create a logging filter or interceptor that scrubs the header before it is written.
import { NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

export class RedactAuthInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
    const request = context.switchToHttp().getRequest();
    // Remove or mask Authorization header from request clone used for logging
    const safeHeaderMap = new Map(request.headers);
    if (safeHeaderMap.has('authorization')) {
      safeHeaderMap.set('authorization', 'REDACTED');
    }
    // Attach sanitized headers for downstream logging if needed
    request.headers = Object.fromEntries(safeHeaderMap.entries());
    return next.handle().pipe(
      map((data) => {
        // Optionally sanitize data before it leaves the layer
        return data;
      })
    );
  }
}

  • Secure CORS configuration: explicitly set allowed origins and avoid exposing the Authorization header to untrusted origins.
import { CorsOptions } from '@nestjs/common';

export const corsConfig: CorsOptions = {
  origin: ['https://app.example.com', 'https://admin.example.com'],
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'X-Request-ID'],
  credentials: true,
  exposedHeaders: ['X-Custom-Header'],
  // Do NOT expose 'authorization' in exposedHeaders to untrusted origins
};

  • Avoid echoing tokens in error responses or DTOs: ensure validation pipes and serialization do not pass through raw Authorization values, and do not include token fields in DTOs returned to clients.
import { Exclude } from 'class-transformer';

export class UserProfileResponse {
  id: number;
  email: string;
  @Exclude() // Prevents this from being serialized in responses
  accessToken?: string;
}

  • Apply global validation to strip or reject unexpected header values, and configure Swagger to avoid documenting the Authorization header in a way that implies safe reflection.
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

const config = new DocumentBuilder()
  .setTitle('Secure API')
  .addBearerAuth()
  .build();
const document = SwaggerModule.createDocument(app, config);
// Ensure security definitions do not include examples with real tokens
SwaggerModule.setup('api', app, document);

Frequently Asked Questions

Can scanning detect Bearer token exposure in NestJS APIs?
Yes. Scanners check whether the Authorization header or token values appear in responses, logs, or error messages, and validate CORS and serialization settings that could lead to exposure.
How often should I rotate Bearer tokens used by a NestJS service?
Rotate tokens based on your risk tolerance and compliance requirements. Short-lived tokens with refresh mechanisms reduce the impact of exposure; continuous monitoring of security scores can help detect configuration issues that increase risk.