MEDIUM open redirectnestjsbearer tokens

Open Redirect in Nestjs with Bearer Tokens

Open Redirect in Nestjs with Bearer Tokens — how this specific combination creates or exposes the vulnerability

An open redirect occurs when an application redirects a user to an arbitrary URL supplied by the attacker. In NestJS, this risk can intersect with Bearer token handling when redirect logic uses user-controlled inputs such as query parameters or request headers without strict validation. If an endpoint accepts a redirect_url parameter and uses it directly in a response, an attacker can craft a link that sends victims to malicious sites while the request carries a valid Bearer token in the Authorization header. The presence of the token does not cause the open redirect, but it can increase the impact because a victim may be already authenticated and the token may be included in browser headers or logs during the redirect flow.

Consider a pattern where a client passes both a token and a redirect target:

// Risky: no validation of redirect_url
@Get('auth/callback')
callback(
  @Query('redirect_url') redirectUrl: string,
  @Header('authorization') authHeader: string,
) {
  const token = this.extractBearerToken(authHeader);
  // ... token validation logic
  return { redirect: redirectUrl };
}

An attacker could supply https://evil.com/steal?token=xxx as redirect_url. Even though the token is extracted for validation, the application may still perform the redirect using the attacker-controlled value, causing the client’s browser to navigate to the malicious site. If the client’s browser automatically includes cookies or if the token is inadvertently reflected, the attacker may gain useful information for phishing or session fixation. OWASP API Security Top 10 includes this as part as 'Broken Redirector' style risks, and the issue is relevant regardless of whether authentication is required; unauthenticated scans by middleBrick can detect such open redirect endpoints during its 12 parallel checks, including Input Validation and Property Authorization assessments.

Another scenario involves returning a 302/307 response with a user-supplied location header. Middle-box components or API gateways might rewrite URLs, but NestJS code must ensure that the target is within an allowed set of domains. Attack patterns like redirect://evil.com or mixed-host schemes can bypass naive prefix checks. Since Bearer tokens are typically handled in headers rather than the URL, the token itself is not leaked via the redirect; however, the flow may still expose internal behavior or authorization state to an attacker. middleBrick’s active LLM security probing and output scanning do not test for open redirect directly, but its Input Validation and Data Exposure checks can surface misconfigured endpoints that may be abused in chained attacks.

Defensive design requires strict allowlisting of redirect targets, rejecting open redirects regardless of authentication state. Do not rely on the absence of a token to mitigate the issue; treat redirect parameters as untrusted even when Bearer tokens are present and validated. Using a mapping from short aliases to full URLs, rather than raw user input, reduces risk significantly.

Bearer Tokens-Specific Remediation in Nestjs — concrete code fixes

Remediation centers on never trusting the redirect target and ensuring token handling does not inadvertently enable unsafe navigation. Below are concrete, safe patterns for NestJS applications that use Bearer tokens.

1. Use an allowlist approach for redirect targets

Maintain a set of trusted domains or paths. Resolve relative URLs to prevent open redirect via encoded or mixed-case schemes.

import { HttpException, HttpStatus, Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { URL } from 'url';

const ALLOWED_HOSTS = new Set(['app.example.com', 'myapp.example.com']);

export function validateRedirectUrl(url: string): string {
  let parsed: URL;
  try {
    parsed = new URL(url);
  } catch {
    throw new HttpException('Invalid redirect URL', HttpStatus.BAD_REQUEST);
  }
  if (!ALLOWED_HOSTS.has(parsed.hostname)) {
    throw new HttpException('Redirect not allowed', HttpStatus.BAD_REQUEST);
  }
  return parsed.toString();
}

// Usage in controller
@Get('auth/callback')
callback(
  @Query('redirect_url') redirectUrl: string,
  @Header('authorization') authHeader: string,
) {
  const token = this.extractBearerToken(authHeader);
  // validate token and user...
  const safeUrl = validateRedirectUrl(redirectUrl);
  return { redirect: safeUrl };
}

2. Prefer server-side mapping instead of raw URLs

Replace raw redirect parameters with an opaque key that maps to a verified destination on the server.

const redirectMap: Record = {
  'welcome': 'https://app.example.com/dashboard',
  'settings': 'https://app.example.com/settings',
};

@Get('redirect')
redirect(@Query('key') key: string) {
  const target = redirectMap[key];
  if (!target) {
    throw new HttpException('Invalid redirect key', HttpStatus.BAD_REQUEST);
  }
  return { redirect: target };
}

3. Standardize Bearer token extraction and validation

Centralize token extraction to avoid duplication and mistakes. Do not place tokens in URLs or fragments.

private extractBearerToken(header: string): string | null {
  if (!header) return null;
  const [type, token] = header.split(' ');
  return type?.toLowerCase() === 'bearer' ? token : null;
}

4. Use NestJS interceptors for cross-cutting concerns

Apply validation consistently across endpoints that handle redirects and tokens.

@Injectable()
export class RedirectValidationInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable {
    const request = context.switchToHttp().getRequest();
    // Example: ensure no open redirect parameters in query
    if (request.query?.redirect_url) {
      // validation logic as above
    }
    return next.handle();
  }
}

These patterns ensure that Bearer tokens remain in secure headers and are never reflected into redirect targets. They align with defenses for Injection and Improper Authentication flows described in OWASP API Top 10, and they avoid reliance on ad-hoc string checks that can be bypassed. middleBrick’s scans can verify that such controls are present by testing unauthenticated surfaces and reviewing the application’s behavior under the 12 security checks.

Frequently Asked Questions

Can an open redirect leak my Bearer token?
Typically no, because Bearer tokens are sent in the Authorization header and are not automatically included in a redirect navigation. However, an open redirect can still aid phishing or session fixation; always validate redirect targets independently of token presence.
Does middleBrick detect open redirects in NestJS APIs?
Yes, middleBrick’s Input Validation and Property Authorization checks can identify endpoints that accept unchecked redirect parameters. Use the CLI (middlebrick scan ) or the Web Dashboard to review findings and remediation guidance.