AccessTokenHttpClient.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. "use strict";
  2. // Licensed to the .NET Foundation under one or more agreements.
  3. // The .NET Foundation licenses this file to you under the MIT license.
  4. Object.defineProperty(exports, "__esModule", { value: true });
  5. exports.AccessTokenHttpClient = void 0;
  6. const HeaderNames_1 = require("./HeaderNames");
  7. const HttpClient_1 = require("./HttpClient");
  8. /** @private */
  9. class AccessTokenHttpClient extends HttpClient_1.HttpClient {
  10. constructor(innerClient, accessTokenFactory) {
  11. super();
  12. this._innerClient = innerClient;
  13. this._accessTokenFactory = accessTokenFactory;
  14. }
  15. async send(request) {
  16. let allowRetry = true;
  17. if (this._accessTokenFactory && (!this._accessToken || (request.url && request.url.indexOf("/negotiate?") > 0))) {
  18. // don't retry if the request is a negotiate or if we just got a potentially new token from the access token factory
  19. allowRetry = false;
  20. this._accessToken = await this._accessTokenFactory();
  21. }
  22. this._setAuthorizationHeader(request);
  23. const response = await this._innerClient.send(request);
  24. if (allowRetry && response.statusCode === 401 && this._accessTokenFactory) {
  25. this._accessToken = await this._accessTokenFactory();
  26. this._setAuthorizationHeader(request);
  27. return await this._innerClient.send(request);
  28. }
  29. return response;
  30. }
  31. _setAuthorizationHeader(request) {
  32. if (!request.headers) {
  33. request.headers = {};
  34. }
  35. if (this._accessToken) {
  36. request.headers[HeaderNames_1.HeaderNames.Authorization] = `Bearer ${this._accessToken}`;
  37. }
  38. // don't remove the header if there isn't an access token factory, the user manually added the header in this case
  39. else if (this._accessTokenFactory) {
  40. if (request.headers[HeaderNames_1.HeaderNames.Authorization]) {
  41. delete request.headers[HeaderNames_1.HeaderNames.Authorization];
  42. }
  43. }
  44. }
  45. getCookieString(url) {
  46. return this._innerClient.getCookieString(url);
  47. }
  48. }
  49. exports.AccessTokenHttpClient = AccessTokenHttpClient;
  50. //# sourceMappingURL=AccessTokenHttpClient.js.map