tokenCredentials.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Copyright (c) Microsoft Corporation. All rights reserved.
  2. // Licensed under the MIT License. See License.txt in the project root for license information.
  3. import { HttpHeaders } from "../httpHeaders";
  4. import { Constants } from "../util/constants";
  5. import { WebResource } from "../webResource";
  6. import { ServiceClientCredentials } from "./serviceClientCredentials";
  7. const HeaderConstants = Constants.HeaderConstants;
  8. const DEFAULT_AUTHORIZATION_SCHEME = "Bearer";
  9. /**
  10. * A credentials object that uses a token string and a authorzation scheme to authenticate.
  11. */
  12. export class TokenCredentials implements ServiceClientCredentials {
  13. token: string;
  14. authorizationScheme: string = DEFAULT_AUTHORIZATION_SCHEME;
  15. /**
  16. * Creates a new TokenCredentials object.
  17. *
  18. * @constructor
  19. * @param {string} token The token.
  20. * @param {string} [authorizationScheme] The authorization scheme.
  21. */
  22. constructor(token: string, authorizationScheme: string = DEFAULT_AUTHORIZATION_SCHEME) {
  23. if (!token) {
  24. throw new Error("token cannot be null or undefined.");
  25. }
  26. this.token = token;
  27. this.authorizationScheme = authorizationScheme;
  28. }
  29. /**
  30. * Signs a request with the Authentication header.
  31. *
  32. * @param {WebResource} webResource The WebResource to be signed.
  33. * @return {Promise<WebResource>} The signed request object.
  34. */
  35. signRequest(webResource: WebResource) {
  36. if (!webResource.headers) webResource.headers = new HttpHeaders();
  37. webResource.headers.set(HeaderConstants.AUTHORIZATION, `${this.authorizationScheme} ${this.token}`);
  38. return Promise.resolve(webResource);
  39. }
  40. }