CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-passport-oauth2

OAuth 2.0 authentication strategy for Passport that enables developers to implement OAuth 2.0-based authentication in Node.js applications.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

error-handling.mddocs/

Error Handling

Passport OAuth2 provides specialized error classes for different OAuth 2.0 failure scenarios, each with proper error codes and HTTP status mapping following RFC 6749 specifications.

Capabilities

AuthorizationError

Represents errors in response to authorization requests, following RFC 6749 section 4.1.2.1.

/**
 * Authorization error constructor
 * @param message - Human-readable error description
 * @param code - OAuth 2.0 error code
 * @param uri - URI reference for additional error information
 * @param status - HTTP status code
 */
function AuthorizationError(message, code, uri, status);

Properties:

  • name: "AuthorizationError"
  • message: Error description
  • code: OAuth error code (default: 'server_error')
  • uri: Error URI reference
  • status: HTTP status code with automatic mapping:
    • access_denied → 403
    • server_error → 502
    • temporarily_unavailable → 503
    • Default → 500

Usage Example:

const { AuthorizationError } = require('passport-oauth2');

// Create authorization error
const error = new AuthorizationError(
  'The user denied the request',
  'access_denied',
  'https://example.com/error',
  403
);

console.log(error.name);    // "AuthorizationError"
console.log(error.code);    // "access_denied"
console.log(error.status);  // 403

TokenError

Represents errors received from token endpoints, following RFC 6749 section 5.2.

/**
 * Token error constructor
 * @param message - Human-readable error description
 * @param code - OAuth 2.0 error code (default: 'invalid_request')
 * @param uri - URI reference for additional error information
 * @param status - HTTP status code (default: 500)
 */
function TokenError(message, code, uri, status);

Properties:

  • name: "TokenError"
  • message: Error description
  • code: OAuth error code (default: 'invalid_request')
  • uri: Error URI reference
  • status: HTTP status code (default: 500)

Common OAuth Token Error Codes:

  • invalid_request: The request is missing a required parameter
  • invalid_client: Client authentication failed
  • invalid_grant: The authorization grant is invalid
  • unauthorized_client: Client is not authorized for this grant type
  • unsupported_grant_type: Grant type is not supported
  • invalid_scope: Requested scope is invalid

Usage Example:

const { TokenError } = require('passport-oauth2');

// Create token error
const error = new TokenError(
  'The authorization code is invalid',
  'invalid_grant',
  'https://example.com/error/invalid_grant',
  400
);

console.log(error.name);    // "TokenError"
console.log(error.code);    // "invalid_grant"
console.log(error.status);  // 400

InternalOAuthError

Wraps errors generated by the node-oauth library, providing better error formatting and debugging information.

/**
 * Internal OAuth error constructor
 * @param message - Human-readable error description
 * @param err - Original error object from node-oauth
 */
function InternalOAuthError(message, err);

/**
 * Returns formatted string representation of the error
 * @returns String representation including OAuth error details
 */
InternalOAuthError.prototype.toString = function();

Properties:

  • name: "InternalOAuthError"
  • message: Error description
  • oauthError: Original error object from node-oauth

Error Formatting: The toString() method provides enhanced error information:

  • If oauthError is an Error object, returns the original error string
  • If oauthError has statusCode and data, includes both in format: (status: 400 data: {"error":"invalid_request"})
  • Otherwise returns the standard error message

Usage Example:

const { InternalOAuthError } = require('passport-oauth2');

// Wrap an OAuth error
const originalError = {
  statusCode: 400,
  data: '{"error":"invalid_request","error_description":"Missing client_id"}'
};

const error = new InternalOAuthError('Failed to obtain access token', originalError);

console.log(error.name);        // "InternalOAuthError"
console.log(error.message);     // "Failed to obtain access token"
console.log(error.oauthError);  // Original error object
console.log(error.toString());  // Enhanced error string with status and data

Error Handling in Strategy

The OAuth2Strategy automatically creates appropriate error objects during the authentication flow:

// In OAuth2Strategy implementation
try {
  // OAuth operations
} catch (err) {
  if (err.statusCode && err.data) {
    // Try to parse as OAuth error response
    const parsedError = this.parseErrorResponse(err.data, err.statusCode);
    if (parsedError) {
      return this.error(parsedError); // TokenError or custom error
    }
  }
  // Fallback to InternalOAuthError
  return this.error(new InternalOAuthError('OAuth request failed', err));
}

Error Response Parsing

The strategy includes a virtual parseErrorResponse method that can be overridden for provider-specific error handling:

/**
 * Parse error response from OAuth 2.0 endpoint (virtual method)
 * Override this method to handle provider-specific error formats
 * @param body - Response body string
 * @param status - HTTP status code
 * @returns TokenError instance or null if parsing fails
 */
OAuth2Strategy.prototype.parseErrorResponse = function(body, status);

Default Implementation:

OAuth2Strategy.prototype.parseErrorResponse = function(body, status) {
  try {
    const json = JSON.parse(body);
    if (json.error) {
      return new TokenError(json.error_description, json.error, json.error_uri);
    }
  } catch (e) {
    // Parsing failed, return null
  }
  return null;
};

Custom Error Parsing Example:

class CustomOAuth2Strategy extends OAuth2Strategy {
  parseErrorResponse(body, status) {
    try {
      const json = JSON.parse(body);
      // Handle provider-specific error format
      if (json.errorCode) {
        return new TokenError(json.errorMessage, json.errorCode, json.helpUrl, status);
      }
    } catch (e) {
      // Fallback to parent implementation
      return super.parseErrorResponse(body, status);
    }
    return null;
  }
}

Install with Tessl CLI

npx tessl i tessl/npm-passport-oauth2

docs

error-handling.md

index.md

state-management.md

tile.json