OAuth 2.0 authentication strategy for Passport that enables developers to implement OAuth 2.0-based authentication in Node.js applications.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
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.
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 descriptioncode: OAuth error code (default: 'server_error')uri: Error URI referencestatus: HTTP status code with automatic mapping:
access_denied → 403server_error → 502temporarily_unavailable → 503Usage 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); // 403Represents 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 descriptioncode: OAuth error code (default: 'invalid_request')uri: Error URI referencestatus: HTTP status code (default: 500)Common OAuth Token Error Codes:
invalid_request: The request is missing a required parameterinvalid_client: Client authentication failedinvalid_grant: The authorization grant is invalidunauthorized_client: Client is not authorized for this grant typeunsupported_grant_type: Grant type is not supportedinvalid_scope: Requested scope is invalidUsage 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); // 400Wraps 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 descriptionoauthError: Original error object from node-oauthError Formatting:
The toString() method provides enhanced error information:
oauthError is an Error object, returns the original error stringoauthError has statusCode and data, includes both in format: (status: 400 data: {"error":"invalid_request"})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 dataThe 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));
}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