basicAuthenticationCredentials.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 * as base64 from "../util/base64";
  5. import { Constants } from "../util/constants";
  6. import { WebResource } from "../webResource";
  7. import { ServiceClientCredentials } from "./serviceClientCredentials";
  8. const HeaderConstants = Constants.HeaderConstants;
  9. const DEFAULT_AUTHORIZATION_SCHEME = "Basic";
  10. export class BasicAuthenticationCredentials implements ServiceClientCredentials {
  11. userName: string;
  12. password: string;
  13. authorizationScheme: string = DEFAULT_AUTHORIZATION_SCHEME;
  14. /**
  15. * Creates a new BasicAuthenticationCredentials object.
  16. *
  17. * @constructor
  18. * @param {string} userName User name.
  19. * @param {string} password Password.
  20. * @param {string} [authorizationScheme] The authorization scheme.
  21. */
  22. constructor(userName: string, password: string, authorizationScheme: string = DEFAULT_AUTHORIZATION_SCHEME) {
  23. if (userName === null || userName === undefined || typeof userName.valueOf() !== "string") {
  24. throw new Error("userName cannot be null or undefined and must be of type string.");
  25. }
  26. if (password === null || password === undefined || typeof password.valueOf() !== "string") {
  27. throw new Error("password cannot be null or undefined and must be of type string.");
  28. }
  29. this.userName = userName;
  30. this.password = password;
  31. this.authorizationScheme = authorizationScheme;
  32. }
  33. /**
  34. * Signs a request with the Authentication header.
  35. *
  36. * @param {WebResource} webResource The WebResource to be signed.
  37. * @returns {Promise<WebResource>} The signed request object.
  38. */
  39. signRequest(webResource: WebResource) {
  40. const credentials = `${this.userName}:${this.password}`;
  41. const encodedCredentials = `${this.authorizationScheme} ${base64.encodeString(credentials)}`;
  42. if (!webResource.headers) webResource.headers = new HttpHeaders();
  43. webResource.headers.set(HeaderConstants.AUTHORIZATION, encodedCredentials);
  44. return Promise.resolve(webResource);
  45. }
  46. }