1 |
|
2 |
|
3 |
|
4 | import { ServiceClientCredentials } from "./serviceClientCredentials";
|
5 | import { Constants as MSRestConstants } from "../util/constants";
|
6 | import { WebResource } from "../webResource";
|
7 |
|
8 | import { TokenCredential } from "@azure/core-auth";
|
9 | import { TokenResponse } from "./tokenResponse";
|
10 |
|
11 | const DEFAULT_AUTHORIZATION_SCHEME = "Bearer";
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | export const azureResourceManagerEndpoints = [
|
17 | "https://management.windows.net",
|
18 | "https://management.chinacloudapi.cn",
|
19 | "https://management.usgovcloudapi.net",
|
20 | "https://management.cloudapi.de",
|
21 | ];
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 | export class AzureIdentityCredentialAdapter implements ServiceClientCredentials {
|
28 | private azureTokenCredential: TokenCredential;
|
29 | private scopes: string | string[];
|
30 | constructor(
|
31 | azureTokenCredential: TokenCredential,
|
32 | scopes: string | string[] = "https:
|
33 | ) {
|
34 | this.azureTokenCredential = azureTokenCredential;
|
35 | this.scopes = scopes;
|
36 | }
|
37 |
|
38 | public async getToken(): Promise<TokenResponse> {
|
39 | const accessToken = await this.azureTokenCredential.getToken(this.scopes);
|
40 | if (accessToken !== null) {
|
41 | const result: TokenResponse = {
|
42 | accessToken: accessToken.token,
|
43 | tokenType: DEFAULT_AUTHORIZATION_SCHEME,
|
44 | expiresOn: accessToken.expiresOnTimestamp,
|
45 | };
|
46 | return result;
|
47 | } else {
|
48 | throw new Error("Could find token for scope");
|
49 | }
|
50 | }
|
51 |
|
52 | public async signRequest(webResource: WebResource) {
|
53 | const tokenResponse = await this.getToken();
|
54 | webResource.headers.set(
|
55 | MSRestConstants.HeaderConstants.AUTHORIZATION,
|
56 | `${tokenResponse.tokenType} ${tokenResponse.accessToken}`
|
57 | );
|
58 | return Promise.resolve(webResource);
|
59 | }
|
60 | }
|