OAuth 1.0a Request Authorization

2.2.6 · active · verified Tue Apr 21

oauth-1.0a is a JavaScript library providing a streamlined way to authorize requests using the OAuth 1.0a protocol in both Node.js and browser environments. It abstracts away the complexities of generating `oauth_consumer_key`, `oauth_nonce`, `oauth_signature`, and other OAuth 1.0a parameters, allowing developers to use their preferred HTTP client (e.g., `request`, `jQuery.ajax`). The current stable version is 2.2.6, with minor updates addressing dependency bumps and TypeScript type improvements. A key differentiator is its separation of cryptographic hashing, requiring users to provide a `hash_function` implementation, which allows for flexibility with native Node.js `crypto` or browser-specific libraries like CryptoJS. It aims to simplify integration with popular OAuth 1.0a services like Twitter, Flickr, and Bitbucket.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `oauth-1.0a` library for Node.js, configure a SHA1 hash function using `node:crypto`, and generate authorization data for a sample GET request. It shows how to obtain the authorization header required for sending authenticated requests to OAuth 1.0a services.

import * as crypto from 'node:crypto';
import OAuth from 'oauth-1.0a';

const consumerKey = process.env.OAUTH_CONSUMER_KEY ?? '';
const consumerSecret = process.env.OAUTH_CONSUMER_SECRET ?? '';

const oauth = OAuth({
    consumer: { key: consumerKey, secret: consumerSecret },
    signature_method: 'HMAC-SHA1',
    hash_function(base_string, key) {
        return crypto
            .createHmac('sha1', key)
            .update(base_string)
            .digest('base64');
    },
});

const request_data = {
    url: 'https://api.twitter.com/1.1/account/verify_credentials.json',
    method: 'GET',
    data: {},
};

// Example token (for user-specific requests)
const token = {
    key: process.env.OAUTH_TOKEN_KEY ?? '',
    secret: process.env.OAUTH_TOKEN_SECRET ?? ''
};

const authorized_request = oauth.authorize(request_data, token);

// To get the header for an HTTP client:
const headers = oauth.toHeader(authorized_request);

console.log('Authorization Header:', headers.Authorization);
// Example of how you would typically send the request with 'fetch' or similar:
// fetch(request_data.url, {
//   method: request_data.method,
//   headers: {
//     ...headers,
//     'Content-Type': 'application/json' // Or other appropriate content type
//   }
// }).then(res => res.json()).then(data => console.log(data));

console.log('OAuth authorization data generated successfully.');

view raw JSON →