import * as debug from "debug" ; import fetch from "cross-fetch" ; import { AuthBase } from "./auth-base" ; import { TokenRotation } from "./mindconnect-base" ; import { getPiamUrl } from "./utils" ; const log = debug ( "mindconnect-credentialauth" ) ; export class CredentialAuth extends AuthBase implements TokenRotation { protected async AcquireToken ( ) { const headers = { ... this . _urlEncodedHeaders , Authorization : this . _basicAuth , } ; const url = `${ getPiamUrl ( this . _gateway , this . _tenant ) }oauth/token` ; log ( `AcquireToken Headers: ${ JSON . stringify ( headers ) } Url: ${ url }` ) ; const body = "grant_type=client_credentials" ; try { const response = await fetch ( url , { method : "POST" , body : body , headers : headers , agent : this . _proxyHttpAgent , } as RequestInit ) ; if ( ! response . ok ) { throw new Error ( `${ response . statusText } ${ await response . text ( ) }` ) ; } if ( response . status >= 200 && response . status <= 299 ) { const json = await response . json ( ) ; log ( `AcquireToken Response ${ JSON . stringify ( json ) }` ) ; this . _accessToken = json ; } else { throw new Error ( `invalid response ${ JSON . stringify ( response ) }` ) ; } } catch ( err ) { log ( err ) ; throw new Error ( `Network error occured ${ err . message }` ) ; } return true ; } returns { ( Promise < string > ) } memberOf public async GetToken ( ) { await this . RenewToken ( ) ; if ( ! this . _accessToken || ! this . _accessToken . access_token ) throw new Error ( "Error getting the new token!" ) ; return this . _accessToken . access_token ; } param { string } _gateway param { string } _basicAuth param { string } _tenant memberOf constructor ( protected _gateway , protected _basicAuth , protected _tenant ) { super ( _gateway , _basicAuth , _tenant ) ; } }