npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

simple-oauth-date

v1.0.1

Published

Node.js client for OAuth2

Downloads

1

Readme

NPM Package Version Build Status Dependency Status

Simple OAuth2

Node.js client library for OAuth2 (this library supports both callbacks or promises for async flow).

OAuth2 lets users grant the access to the desired resources to third party applications, giving them the possibility to enable and disable those accesses whenever they want.

Simple OAuth2 supports the following flows.

Table of Contents

Requirements

Node client library is tested against the latest minor Node versions: 4, 5 and 6.

To use in older node version, please use [email protected].

Getting started

Installation

Install the client library using npm:

  $ npm install --save simple-oauth2

Options

Simple OAuth2 accepts an object with the following valid params.

  • client - required object with the following properties:

    • id - Service registered client id. Required.
    • secret - Service registered client secret. Required.
    • secretParamName - Parameter name used to send the client secret. Default to client_secret.
    • idParamName - Parameter name used to send the client id. Default to client_id.
  • auth - required object with the following properties.

    • tokenHost - String used to set the host to request the tokens to. Required.
    • tokenPath - String path to request an access token. Default to /oauth/token.
    • revokePath - String path to revoke an access token. Default to /oauth/revoke.
    • authorizeHost - String used to set the host to request an "authorization code". Default to the value set on auth.tokenHost.
    • authorizePath - String path to request an authorization code. Default to /oauth/authorize.
  • http optional object used to set global options to the internal http library (request-js).

    • Any key is allowed here. Default to headers.Accept = application/json.
  • options optional object to setup the module.

    • bodyFormat - Format of data sent in the request body. Valid values are form or json. Defaults to form.
    • useBodyAuth - Whether or not the client.id/client.secret params are sent in the request body. Defaults to true.
    • useBasicAuthorizationHeader - Whether or not the Basic Authorization header should be sent at the token request.
// Set the configuration settings
const credentials = {
  client: {
    id: '<client-id>',
    secret: '<client-secret>'
  },
  auth: {
    tokenHost: 'https://api.oauth.com'
  }
};

// Initialize the OAuth2 Library
const oauth2 = require('simple-oauth2').create(credentials);

Example of Usage

See the example folder.

OAuth2 Supported flows

Authorization Code flow

The Authorization Code flow is made up from two parts. At first your application asks to the user the permission to access their data. If the user approves the OAuth2 server sends to the client an authorization code. In the second part, the client POST the authorization code along with its client secret to the oauth server in order to get the access token.

const oauth2 = require('simple-oauth2').create(credentials);

// Authorization oauth2 URI
const authorizationUri = oauth2.authorizationCode.authorizeURL({
  redirect_uri: 'http://localhost:3000/callback',
  scope: '<scope>',
  state: '<state>'
});

// Redirect example using Express (see http://expressjs.com/api.html#res.redirect)
res.redirect(authorizationUri);

// Get the access token object (the authorization code is given from the previous step).
const tokenConfig = {
  code: '<code>',
  redirect_uri: 'http://localhost:3000/callback'
};

// Callbacks
// Save the access token
oauth2.authorizationCode.getToken(tokenConfig, (error, result) => {
  if (error) {
    return console.log('Access Token Error', error.message);
  }

  const token = oauth2.accessToken.create(result);
});

// Promises
// Save the access token
oauth2.authorizationCode.getToken(tokenConfig)
.then((result) => {
  const token = oauth2.accessToken.create(result);
})
.catch((error) => {
  console.log('Access Token Error', error.message);
});

Password Credentials Flow

This flow is suitable when the resource owner has a trust relationship with the client, such as its computer operating system or a highly privileged application. Use this flow only when other flows are not viable or when you need a fast way to test your application.

const oauth2 = require('simple-oauth2').create(credentials);

// Get the access token object.
const tokenConfig = {
  username: 'username',
  password: 'password' 
};

// Callbacks
// Save the access token
oauth2.ownerPassword.getToken(tokenConfig, (error, result) => {
  if (error) {
    return console.log('Access Token Error', error.message);
  }

  const token = oauth2.accessToken.create(result);
});

// Promises
// Save the access token
oauth2.ownerPassword
  .getToken(tokenConfig)
  .then((result) => {
    const token = oauth2.accessToken.create(result);

    return token;
  });

Client Credentials Flow

This flow is suitable when client is requesting access to the protected resources under its control.

const oauth2 = require('simple-oauth2').create(credentials);
const tokenConfig = {};

// Callbacks
// Get the access token object for the client
oauth2.clientCredentials.getToken(tokenConfig, (error, result) => {
  if (error) {
    return console.log('Access Token Error', error.message);
  }

  const token = oauth2.accessToken.create(result);
});


// Promises
// Get the access token object for the client
oauth2.clientCredentials
  .getToken(tokenConfig)
  .then((result) => {
    const token = oauth2.accessToken.create(result);
  })
  .catch((error) => {
    console.log('Access Token error', error.message);
  });

Helpers

Access Token object

When a token expires we need to refresh it. Simple OAuth2 offers the AccessToken class that add a couple of useful methods to refresh the access token when it is expired.

// Sample of a JSON access token (you got it through previous steps)
const tokenObject = {
  'access_token': '<access-token>',
  'refresh_token': '<refresh-token>',
  'expires_in': '7200'
};

// Create the access token wrapper
const token = oauth2.accessToken.create(tokenObject);

// Check if the token is expired. If expired it is refreshed.
if (token.expired()) {
  // Callbacks
  token.refresh((error, result) => {
    token = result;
  })

  // Promises
  token.refresh()
  .then((result) => {
    token = result;
  });
}

When you've done with the token or you want to log out, you can revoke the access token and refresh token.


// Callbacks
// Revoke only the access token
token.revoke('access_token', (error) => {
  // Session ended. But the refresh_token is still valid.

  // Revoke the refresh_token
  token.revoke('refresh_token', (error) => {
    console.log('token revoked.');
  });
});

// Promises
// Revoke only the access token
token.revoke('access_token')
  .then(() => {
    // Revoke the refresh token
    return token.revoke('refresh_token');
  })
  .then(() => {
    console.log('Token revoked');
  })
  .catch((error) => {
    console.log('Error revoking token.', error.message);
  });

Errors

Exceptions are raised when a 4xx or 5xx status code is returned.

HTTPError

Through the error message attribute you can access the JSON representation based on HTTP status and error message.

// Callbacks
oauth2.authorizationCode.getToken({}, (error, token) => {
  if (error) {
    return console.log(error.message);
  }
});

// Promises
oauth2.authorizationCode
  .getToken({})
  .catch((error) => {
    console.log(error.message);
  });

// => { "status": "401", "message": "Unauthorized" }

Contributing

See CONTRIBUTING

Authors

Andrea Reginato

Contributors

Special thanks to the following people for submitting patches.

Changelog

See CHANGELOG

License

Simple OAuth 2.0 is licensed under the Apache License, Version 2.0