Obtain Access Token in NodeJS

This section describes the way of using OAuth 2.0 Client Credentials grant flow to obtain the service user's access token in your NodeJS application with blockapps-rest and token caching implemented.

config.yaml may have the separate "service" credentials of the OAuth 2.0 Client ("app client") under nodes -> 0 -> oauth section:

oauth:
  <...>
  serviceFlow: client-credential
  serviceFlowClientId: my-client-name
  serviceFlowClientSecret: abcd-1234-5ab6-wxyz-09876c654321
  <...>

Once the proper oauth credentials are entered into the config file, tokens may be fetched programmatically using blockapps-rest:

import { oauthUtil, rest } from 'blockapps-rest';
import config from '../load.config'; 
const oauth = oauthUtil.init(config.nodes[0].oauth);

const CACHED_DATA = {
  serviceToken: null,
  serviceTokenExpiresAt: null,
}
const SERVICE_TOKEN_LIFETIME_RESERVE_SECONDS = 5

const getServiceToken = async () => {
  const { serviceFlow, serviceFlowClientId, serviceFlowClientSecret } = config.nodes[0].oauth;
  switch (serviceFlow) {
    case 'client-credential': {
      let token = CACHED_DATA.serviceToken
      const expiresAt = CACHED_DATA.serviceTokenExpiresAt
      if (!token || !expiresAt || expiresAt <= (Math.floor(Date.now() / 1000) + SERVICE_TOKEN_LIFETIME_RESERVE_SECONDS)) {
        const tokenObj = await oauth.getAccessTokenByClientSecret(
          serviceFlowClientId,
          serviceFlowClientSecret,
        );
        token = tokenObj.token[config.nodes[0].oauth.tokenField ? config.nodes[0].oauth.tokenField : 'access_token']
        CACHED_DATA.serviceToken = token
        CACHED_DATA.serviceTokenExpiresAt = Math.floor(tokenObj.token.expires_at / 1000)
      }
      return token
    }
    default:
      throw Error(`Unsupported service oauth flow: ${serviceFlow}`);
  }
};

export {
  getApplicationUserToken
};

Note

The Resource Owner Password grant flow can be similarly implemented in your application in order to obtain the user-specific tokens (as opposed to the service user's tokens obtained with Client Credentials grant flow.)