oauth2-server

repository·master·Indexed 26 days ago

https://github.com/oauthjs/node-oauth2-server

A complete, framework-agnostic, and RFC 6749 and RFC 6750 compliant module for implementing an OAuth2 server in Node.js. It supports multiple grant types including authorization_code, client_credentials, refresh_token, password, and extension grants with scopes. The library is storage-agnostic, allowing use with backends such as PostgreSQL, MySQL, MongoDB, or Redis, and provides official wrappers for Express and Koa.

Tokens
18.4K
Snippets
39
Records
102
Agent score
87%

What's inside oauth2-server

  1. Overview of oauth2-server features

    master

    The oauth2-server module provides a complete, RFC 6749 and RFC 6750 compliant implementation for Node.js.

    Key features include:

    • Supported Grant Types: authorization_code, client_credentials, refresh_token, password, and extension grants with scopes.
    • Asynchronous Support: Compatible with Promises, Node-style callbacks, ES6 generators, and async/await (via Babel).
    • Storage Agnostic: Can be used with any storage backend such as PostgreSQL, MySQL, MongoDB, or Redis.
    • Framework Agnostic: While it can be used directly, official wrappers exist for Express and Koa.
  2. Use official adapters for Express and Koa

    master

    The oauth2-server module is framework-agnostic and is typically used through an adapter that converts its interface to work with specific HTTP server frameworks. For popular frameworks, use the following officially supported adapters:

    • Express: Use express-oauth-server.
    • Koa: Use koa-oauth-server.
  3. Implement model functions with various asynchronous patterns

    master

    When defining your model object for OAuth2Server, each function can support several asynchronous patterns. The library handles Promises, Node-style callbacks, ES6 generators, and async/await (via Babel). Note that returning a plain value is also supported if asynchronism is not required.

    const model = {
      // Support returning promises
      getAccessToken: function() {
        return new Promise((resolve, reject) => resolve('works!'));
      },
    
      // Or, calling a Node-style callback
      getAuthorizationCode: function(done) {
        done(null, 'works!');
      },
    
      // Or, using generators
      getClient: function*() {
        yield somethingAsync();
        return 'works!';
      },
    
      // Or, async/await (using Babel)
      getUser: async function() {
        await somethingAsync();
        return 'works!';
      }
    };
    
    const OAuth2Server = require('oauth2-server');
    let oauth = new OAuth2Server({model: model});
  4. Install oauth2-server via npm

    master

    Install the oauth2-server module using npm to implement an OAuth2 server in Node.js. The module is framework-agnostic, but if you are using Express or Koa, it is recommended to use their respective official wrappers (express-oauth-server or koa-oauth-server) instead of using this module directly.

    npm install oauth2-server
  5. Migrate middleware names from 2.x to 3.x

    master

    When upgrading to oauth2-server v3.x, the middleware names have been updated to align more closely with the OAuth2 RFC. Update your middleware references as follows:

    Old Name (2.x)New Name (3.x)
    authoriseauthenticate
    authCodeGrantauthorize
    granttoken

    Note that errorHandler and lockdown have been removed in v3.x. Errors are now handled by external wrappers, and lockdown (which was specific to Express) is no longer provided.

  6. Write a custom adapter for oauth2-server

    master

    To create a custom adapter, you must bridge the gap between the oauth2-server core and your specific HTTP framework.

    An adapter should:

    1. Inherit from OAuth2Server.
    2. Override the following methods:
      • authenticate()
      • authorize()
      • token()

    For each overridden method, you must:

    • Create Request and Response objects from your framework's specific request/response objects.
    • Call the original OAuth2Server function.
    • Copy all fields from the oauth2-server Response object back to your framework-specific response object and send it.
  7. Configure OAuth2 server options

    master

    You can set several options when instantiating the OAuth service.

    Available Options

    • addAcceptedScopesHeader (default: true): Adds the X-Accepted-OAuth-Scopes header.
    • addAuthorizedScopesHeader (default: true): Adds the X-OAuth-Scopes header.
    • allowBearerTokensInQueryString (default: false): Allows bearer tokens in the query string (e.g., ?access_token=).
    • allowEmptyState (default: false): If true, state can be empty or omitted.
    • authorizationCodeLifetime (default: 300): Lifetime in seconds for authorization codes.
    • accessTokenLifetime (default: 3600): Lifetime in seconds for access tokens.
    • refreshTokenLifetime (default: 1209600): Lifetime in seconds for refresh tokens.
    • allowExtendedTokenAttributes (default: false): Allows extra attributes (like id_token) in token responses.
    • requireClientAuthentication (default: true for all grant types): Allows setting client/secret authentication to false for specific grant types.

    Important v3.x Changes

    • Non-expiring tokens: In v3.x, accessTokenLifetime can no longer be set to null. To create a non-expiring token, set it to a very high value.
    • Removed options: grants, debug, clientIdRegex, passthroughErrors, and continueAfterResponse are no longer supported. Use the getClient method to manage grants.
  8. Upgrade from v2.x to v3.x

    master
    Version 3.x is a rewrite of the module using a promise-based approach, which introduces changes to the API and the model specification. Version 2.x is no longer supported. For detailed instructions on migrating your implementation, refer to the official 3.0 migration guide.