simple-oauth2 vs oauth2-server vs client-oauth2
OAuth 2.0 Libraries for Node.js Comparison
1 Year
simple-oauth2oauth2-serverclient-oauth2
What's OAuth 2.0 Libraries for Node.js?

These libraries provide implementations for OAuth 2.0, a widely used authorization framework that allows third-party services to exchange information without sharing credentials. They facilitate the process of securing APIs and managing user authentication and authorization in web applications. Each library has its own approach and use cases, catering to different needs in OAuth 2.0 implementation.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
simple-oauth2270,6541,63932.7 kB12a year agoApache-2.0
oauth2-server121,1374,060-1905 years agoMIT
client-oauth2110,294539-845 years agoApache-2.0
Feature Comparison: simple-oauth2 vs oauth2-server vs client-oauth2

Use Case

  • simple-oauth2:

    simple-oauth2 can be used for both client and server-side applications. It is particularly useful when you want a straightforward way to implement OAuth 2.0 without the complexity of a full server implementation. It works well in scenarios where you need to authenticate users and access APIs seamlessly.

  • oauth2-server:

    oauth2-server is intended for server-side applications that need to implement an OAuth 2.0 authorization server. It supports various grant types, making it suitable for scenarios where you need to manage user authentication and provide access tokens to clients securely.

  • client-oauth2:

    client-oauth2 is designed for client-side applications, particularly SPAs, where it simplifies the process of obtaining and managing access tokens. It is ideal for scenarios where user interaction is required to authorize access to APIs, such as social media integrations or third-party service access.

Complexity

  • simple-oauth2:

    simple-oauth2 strikes a balance between simplicity and functionality. It is designed to be easy to integrate while still providing enough flexibility to handle various OAuth 2.0 flows, making it suitable for developers looking for a straightforward solution without sacrificing capabilities.

  • oauth2-server:

    oauth2-server is more complex as it requires understanding of OAuth 2.0 specifications and server-side implementation details. It provides a comprehensive solution that can be tailored to specific needs, but this also means a steeper learning curve for developers.

  • client-oauth2:

    client-oauth2 is relatively simple and easy to use, focusing on the client-side flow of OAuth 2.0. It abstracts away much of the complexity involved in token management, making it accessible for developers who may not be familiar with OAuth 2.0 intricacies.

Token Management

  • simple-oauth2:

    simple-oauth2 simplifies token management by providing a clear API for obtaining and refreshing tokens. It abstracts the complexity of token handling while allowing developers to implement custom logic if needed, making it versatile for various use cases.

  • oauth2-server:

    oauth2-server provides extensive capabilities for managing access tokens, including issuing, revoking, and validating tokens. It allows for custom implementations of token storage and management, giving developers full control over how tokens are handled in their applications.

  • client-oauth2:

    client-oauth2 handles token management effectively on the client side, allowing developers to easily store, refresh, and manage access tokens. It provides built-in methods for token handling, reducing the need for manual implementation.

Extensibility

  • simple-oauth2:

    simple-oauth2 offers a moderate level of extensibility. While it provides a straightforward API, developers can still extend its functionality by implementing custom token handling and integrating it with other libraries, making it adaptable for different scenarios.

  • oauth2-server:

    oauth2-server is highly extensible, allowing developers to customize the implementation to fit specific needs. It supports various grant types and can be extended with custom logic for token storage, validation, and user authentication, making it ideal for complex applications.

  • client-oauth2:

    client-oauth2 is not highly extensible as it is focused on client-side flows. However, it can be integrated with other libraries and frameworks to enhance functionality, making it suitable for lightweight applications.

Community Support

  • simple-oauth2:

    simple-oauth2 benefits from a growing community and good documentation, providing developers with the necessary resources to implement OAuth 2.0 effectively. Its simplicity contributes to a supportive environment for new users.

  • oauth2-server:

    oauth2-server has a robust community and extensive documentation, making it easier for developers to find resources, examples, and support. Its popularity ensures that common issues are well-documented and addressed.

  • client-oauth2:

    client-oauth2 has a smaller community compared to the other two libraries, but it is still maintained and has sufficient documentation to assist developers in implementation.

How to Choose: simple-oauth2 vs oauth2-server vs client-oauth2
  • simple-oauth2:

    Opt for simple-oauth2 if you want a simple and flexible library for both client and server-side OAuth 2.0 implementations. It provides a straightforward API for managing tokens and is designed to be easy to integrate into existing applications, making it a good choice for developers looking for simplicity and ease of use.

  • oauth2-server:

    Select oauth2-server if you are building a complete OAuth 2.0 server implementation. This library is suitable for creating your own authorization server, managing access tokens, and supporting various grant types, making it ideal for backend applications that require full control over the OAuth process.

  • client-oauth2:

    Choose client-oauth2 if you need a lightweight and straightforward client-side library for handling OAuth 2.0 authorization flows. It is particularly useful for single-page applications (SPAs) where you want to manage tokens and make authenticated requests to APIs easily.

README for simple-oauth2

Simple OAuth2

NPM Package Version Build Status

Simple OAuth2 is a Node.js client library for the OAuth 2.0 authorization framework. OAuth 2.0 is the industry-standard protocol for authorization, enabling third-party applications to obtain limited access to an HTTP service, either on behalf of a resource owner or by allowing the third-party application to obtain access on its own behalf.

Table of Contents

Requirements

| Version | Node support | |----------------------------------------------------------------------------------|---------------------| | 5.x | Node 14.x or higher | | 6.x (Development) | Node 16.x or higher |

Older node versions are unsupported.

Usage

Install the client library using npm:

npm install --save simple-oauth2

With a minimal configuration, create a client instance of any supported grant type.

const config = {
  client: {
    id: '<client-id>',
    secret: '<client-secret>'
  },
  auth: {
    tokenHost: 'https://api.oauth.com'
  }
};

const { ClientCredentials, ResourceOwnerPassword, AuthorizationCode } = require('simple-oauth2');

For a complete reference of configuration options, see the API Options

Supported Grant Types

Depending on your use-case, any of the following supported grant types may be useful:

Authorization Code Grant

The Authorization Code grant type is used by confidential and public clients to exchange an authorization code for an access token. After the user returns to the client via the redirect URL, the application will get the authorization code from the URL and use it to request 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();

See the API reference for a complete reference of available options or any of our available examples at the example folder.

Resource Owner Password Credentials Grant

The Resource Owner Password Credentials grant type is a way to exchange a user's credentials for an access token. Because the client application has to collect the user's password and send it to the authorization server, it is not recommended that this grant be used at all anymore.

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();

See the API reference for a complete reference of available options.

Client Credentials Grant

The Client Credentials grant type is used by clients to obtain an access token outside of the context of a user. This is typically used by clients to access resources about themselves rather than to access a user's resources.

async function run() {
  const client = new ClientCredentials(config);

  const tokenParams = {
    scope: '<scope>',
  };

  try {
    const accessToken = await client.getToken(tokenParams);
  } catch (error) {
    console.log('Access Token error', error.message);
  }
}

run();

See the API reference for a complete reference of available options.

Access Token

On completion of any supported grant type an access token will be obtained. A list of supported operations can be found below.

Refresh an access token

On long lived applications, it is often necessary to refresh access tokens. In such scenarios the access token is usually persisted in an external database by first serializing it.

async function run() {
  const accessTokenJSONString = JSON.stringify(accessToken);

  await persistAccessTokenJSON(accessTokenJSONString);
}

run();

By the time we need to refresh the persistent access token, we can get back an AccessToken instance by using the client's .createToken method.

async function run() {
  const accessTokenJSONString = await getPersistedAccessTokenJSON();

  let accessToken = client.createToken(JSON.parse(accessTokenJSONString));
}

run();

Once we have determined the access token needs refreshing with the .expired() method, we can finally refresh it with a .refresh() method call.

async function run() {
  if (accessToken.expired()) {
    try {
      const refreshParams = {
        scope: '<scope>',
      };

      accessToken = await accessToken.refresh(refreshParams);
    } catch (error) {
      console.log('Error refreshing access token: ', error.message);
    }
  }
}

run();

The .expired() helper is useful for knowing when a token has definitively expired. However, there is a common race condition when tokens are near expiring. If an OAuth 2.0 token is issued with a expires_in property (as opposed to an expires_at property), there can be discrepancies between the time the OAuth 2.0 server issues the access token and when it is received.

These come down to factors such as network and processing latency and can be worked around by preemptively refreshing the access token:

async function run() {
  const EXPIRATION_WINDOW_IN_SECONDS = 300; // Window of time before the actual expiration to refresh the token

  if (accessToken.expired(EXPIRATION_WINDOW_IN_SECONDS)) {
    try {
      accessToken = await accessToken.refresh();
    } catch (error) {
      console.log('Error refreshing access token: ', error.message);
    }
  }
}

run();

Warning: Tokens obtained with the Client Credentials grant may not be refreshed. Fetch a new token when it's expired.

See the API reference for a complete reference of available options.

Revoke an access or refresh token

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

async function run() {
  try {
    await accessToken.revoke('access_token');
    await accessToken.revoke('refresh_token');
  } catch (error) {
    console.log('Error revoking token: ', error.message);
  }
}

run();

As a convenience method, you can also revoke both tokens in a single call:

async function run() {
  try {
    // Revokes both tokens, refresh token is only revoked if the access_token is properly revoked
    await accessToken.revokeAll();
  } catch (error) {
    console.log('Error revoking token: ', error.message);
  }
}

run();

See the API reference for a complete reference of available options.

Errors

Whenever a client or server error is produced, a boom error is thrown by the library. As such any boom error property is available, but the exact information may vary according to the type of error.

async function run() {
  const client = new ClientCredentials(config);

  try {
    await client.getToken();
  } catch(error) {
    console.log(error.output);
  }
}

run();

// { statusCode: 401,
//   payload:
//    { statusCode: 401,
//      error: 'Unauthorized',
//      message: 'Response Error: 401 Unauthorized' },
//   headers: {} }

Debugging the module

This module uses the debug module to help on error diagnosis. Use the following environment variable to help in your debug journey:

DEBUG=*simple-oauth2*

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

Thanks to Open Source

Simple OAuth 2.0 come to life thanks to the work I've made in Lelylan, an open source microservices architecture for the Internet of Things. If this project helped you in any way, think about giving us a star on Github.