simple-oauth2

repository·master·Indexed 23 days ago

https://github.com/lelylan/simple-oauth2

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

Tokens
6.8K
Snippets
16
Records
44
Agent score
81%

What's inside simple-oauth2

  1. Configure the simple-oauth2 client

    master

    To 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');
  2. Set up environment variables for examples

    master

    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"
  3. Refresh an access token

    master

    To handle long-lived applications, you can refresh expired access tokens.

    1. Persistence: You can serialize an AccessToken to JSON to store it in a database.
    2. Rehydration: Use client.createToken(parsedJson) to recreate the AccessToken instance from stored data.
    3. Expiration Check: Use 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.
    4. Refresh: Call 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);
        }
      }
    }
  4. Configure Simple OAuth2 grant options

    master

    All grant classes (AuthorizationCode, ResourceOwnerPassword, ClientCredentials) accept a configuration object containing client, auth, http, and options properties.

    client (Required)

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

    auth (Required)

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

    http (Optional)

    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.

    options (Optional)

    • 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.
  5. Configuration schemas for different Grant Types

    master

    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.

    Authorization Code Grant

    Requires client, auth (including authorization endpoints), http, and options.

    Client Credentials Grant

    Requires client, auth (token endpoints only), http, and options.

    Resource Owner Password Grant

    Requires client, auth (token endpoints only), http, and options.

  6. Configure Authorization Method and Body Format

    master

    When configuring the simple-oauth2 client, you can control how credentials are sent and how the request body is formatted using the following options:

    Authorization Method

    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.

    Body Format

    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.

  7. Use the Authorization Code Grant

    master

    The Authorization Code grant is used by confidential and public clients to exchange an authorization code for an access token.

    1. Use client.authorizeURL() to generate the URL for redirecting the user to the authorization server.
    2. After the user redirects back with a 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();
  8. Use the Resource Owner Password Credentials Grant

    master

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