AccessTokenHttpClient.js 2.0 KB

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