Install simple-oauth2 via npm
masterInstall the client library using npm to use it in your Node.js project.
npm install --save simple-oauth2repository·master·Indexed 23 days ago
https://github.com/lelylan/simple-oauth2A Node.js client library for the OAuth 2.0 authorization framework. It supports multiple grant types, including Authorization Code, Resource Owner Password, and Client Credentials. The library provides utilities for generating authorization URLs, exchanging codes for access tokens, refreshing expired tokens, and revoking tokens.
Install the client library using npm to use it in your Node.js project.
npm install --save simple-oauth2To initialize a client, provide a configuration object containing client credentials (id and secret) and auth settings (such as tokenHost).
const config = {
client: {
id: '<client-id>',
secret: '<client-secret>'
},
auth: {
tokenHost: 'https://api.oauth.com'
}
};
const { ClientCredentials, ResourceOwnerPassword, AuthorizationCode } = require('simple-oauth2');Before running any of the provided examples in the example/ directory, you must set the following environment variables to provide your OAuth2 credentials:
CLIENT_ID: Your application's client ID.CLIENT_SECRET: Your application's client secret.export CLIENT_ID="your client id"
export CLIENT_SECRET="your client secret"To handle long-lived applications, you can refresh expired access tokens.
AccessToken to JSON to store it in a database.client.createToken(parsedJson) to recreate the AccessToken instance from stored data.accessToken.expired() to check if the token is invalid. To avoid race conditions caused by network latency, pass a window in seconds (e.g., accessToken.expired(300)) to refresh the token preemptively.await accessToken.refresh(refreshParams) to obtain a new token.Warning: Tokens obtained via the ClientCredentials grant may not be refreshable. You should fetch a new token instead.
// Rehydrating and refreshing a token
async function run() {
const accessTokenJSONString = await getPersistedAccessTokenJSON();
let accessToken = client.createToken(JSON.parse(accessTokenJSONString));
const EXPIRATION_WINDOW_IN_SECONDS = 300;
if (accessToken.expired(EXPIRATION_WINDOW_IN_SECONDS)) {
try {
const refreshParams = {
scope: '<scope>',
};
accessToken = await accessToken.refresh(refreshParams);
} catch (error) {
console.log('Error refreshing access token: ', error.message);
}
}
}All grant classes (AuthorizationCode, ResourceOwnerPassword, ClientCredentials) accept a configuration object containing client, auth, http, and options properties.
id: Service registered client ID.secret: Service registered client secret.idParamName: Parameter name for client ID (defaults to client_id).secretParamName: Parameter name for client secret (defaults to client_secret).tokenHost: Base URL for obtaining access tokens.tokenPath: URL path for tokens (defaults to /oauth/token).refreshPath: URL path for refreshing tokens (defaults to auth.tokenPath).revokePath: URL path for revoking tokens (defaults to /oauth/revoke).authorizeHost: Base URL for authorization codes (only for AuthorizationCode, defaults to auth.tokenHost).authorizePath: URL path for authorization codes (only for AuthorizationCode, defaults to /oauth/authorize).Sets default options for the internal wreck library. All options except baseUrl are allowed.
json: JSON response parsing mode (defaults to strict).redirects: Number of redirects to follow (defaults to false).headers: HTTP headers (e.g., accept defaults to application/json). Note that authorization is managed by the library.scopeSeparator: Character used to separate scopes (defaults to empty space).credentialsEncodingMode: Encoding for header authorization. Use loose if the provider is non-compliant with OAuth 2.0 spec (defaults to strict).bodyFormat: Request body format. Valid values: form or json (defaults to form).authorizationMethod: How to send credentials. Valid values: header or body (defaults to header). If body is used, bodyFormat determines the format.The library provides specific configuration schemas depending on the OAuth2 grant type you are implementing. While they share common structures (client, auth, http, and options), the requirements for the auth object vary.
Requires client, auth (including authorization endpoints), http, and options.
Requires client, auth (token endpoints only), http, and options.
Requires client, auth (token endpoints only), http, and options.
When configuring the simple-oauth2 client, you can control how credentials are sent and how the request body is formatted using the following options:
Determines if client credentials (ID and Secret) are sent in the HTTP headers or the request body.
header: Sends credentials via the Authorization header using Basic authentication.body: Includes credentials in the request body using the configured idParamName and secretParamName.Determines the Content-Type and encoding of the request payload.
form: Uses application/x-www-form-urlencoded encoding.json: Uses application/json encoding.These settings are applied internally by the RequestOptions class to prepare outgoing HTTP requests.
The module uses the debug package. To enable detailed diagnostic logging, set the DEBUG environment variable to *simple-oauth2*.
DEBUG=*simple-oauth2*To see a reference implementation for Dropbox, view the ./dropbox.js module or execute the example directly via npm.
Note: Ensure CLIENT_ID and CLIENT_SECRET are exported in your environment first.
npm run start:dropboxThe Authorization Code grant is used by confidential and public clients to exchange an authorization code for an access token.
client.authorizeURL() to generate the URL for redirecting the user to the authorization server.code, use client.getToken() to exchange that code for an access token.async function run() {
const client = new AuthorizationCode(config);
const authorizationUri = client.authorizeURL({
redirect_uri: 'http://localhost:3000/callback',
scope: '<scope>',
state: '<state>',
customParam: 'foo', // non-standard oauth params may be passed as well
});
// Redirect example using Express (see http://expressjs.com/api.html#res.redirect)
res.redirect(authorizationUri);
const tokenParams = {
code: '<code>',
redirect_uri: 'http://localhost:3000/callback',
scope: '<scope>',
};
try {
const accessToken = await client.getToken(tokenParams);
} catch (error) {
console.log('Access Token Error', error.message);
}
}
run();To see a reference implementation for Github, view the ./github.js module or execute the example directly via npm.
Note: Ensure CLIENT_ID and CLIENT_SECRET are exported in your environment first.
npm run start:githubThis grant type exchanges a user's credentials (username and password) directly for an access token. Note: This method is generally discouraged in modern OAuth 2.0 implementations.
async function run() {
const client = new ResourceOwnerPassword(config);
const tokenParams = {
username: 'username',
password: 'password',
scope: '<scope>',
};
try {
const accessToken = await client.getToken(tokenParams);
} catch (error) {
console.log('Access Token Error', error.message);
}
}
run();