diff --git a/auth/authenticators/iam-authenticator.ts b/auth/authenticators/iam-authenticator.ts index 656c23c70..742435d8b 100644 --- a/auth/authenticators/iam-authenticator.ts +++ b/auth/authenticators/iam-authenticator.ts @@ -118,4 +118,14 @@ export class IamAuthenticator extends TokenRequestBasedAuthenticator { // update properties in token manager this.tokenManager.setScope(scope); } + + /** + * Return the most recently stored refresh token. + * + * @public + * @returns {string} + */ + public getRefreshToken(): string { + return this.tokenManager.getRefreshToken(); + } } diff --git a/auth/token-managers/iam-token-manager.ts b/auth/token-managers/iam-token-manager.ts index 9b1919fcf..be9cd4c57 100644 --- a/auth/token-managers/iam-token-manager.ts +++ b/auth/token-managers/iam-token-manager.ts @@ -52,6 +52,7 @@ interface Options extends JwtTokenManagerOptions { */ export class IamTokenManager extends JwtTokenManager { protected requiredOptions = ['apikey']; + protected refreshToken: string; private apikey: string; private clientId: string; private clientSecret: string; @@ -131,6 +132,33 @@ export class IamTokenManager extends JwtTokenManager { } } + /** + * Return the most recently stored refresh token. + * + * @public + * @returns {string} + */ + public getRefreshToken(): string { + return this.refreshToken; + } + + /** + * Extend this method from the parent class to extract the refresh token from + * the request and save it. + * + * @param tokenResponse - Response object from JWT service request + * @protected + * @returns {void} + */ + protected saveTokenInfo(tokenResponse): void { + super.saveTokenInfo(tokenResponse); + + const responseBody = tokenResponse.result || {}; + if (responseBody.refresh_token) { + this.refreshToken = responseBody.refresh_token; + } + } + /** * Request an IAM token using an API key. * diff --git a/test/unit/iam-token-manager.test.js b/test/unit/iam-token-manager.test.js index 7e6151758..1a7b1099d 100644 --- a/test/unit/iam-token-manager.test.js +++ b/test/unit/iam-token-manager.test.js @@ -21,10 +21,11 @@ RequestWrapper.mockImplementation(() => { const ACCESS_TOKEN = '9012'; const CURRENT_ACCESS_TOKEN = '1234'; +const REFRESH_TOKEN = '3456'; const IAM_RESPONSE = { result: { access_token: ACCESS_TOKEN, - refresh_token: '3456', + refresh_token: REFRESH_TOKEN, token_type: 'Bearer', expires_in: 3600, expiration: Math.floor(Date.now() / 1000) + 3600, @@ -354,4 +355,17 @@ describe('iam_token_manager_v1', function() { expect(scope).toBeUndefined(); done(); }); + + it('should save and expose the refresh token', async () => { + const instance = new IamTokenManager({ + apikey: 'abcd-1234', + }); + + mockSendRequest.mockImplementation(parameters => Promise.resolve(IAM_RESPONSE)); + + await instance.getToken(); + + expect(instance.refreshToken).toBe(REFRESH_TOKEN); + expect(instance.getRefreshToken()).toBe(REFRESH_TOKEN); + }); });