1- import Request from 'request' ;
2-
3- import { Configuration } from './Configuration' ;
4- import { Authentication } from './Authentication' ;
1+ import { Configuration } from 'Configuration' ;
2+ import { Authentication } from 'Authentication' ;
3+ import { HttpClient , HttpOptions } from './httpClient' ;
54
65export class JWTAuth implements Authentication {
76 private _accessToken ?: string ;
87 private readonly _configuration : Configuration ;
8+ private _client : HttpClient ;
99
1010 constructor ( configuration : Configuration ) {
1111 this . _configuration = configuration ;
@@ -14,14 +14,15 @@ export class JWTAuth implements Authentication {
1414 // Use saved token
1515 this . _accessToken = configuration . accessToken ;
1616 }
17+ this . _client = new HttpClient ( ) ;
1718 }
1819
1920 /**
2021 * Apply authentication settings to header and query params.
2122 */
22- public async applyToRequest ( requestOptions : Request . Options ) : Promise < void > {
23+ public async applyToRequest ( requestOptions : HttpOptions ) : Promise < void > {
2324 if ( this . _accessToken == null ) {
24- await this . requestToken ( ) ;
25+ this . _accessToken = await this . requestToken ( ) ;
2526 }
2627
2728 if ( requestOptions && requestOptions . headers ) {
@@ -31,18 +32,12 @@ export class JWTAuth implements Authentication {
3132 return Promise . resolve ( ) ;
3233 }
3334
34- public async applyUnauthorized ( ) : Promise < void > {
35- if ( this . _configuration . clientId && this . _configuration . clientSecret ) {
36- await this . requestToken ( ) ;
37- } else {
35+ private async requestToken ( ) : Promise < string > {
36+ if ( ! this . _configuration . clientId || ! this . _configuration . clientSecret ) {
3837 throw new Error ( "Required 'clientId' or 'clientSecret' not specified in configuration." ) ;
3938 }
40- }
41-
42- private requestToken ( ) : Promise < void > {
43- const requestOptions : Request . Options = {
39+ const requestOptions : HttpOptions = {
4440 method : 'POST' ,
45- json : true ,
4641 uri : this . _configuration . tokenUrl ,
4742 form : {
4843 grant_type : 'client_credentials' ,
@@ -51,23 +46,8 @@ export class JWTAuth implements Authentication {
5146 } ,
5247 } ;
5348
54- return new Promise < void > ( ( resolve , reject ) => {
55- const self = this ;
56- Request ( requestOptions , ( error , response ) => {
57- if ( error ) {
58- reject ( error ) ;
59- } else {
60- if ( response . statusCode && response . statusCode >= 200 && response . statusCode <= 299 ) {
61- self . _accessToken = response . body . access_token ;
62- resolve ( ) ;
63- } else {
64- reject (
65- response . body ??
66- `Error fetching token from '${ requestOptions . uri } ': ${ response . statusCode } ${ response . statusMessage } `
67- ) ;
68- }
69- }
70- } ) ;
71- } ) ;
49+ const result = await this . _client . requestAsync ( requestOptions ) ;
50+ const parsed = JSON . parse ( result . body ) ;
51+ return parsed . access_token ;
7252 }
7353}
0 commit comments