client-oauth2 vs oauth2-server vs simple-oauth2
OAuth 2.0 Libraries for Node.js
client-oauth2oauth2-serversimple-oauth2

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.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
client-oauth20539-846 years agoApache-2.0
oauth2-server04,076-1896 years agoMIT
simple-oauth201,64932.7 kB112 years agoApache-2.0

Feature Comparison: client-oauth2 vs oauth2-server vs simple-oauth2

Use Case

  • 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.

  • 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.

  • 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.

Complexity

  • 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.

  • 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.

  • 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.

Token Management

  • 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.

  • 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.

  • 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.

Extensibility

  • 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.

  • 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.

  • 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.

Community Support

  • 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.

  • 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.

  • 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.

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

  • 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.

  • 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.

  • 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.

README for client-oauth2

Client OAuth 2.0

NPM version NPM downloads Build status Greenkeeper badge

Straight-forward execution of OAuth 2.0 flows and authenticated API requests. 7.58 kB in browsers, after minification and gzipping, 75% from url and querystring dependencies.

Installation

npm install client-oauth2 --save

Usage

The module supports executing all the various OAuth 2.0 flows in any JavaScript environment. To authenticate you need to create an instance of the module for your API.

var ClientOAuth2 = require('client-oauth2')

var githubAuth = new ClientOAuth2({
  clientId: 'abc',
  clientSecret: '123',
  accessTokenUri: 'https://github.com/login/oauth/access_token',
  authorizationUri: 'https://github.com/login/oauth/authorize',
  redirectUri: 'http://example.com/auth/github/callback',
  scopes: ['notifications', 'gist']
})

P.S. The second argument to the constructor can inject a custom request function.

Options (global and method-based)

  • clientId The client id string assigned to you by the provider
  • clientSecret The client secret string assigned to you by the provider (not required for token)
  • accessTokenUri The url to request the access token (not required for token)
  • authorizationUri The url to redirect users to authenticate with the provider (only required for token and code)
  • redirectUri A custom url for the provider to redirect users back to your application (only required for token and code)
  • scopes An array of scopes to authenticate against
  • state Nonce sent back with the redirect when authorization is complete to verify authenticity (should be random for every request)

Request options

  • body An object to merge with the body of every request
  • query An object to merge with the query parameters of every request
  • headers An object to merge with the headers of every request

To re-create an access token instance and make requests on behalf on the user, you can create an access token instance by using the createToken method on a client instance.

// Can also just pass the raw `data` object in place of an argument.
var token = githubAuth.createToken('access token', 'optional refresh token', 'optional token type', { data: 'raw user data' })

// Set the token TTL.
token.expiresIn(1234) // Seconds.
token.expiresIn(new Date('2016-11-08')) // Date.

// Refresh the users credentials and save the new access token and info.
token.refresh().then(storeNewToken)

// Sign a standard HTTP request object, updating the URL with the access token
// or adding authorization headers, depending on token type.
token.sign({
  method: 'get',
  url: 'https://api.github.com/users'
}) //=> { method, url, headers, ... }

P.S. All authorization methods accept options as the last argument, useful for overriding the global configuration on a per-request basis.

Authorization Code Grant

The authorization code grant type is used to obtain both access tokens and refresh tokens and is optimized for confidential clients. Since this is a redirection-based flow, the client must be capable of interacting with the resource owner's user-agent (typically a web browser) and capable of receiving incoming requests (via redirection) from the authorization server.

  1. Redirect user to githubAuth.code.getUri([ options ]).
  2. Parse response uri and get token using githubAuth.code.getToken(uri [, options ]).
var express = require('express')
var app = express()

app.get('/auth/github', function (req, res) {
  var uri = githubAuth.code.getUri()

  res.redirect(uri)
})

app.get('/auth/github/callback', function (req, res) {
  githubAuth.code.getToken(req.originalUrl)
    .then(function (user) {
      console.log(user) //=> { accessToken: '...', tokenType: 'bearer', ... }

      // Refresh the current users access token.
      user.refresh().then(function (updatedUser) {
        console.log(updatedUser !== user) //=> true
        console.log(updatedUser.accessToken)
      })

      // Sign API requests on behalf of the current user.
      user.sign({
        method: 'get',
        url: 'http://example.com'
      })

      // We should store the token into a database.
      return res.send(user.accessToken)
    })
})

P.S. The getToken URI parameter can be an object containing pathname and query properties.

Implicit Grant

The implicit grant type is used to obtain access tokens (it does not support the issuance of refresh tokens) and is optimized for public clients known to operate a particular redirection URI. These clients are typically implemented in a browser using a scripting language such as JavaScript.

  1. Redirect user to githubAuth.token.getUri([ options ]).
  2. Parse response uri for the access token using githubAuth.token.getToken(uri [, options ]).
window.oauth2Callback = function (uri) {
  githubAuth.token.getToken(uri)
    .then(function (user) {
      console.log(user) //=> { accessToken: '...', tokenType: 'bearer', ... }

      // Make a request to the github API for the current user.
      return popsicle.request(user.sign({
        method: 'get',
        url: 'https://api.github.com/user'
      })).then(function (res) {
        console.log(res) //=> { body: { ... }, status: 200, headers: { ... } }
      })
    })
}

// Open the page in a new window, then redirect back to a page that calls our global `oauth2Callback` function.
window.open(githubAuth.token.getUri())

P.S. The getToken URI parameter can be an object containing pathname, query and hash properties.

Resource Owner Password Credentials Grant

The resource owner password credentials grant type is suitable in cases where the resource owner has a trust relationship with the client, such as the device operating system or a highly privileged application. The authorization server should take special care when enabling this grant type and only allow it when other flows are not viable.

  1. Make a direct request for the access token on behalf of the user using githubAuth.owner.getToken(username, password [, options ]).
githubAuth.owner.getToken('blakeembrey', 'hunter2')
  .then(function (user) {
    console.log(user) //=> { accessToken: '...', tokenType: 'bearer', ... }
  })

Client Credentials Grant

The client can request an access token using only its client credentials (or other supported means of authentication) when the client is requesting access to the protected resources under its control, or those of another resource owner that have been previously arranged with the authorization server (the method of which is beyond the scope of this specification).

  1. Get the access token for the application by using githubAuth.credentials.getToken([ options ]).
githubAuth.credentials.getToken()
  .then(function (user) {
    console.log(user) //=> { accessToken: '...', tokenType: 'bearer', ... }
  })

JWT as Authorization Grant

A JSON Web Token (JWT) Bearer Token can be used to request an access token when a client wishes to utilize an existing trust relationship, expressed through the semantics of (and digital signature or Message Authentication Code calculated over) the JWT, without a direct user approval step at the authorization server.

  1. Get the access token for the application by using githubAuth.jwt.getToken(jwt [, options ]).
githubAuth.jwt.getToken('eyJhbGciOiJFUzI1NiJ9.eyJpc3Mi[...omitted for brevity...].J9l-ZhwP[...omitted for brevity...]')
  .then(function (user) {
    console.log(user) //=> { accessToken: '...', tokenType: 'bearer', ... }
  })

Dependencies

Requires an ES5 environment with global Promise and Object.assign.

License

Apache 2.0