UNPKG

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