Skip to content
This repository has been archived by the owner on Oct 21, 2021. It is now read-only.

Typescript Sample

Josh Horton edited this page Mar 17, 2021 · 7 revisions

TypeScript Sample

The following TypeScript code sample programmatically manages the System User authentication process of obtaining an IBM Cloud IAM token and exchanging it for a Service ID token. You can utilize this code to start automating your data uploads to IBM Food Trust™.

TypeScript Code

const request = require('request-promise');
const errors  = require('request-promise/errors');

export async function getToken(base_url: string,
                               organization_id: string,
                               apikey: string): Promise<string> {
  const iamTokenData = await getCloudIamToken(apikey);
  return await exchangeToken(base_url, organization_id , iamTokenData);
}

function getCloudIamToken(apikey: string): Promise<CloudIamToken> {
  const parameters = {
    grant_type : 'urn:ibm:params:oauth:grant-type:apikey',
    apikey     : apikey
  };
  const requestOptions = {
    uri: 'https://iam.cloud.ibm.com/identity/token',
    method: 'POST',
    headers: {
      'Accept': 'application/json'
    },
    form: parameters, // adds header 'Content-Type' = 'application/x-www-form-urlencoded'
    json: true
  };
  return request(requestOptions)
    .then((resp: CloudIamToken) => {
      return resp;
    })
    .catch(errors.StatusCodeError, (rpError: any) => {
      Promise.reject(rpError.message);
    })
    .catch(errors.RequestError, (rpError: any) => {
      Promise.reject(rpError.error);
    });
}

function exchangeToken(base_url: string,
                              organization_id: string,
                              iamTokenData: CloudIamToken): Promise<string> {
  const endpoint_url = base_url + '/ift/api/identity-proxy/exchange_token/v1/organization/' + organization_id;
  const requestOptions = {
    uri: endpoint_url,
    method: 'POST',
    headers: {
      'Accept': 'application/json'
    },
    body: iamTokenData,
    json: true
  };
  return request(requestOptions)
    .then((resp: ExchangeTokenResponse) => {
      return resp.onboarding_token;
    })
    .catch(errors.StatusCodeError, (rpError: any) => {
      Promise.reject(rpError.message);
    })
    .catch(errors.RequestError, (rpError: any) => {
      Promise.reject(rpError.error);
    });
}

interface CloudIamToken {
  access_token : string;
  token_type   : string;
  expires_in   : number;
  expiration   : number;
}

interface ExchangeTokenResponse {
  onboarding_token: string;
}
Clone this wiki locally