1 |
|
2 |
|
3 |
|
4 | import { HttpHeaders } from "../httpHeaders";
|
5 | import * as base64 from "../util/base64";
|
6 | import { Constants } from "../util/constants";
|
7 | import { WebResourceLike } from "../webResource";
|
8 | import { ServiceClientCredentials } from "./serviceClientCredentials";
|
9 | const HeaderConstants = Constants.HeaderConstants;
|
10 | const DEFAULT_AUTHORIZATION_SCHEME = "Basic";
|
11 |
|
12 | export class BasicAuthenticationCredentials implements ServiceClientCredentials {
|
13 | userName: string;
|
14 | password: string;
|
15 | authorizationScheme: string = DEFAULT_AUTHORIZATION_SCHEME;
|
16 |
|
17 | |
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
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 |
|
43 |
|
44 |
|
45 |
|
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 | }
|