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 { ServiceClientCredentials } from "./serviceClientCredentials";
5import { Constants as MSRestConstants } from "../util/constants";
6import { WebResource } from "../webResource";
7
8import { TokenCredential } from "@azure/core-auth";
9import { TokenResponse } from "./tokenResponse";
10
11const DEFAULT_AUTHORIZATION_SCHEME = "Bearer";
12
13/**
14 * Resource manager endpoints to match in order to specify a valid scope to the AzureIdentityCredentialAdapter.
15 */
16export 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 * This class provides a simple extension to use {@link TokenCredential} from `@azure/identity` library to
25 * use with legacy Azure SDKs that accept {@link ServiceClientCredentials} family of credentials for authentication.
26 */
27export class AzureIdentityCredentialAdapter implements ServiceClientCredentials {
28 private azureTokenCredential: TokenCredential;
29 private scopes: string | string[];
30 constructor(
31 azureTokenCredential: TokenCredential,
32 scopes: string | string[] = "https://management.azure.com/.default"
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}