@azure/identity 4.3.0-beta.2 → 4.3.1-alpha.20240618.4
Sign up to get free protection for your applications and to get access to all the features.
- package/README.md +4 -8
- package/dist/index.js +61 -83
- package/dist/index.js.map +1 -1
- package/dist-esm/src/constants.js +1 -1
- package/dist-esm/src/constants.js.map +1 -1
- package/dist-esm/src/credentials/azurePipelinesCredential.js +35 -60
- package/dist-esm/src/credentials/azurePipelinesCredential.js.map +1 -1
- package/dist-esm/src/msal/nodeFlows/msalClient.js +27 -24
- package/dist-esm/src/msal/nodeFlows/msalClient.js.map +1 -1
- package/package.json +3 -3
- package/types/identity.d.ts +3 -8
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,
|
1
|
+
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,OAAO,CAAC;AAEnC;;;GAGG;AACH,2EAA2E;AAC3E,6CAA6C;AAC7C,uGAAuG;AACvG,MAAM,CAAC,MAAM,uBAAuB,GAAG,sCAAsC,CAAC;AAE9E;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,QAAQ,CAAC;AAExC;;GAEG;AACH,MAAM,CAAN,IAAY,mBAiBX;AAjBD,WAAY,mBAAmB;IAC7B;;OAEG;IACH,oEAA6C,CAAA;IAC7C;;OAEG;IACH,wEAAiD,CAAA;IACjD;;OAEG;IACH,2EAAoD,CAAA;IACpD;;OAEG;IACH,6EAAsD,CAAA;AACxD,CAAC,EAjBW,mBAAmB,KAAnB,mBAAmB,QAiB9B;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,mBAAmB,CAAC,gBAAgB,CAAC;AAEzE;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAa,CAAC,GAAG,CAAC,CAAC;AAE3C;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,CAAC;AAEtC;;GAEG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,OAAO,CAAC;AAE5C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,YAAY,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Current version of the `@azure/identity` package.\n */\nexport const SDK_VERSION = `4.3.1`;\n\n/**\n * The default client ID for authentication\n * @internal\n */\n// TODO: temporary - this is the Azure CLI clientID - we'll replace it when\n// Developer Sign On application is available\n// https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/Constants.cs#L9\nexport const DeveloperSignOnClientId = \"04b07795-8ddb-461a-bbee-02f9e1bf7b46\";\n\n/**\n * The default tenant for authentication\n * @internal\n */\nexport const DefaultTenantId = \"common\";\n\n/**\n * A list of known Azure authority hosts\n */\nexport enum AzureAuthorityHosts {\n /**\n * China-based Azure Authority Host\n */\n AzureChina = \"https://login.chinacloudapi.cn\",\n /**\n * Germany-based Azure Authority Host\n */\n AzureGermany = \"https://login.microsoftonline.de\",\n /**\n * US Government Azure Authority Host\n */\n AzureGovernment = \"https://login.microsoftonline.us\",\n /**\n * Public Cloud Azure Authority Host\n */\n AzurePublicCloud = \"https://login.microsoftonline.com\",\n}\n\n/**\n * @internal\n * The default authority host.\n */\nexport const DefaultAuthorityHost = AzureAuthorityHosts.AzurePublicCloud;\n\n/**\n * @internal\n * Allow acquiring tokens for any tenant for multi-tentant auth.\n */\nexport const ALL_TENANTS: string[] = [\"*\"];\n\n/**\n * @internal\n */\nexport const CACHE_CAE_SUFFIX = \"cae\";\n\n/**\n * @internal\n */\nexport const CACHE_NON_CAE_SUFFIX = \"nocae\";\n\n/**\n * @internal\n *\n * The default name for the cache persistence plugin.\n * Matches the constant defined in the cache persistence package.\n */\nexport const DEFAULT_TOKEN_CACHE_NAME = \"msal.cache\";\n"]}
|
@@ -1,14 +1,14 @@
|
|
1
1
|
// Copyright (c) Microsoft Corporation.
|
2
2
|
// Licensed under the MIT license.
|
3
3
|
import { ClientAssertionCredential } from "./clientAssertionCredential";
|
4
|
-
import { CredentialUnavailableError } from "../errors";
|
4
|
+
import { AuthenticationError, CredentialUnavailableError } from "../errors";
|
5
5
|
import { credentialLogger } from "../util/logging";
|
6
6
|
import { checkTenantId } from "../util/tenantIdUtils";
|
7
7
|
import { createHttpHeaders, createPipelineRequest } from "@azure/core-rest-pipeline";
|
8
8
|
import { IdentityClient } from "../client/identityClient";
|
9
9
|
const credentialName = "AzurePipelinesCredential";
|
10
10
|
const logger = credentialLogger(credentialName);
|
11
|
-
const OIDC_API_VERSION = "7.1
|
11
|
+
const OIDC_API_VERSION = "7.1";
|
12
12
|
/**
|
13
13
|
* This credential is designed to be used in Azure Pipelines with service connections
|
14
14
|
* as a setup for workload identity federation.
|
@@ -18,23 +18,23 @@ export class AzurePipelinesCredential {
|
|
18
18
|
* AzurePipelinesCredential supports Federated Identity on Azure Pipelines through Service Connections.
|
19
19
|
* @param tenantId - tenantId associated with the service connection
|
20
20
|
* @param clientId - clientId associated with the service connection
|
21
|
-
* @param serviceConnectionId -
|
21
|
+
* @param serviceConnectionId - Unique ID for the service connection, as found in the querystring's resourceId key
|
22
|
+
* @param systemAccessToken - The pipeline's <see href="https://learn.microsoft.com/azure/devops/pipelines/build/variables?view=azure-devops%26tabs=yaml#systemaccesstoken">System.AccessToken</see> value.
|
22
23
|
* @param options - The identity client options to use for authentication.
|
23
24
|
*/
|
24
|
-
constructor(tenantId, clientId, serviceConnectionId, options) {
|
25
|
-
if (!clientId || !tenantId || !serviceConnectionId) {
|
26
|
-
throw new CredentialUnavailableError(`${credentialName}: is unavailable. tenantId, clientId, and
|
25
|
+
constructor(tenantId, clientId, serviceConnectionId, systemAccessToken, options) {
|
26
|
+
if (!clientId || !tenantId || !serviceConnectionId || !systemAccessToken) {
|
27
|
+
throw new CredentialUnavailableError(`${credentialName}: is unavailable. tenantId, clientId, serviceConnectionId, and systemAccessToken are required parameters.`);
|
27
28
|
}
|
28
29
|
this.identityClient = new IdentityClient(options);
|
29
30
|
checkTenantId(logger, tenantId);
|
30
|
-
logger.info(`Invoking AzurePipelinesCredential with tenant ID: ${tenantId},
|
31
|
-
if (
|
32
|
-
this
|
33
|
-
const oidcRequestUrl = `${process.env.SYSTEM_TEAMFOUNDATIONCOLLECTIONURI}${process.env.SYSTEM_TEAMPROJECTID}/_apis/distributedtask/hubs/build/plans/${process.env.SYSTEM_PLANID}/jobs/${process.env.SYSTEM_JOBID}/oidctoken?api-version=${OIDC_API_VERSION}&serviceConnectionId=${serviceConnectionId}`;
|
34
|
-
const systemAccessToken = `${process.env.SYSTEM_ACCESSTOKEN}`;
|
35
|
-
logger.info(`Invoking ClientAssertionCredential with tenant ID: ${tenantId}, clientId: ${clientId} and service connection id: ${serviceConnectionId}`);
|
36
|
-
this.clientAssertionCredential = new ClientAssertionCredential(tenantId, clientId, this.requestOidcToken.bind(this, oidcRequestUrl, systemAccessToken), options);
|
31
|
+
logger.info(`Invoking AzurePipelinesCredential with tenant ID: ${tenantId}, client ID: ${clientId}, and service connection ID: ${serviceConnectionId}`);
|
32
|
+
if (!process.env.SYSTEM_OIDCREQUESTURI) {
|
33
|
+
throw new CredentialUnavailableError(`${credentialName}: is unavailable. Ensure that you're running this task in an Azure Pipeline, so that following missing system variable(s) can be defined- "SYSTEM_OIDCREQUESTURI"`);
|
37
34
|
}
|
35
|
+
const oidcRequestUrl = `${process.env.SYSTEM_OIDCREQUESTURI}?api-version=${OIDC_API_VERSION}&serviceConnectionId=${serviceConnectionId}`;
|
36
|
+
logger.info(`Invoking ClientAssertionCredential with tenant ID: ${tenantId}, client ID: ${clientId} and service connection ID: ${serviceConnectionId}`);
|
37
|
+
this.clientAssertionCredential = new ClientAssertionCredential(tenantId, clientId, this.requestOidcToken.bind(this, oidcRequestUrl, systemAccessToken), options);
|
38
38
|
}
|
39
39
|
/**
|
40
40
|
* Authenticates with Microsoft Entra ID and returns an access token if successful.
|
@@ -46,16 +46,13 @@ export class AzurePipelinesCredential {
|
|
46
46
|
*/
|
47
47
|
async getToken(scopes, options) {
|
48
48
|
if (!this.clientAssertionCredential) {
|
49
|
-
const errorMessage = `${credentialName}: is unavailable. To use Federation Identity in Azure Pipelines,
|
49
|
+
const errorMessage = `${credentialName}: is unavailable. To use Federation Identity in Azure Pipelines, the following parameters are required -
|
50
50
|
tenantId,
|
51
51
|
clientId,
|
52
52
|
serviceConnectionId,
|
53
|
-
|
54
|
-
"
|
55
|
-
|
56
|
-
"SYSTEM_JOBID" &&
|
57
|
-
"SYSTEM_ACCESSTOKEN"
|
58
|
-
See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/troubleshoot`;
|
53
|
+
systemAccessToken,
|
54
|
+
"SYSTEM_OIDCREQUESTURI".
|
55
|
+
See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`;
|
59
56
|
logger.error(errorMessage);
|
60
57
|
throw new CredentialUnavailableError(errorMessage);
|
61
58
|
}
|
@@ -83,48 +80,26 @@ export class AzurePipelinesCredential {
|
|
83
80
|
const text = response.bodyAsText;
|
84
81
|
if (!text) {
|
85
82
|
logger.error(`${credentialName}: Authenticated Failed. Received null token from OIDC request. Response status- ${response.status}. Complete response - ${JSON.stringify(response)}`);
|
86
|
-
throw new
|
83
|
+
throw new AuthenticationError(response.status, `${credentialName}: Authenticated Failed. Received null token from OIDC request. Response status- ${response.status}. Complete response - ${JSON.stringify(response)}`);
|
87
84
|
}
|
88
|
-
|
89
|
-
|
90
|
-
|
85
|
+
try {
|
86
|
+
const result = JSON.parse(text);
|
87
|
+
if (result === null || result === void 0 ? void 0 : result.oidcToken) {
|
88
|
+
return result.oidcToken;
|
89
|
+
}
|
90
|
+
else {
|
91
|
+
let errorMessage = `${credentialName}: Authentication Failed. oidcToken field not detected in the response.`;
|
92
|
+
if (response.status !== 200) {
|
93
|
+
errorMessage += `Response = ${JSON.stringify(result)}`;
|
94
|
+
}
|
95
|
+
logger.error(errorMessage);
|
96
|
+
throw new AuthenticationError(response.status, errorMessage);
|
97
|
+
}
|
91
98
|
}
|
92
|
-
|
93
|
-
logger.error(
|
94
|
-
|
95
|
-
|
96
|
-
}
|
97
|
-
/**
|
98
|
-
* Ensures all system env vars are there to form the request uri for OIDC token
|
99
|
-
* @returns void
|
100
|
-
* @throws CredentialUnavailableError
|
101
|
-
*/
|
102
|
-
ensurePipelinesSystemVars() {
|
103
|
-
if (process.env.SYSTEM_TEAMFOUNDATIONCOLLECTIONURI &&
|
104
|
-
process.env.SYSTEM_TEAMPROJECTID &&
|
105
|
-
process.env.SYSTEM_PLANID &&
|
106
|
-
process.env.SYSTEM_JOBID &&
|
107
|
-
process.env.SYSTEM_ACCESSTOKEN) {
|
108
|
-
return;
|
109
|
-
}
|
110
|
-
const missingEnvVars = [];
|
111
|
-
let errorMessage = "";
|
112
|
-
if (!process.env.SYSTEM_TEAMFOUNDATIONCOLLECTIONURI) {
|
113
|
-
missingEnvVars.push("SYSTEM_TEAMFOUNDATIONCOLLECTIONURI");
|
114
|
-
}
|
115
|
-
if (!process.env.SYSTEM_TEAMPROJECTID)
|
116
|
-
missingEnvVars.push("SYSTEM_TEAMPROJECTID");
|
117
|
-
if (!process.env.SYSTEM_PLANID)
|
118
|
-
missingEnvVars.push("SYSTEM_PLANID");
|
119
|
-
if (!process.env.SYSTEM_JOBID)
|
120
|
-
missingEnvVars.push("SYSTEM_JOBID");
|
121
|
-
if (!process.env.SYSTEM_ACCESSTOKEN) {
|
122
|
-
errorMessage +=
|
123
|
-
"\nPlease ensure that the system access token is available in the SYSTEM_ACCESSTOKEN value; this is often most easily achieved by adding a block to the end of your pipeline yaml for the task with:\n env: \n- SYSTEM_ACCESSTOKEN: $(System.AccessToken)";
|
124
|
-
missingEnvVars.push("SYSTEM_ACCESSTOKEN");
|
125
|
-
}
|
126
|
-
if (missingEnvVars.length > 0) {
|
127
|
-
throw new CredentialUnavailableError(`${credentialName}: is unavailable. Ensure that you're running this task in an Azure Pipeline, so that following missing system variable(s) can be defined- ${missingEnvVars.join(", ")}.${errorMessage}`);
|
99
|
+
catch (e) {
|
100
|
+
logger.error(e.message);
|
101
|
+
logger.error(`${credentialName}: Authentication Failed. oidcToken field not detected in the response. Response = ${text}`);
|
102
|
+
throw new AuthenticationError(response.status, `${credentialName}: Authentication Failed. oidcToken field not detected in the response. Response = ${text}`);
|
128
103
|
}
|
129
104
|
}
|
130
105
|
}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"azurePipelinesCredential.js","sourceRoot":"","sources":["../../../src/credentials/azurePipelinesCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,EAAuB,0BAA0B,EAAE,MAAM,WAAW,CAAC;AAC5E,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAErF,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAE1D,MAAM,cAAc,GAAG,0BAA0B,CAAC;AAClD,MAAM,MAAM,GAAG,gBAAgB,CAAC,cAAc,CAAC,CAAC;AAChD,MAAM,gBAAgB,GAAG,eAAe,CAAC;AAEzC;;;GAGG;AACH,MAAM,OAAO,wBAAwB;IAInC;;;;;;OAMG;IACH,YACE,QAAgB,EAChB,QAAgB,EAChB,mBAA2B,EAC3B,OAAyC;QAEzC,IAAI,CAAC,QAAQ,IAAI,CAAC,QAAQ,IAAI,CAAC,mBAAmB,EAAE,CAAC;YACnD,MAAM,IAAI,0BAA0B,CAClC,GAAG,cAAc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AC;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { ClientAssertionCredential } from \"./clientAssertionCredential\";\nimport { AuthenticationError, CredentialUnavailableError } from \"../errors\";\nimport { credentialLogger } from \"../util/logging\";\nimport { checkTenantId } from \"../util/tenantIdUtils\";\nimport { createHttpHeaders, createPipelineRequest } from \"@azure/core-rest-pipeline\";\nimport { AzurePipelinesCredentialOptions } from \"./azurePipelinesCredentialOptions\";\nimport { IdentityClient } from \"../client/identityClient\";\n\nconst credentialName = \"AzurePipelinesCredential\";\nconst logger = credentialLogger(credentialName);\nconst OIDC_API_VERSION = \"7.1-preview.1\";\n\n/**\n * This credential is designed to be used in Azure Pipelines with service connections\n * as a setup for workload identity federation.\n */\nexport class AzurePipelinesCredential implements TokenCredential {\n private clientAssertionCredential: ClientAssertionCredential | undefined;\n private identityClient: IdentityClient;\n\n /**\n * AzurePipelinesCredential supports Federated Identity on Azure Pipelines through Service Connections.\n * @param tenantId - tenantId associated with the service connection\n * @param clientId - clientId associated with the service connection\n * @param serviceConnectionId - id for the service connection, as found in the querystring's resourceId key\n * @param options - The identity client options to use for authentication.\n */\n constructor(\n tenantId: string,\n clientId: string,\n serviceConnectionId: string,\n options?: AzurePipelinesCredentialOptions,\n ) {\n if (!clientId || !tenantId || !serviceConnectionId) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. tenantId, clientId, and serviceConnectionId are required parameters.`,\n );\n }\n this.identityClient = new IdentityClient(options);\n checkTenantId(logger, tenantId);\n logger.info(\n `Invoking AzurePipelinesCredential with tenant ID: ${tenantId}, clientId: ${clientId} and service connection id: ${serviceConnectionId}`,\n );\n\n if (clientId && tenantId && serviceConnectionId) {\n this.ensurePipelinesSystemVars();\n const oidcRequestUrl = `${process.env.SYSTEM_TEAMFOUNDATIONCOLLECTIONURI}${process.env.SYSTEM_TEAMPROJECTID}/_apis/distributedtask/hubs/build/plans/${process.env.SYSTEM_PLANID}/jobs/${process.env.SYSTEM_JOBID}/oidctoken?api-version=${OIDC_API_VERSION}&serviceConnectionId=${serviceConnectionId}`;\n const systemAccessToken = `${process.env.SYSTEM_ACCESSTOKEN}`;\n logger.info(\n `Invoking ClientAssertionCredential with tenant ID: ${tenantId}, clientId: ${clientId} and service connection id: ${serviceConnectionId}`,\n );\n this.clientAssertionCredential = new ClientAssertionCredential(\n tenantId,\n clientId,\n this.requestOidcToken.bind(this, oidcRequestUrl, systemAccessToken),\n options,\n );\n }\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} or {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions,\n ): Promise<AccessToken> {\n if (!this.clientAssertionCredential) {\n const errorMessage = `${credentialName}: is unavailable. To use Federation Identity in Azure Pipelines, these are required as input parameters / env variables - \n tenantId,\n clientId,\n serviceConnectionId,\n \"SYSTEM_TEAMFOUNDATIONCOLLECTIONURI\" &&\n \"SYSTEM_TEAMPROJECTID\" &&\n \"SYSTEM_PLANID\" &&\n \"SYSTEM_JOBID\" &&\n \"SYSTEM_ACCESSTOKEN\"\n See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/troubleshoot`;\n logger.error(errorMessage);\n throw new CredentialUnavailableError(errorMessage);\n }\n logger.info(\"Invoking getToken() of Client Assertion Credential\");\n return this.clientAssertionCredential.getToken(scopes, options);\n }\n\n /**\n *\n * @param oidcRequestUrl - oidc request url\n * @param systemAccessToken - system access token\n * @returns OIDC token from Azure Pipelines\n */\n private async requestOidcToken(\n oidcRequestUrl: string,\n systemAccessToken: string,\n ): Promise<string> {\n logger.info(\"Requesting OIDC token from Azure Pipelines...\");\n logger.info(oidcRequestUrl);\n const request = createPipelineRequest({\n url: oidcRequestUrl,\n method: \"POST\",\n headers: createHttpHeaders({\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${systemAccessToken}`,\n }),\n });\n const response = await this.identityClient.sendRequest(request);\n const text = response.bodyAsText;\n if (!text) {\n logger.error(\n `${credentialName}: Authenticated Failed. Received null token from OIDC request. Response status- ${\n response.status\n }. Complete response - ${JSON.stringify(response)}`,\n );\n throw new CredentialUnavailableError(\n `${credentialName}: Authenticated Failed. Received null token from OIDC request. Response status- ${\n response.status\n }. Complete response - ${JSON.stringify(response)}`,\n );\n }\n const result = JSON.parse(text);\n if (result?.oidcToken) {\n return result.oidcToken;\n } else {\n logger.error(\n `${credentialName}: Authentication Failed. oidcToken field not detected in the response. Response = ${JSON.stringify(\n result,\n )}`,\n );\n throw new CredentialUnavailableError(\n `${credentialName}: Authentication Failed. oidcToken field not detected in the response. Response = ${JSON.stringify(\n result,\n )}`,\n );\n }\n }\n\n /**\n * Ensures all system env vars are there to form the request uri for OIDC token\n * @returns void\n * @throws CredentialUnavailableError\n */\n private ensurePipelinesSystemVars(): void {\n if (\n process.env.SYSTEM_TEAMFOUNDATIONCOLLECTIONURI &&\n process.env.SYSTEM_TEAMPROJECTID &&\n process.env.SYSTEM_PLANID &&\n process.env.SYSTEM_JOBID &&\n process.env.SYSTEM_ACCESSTOKEN\n ) {\n return;\n }\n const missingEnvVars = [];\n let errorMessage = \"\";\n if (!process.env.SYSTEM_TEAMFOUNDATIONCOLLECTIONURI) {\n missingEnvVars.push(\"SYSTEM_TEAMFOUNDATIONCOLLECTIONURI\");\n }\n if (!process.env.SYSTEM_TEAMPROJECTID) missingEnvVars.push(\"SYSTEM_TEAMPROJECTID\");\n if (!process.env.SYSTEM_PLANID) missingEnvVars.push(\"SYSTEM_PLANID\");\n if (!process.env.SYSTEM_JOBID) missingEnvVars.push(\"SYSTEM_JOBID\");\n if (!process.env.SYSTEM_ACCESSTOKEN) {\n errorMessage +=\n \"\\nPlease ensure that the system access token is available in the SYSTEM_ACCESSTOKEN value; this is often most easily achieved by adding a block to the end of your pipeline yaml for the task with:\\n env: \\n- SYSTEM_ACCESSTOKEN: $(System.AccessToken)\";\n missingEnvVars.push(\"SYSTEM_ACCESSTOKEN\");\n }\n if (missingEnvVars.length > 0) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. Ensure that you're running this task in an Azure Pipeline, so that following missing system variable(s) can be defined- ${missingEnvVars.join(\n \", \",\n )}.${errorMessage}`,\n );\n }\n }\n}\n"]}
|
1
|
+
{"version":3,"file":"azurePipelinesCredential.js","sourceRoot":"","sources":["../../../src/credentials/azurePipelinesCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,EAAE,mBAAmB,EAAE,0BAA0B,EAAE,MAAM,WAAW,CAAC;AAC5E,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAErF,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAE1D,MAAM,cAAc,GAAG,0BAA0B,CAAC;AAClD,MAAM,MAAM,GAAG,gBAAgB,CAAC,cAAc,CAAC,CAAC;AAChD,MAAM,gBAAgB,GAAG,KAAK,CAAC;AAE/B;;;GAGG;AACH,MAAM,OAAO,wBAAwB;IAInC;;;;;;;OAOG;IACH,YACE,QAAgB,EAChB,QAAgB,EAChB,mBAA2B,EAC3B,iBAAyB,EACzB,OAAyC;QAEzC,IAAI,CAAC,QAAQ,IAAI,CAAC,QAAQ,IAAI,CAAC,mBAAmB,IAAI,CAAC,iBAAiB,EAAE,CAAC;YACzE,MAAM,IAAI,0BAA0B,CAClC,GAAG,cAAc,2GAA2G,CAC7H,CAAC;QACJ,CAA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AAC,YAAY,CAAC,CAAC;gBAC3B,MAAM,IAAI,mBAAmB,CAAC,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;YAC/D,CAAC;QACH,CAAC;QAAC,OAAO,CAAM,EAAE,CAAC;YAChB,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;YACxB,MAAM,CAAC,KAAK,CACV,GAAG,cAAc,qFAAqF,IAAI,EAAE,CAC7G,CAAC;YACF,MAAM,IAAI,mBAAmB,CAC3B,QAAQ,CAAC,MAAM,EACf,GAAG,cAAc,qFAAqF,IAAI,EAAE,CAC7G,CAAC;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { ClientAssertionCredential } from \"./clientAssertionCredential\";\nimport { AuthenticationError, CredentialUnavailableError } from \"../errors\";\nimport { credentialLogger } from \"../util/logging\";\nimport { checkTenantId } from \"../util/tenantIdUtils\";\nimport { createHttpHeaders, createPipelineRequest } from \"@azure/core-rest-pipeline\";\nimport { AzurePipelinesCredentialOptions } from \"./azurePipelinesCredentialOptions\";\nimport { IdentityClient } from \"../client/identityClient\";\n\nconst credentialName = \"AzurePipelinesCredential\";\nconst logger = credentialLogger(credentialName);\nconst OIDC_API_VERSION = \"7.1\";\n\n/**\n * This credential is designed to be used in Azure Pipelines with service connections\n * as a setup for workload identity federation.\n */\nexport class AzurePipelinesCredential implements TokenCredential {\n private clientAssertionCredential: ClientAssertionCredential | undefined;\n private identityClient: IdentityClient;\n\n /**\n * AzurePipelinesCredential supports Federated Identity on Azure Pipelines through Service Connections.\n * @param tenantId - tenantId associated with the service connection\n * @param clientId - clientId associated with the service connection\n * @param serviceConnectionId - Unique ID for the service connection, as found in the querystring's resourceId key\n * @param systemAccessToken - The pipeline's <see href=\"https://learn.microsoft.com/azure/devops/pipelines/build/variables?view=azure-devops%26tabs=yaml#systemaccesstoken\">System.AccessToken</see> value.\n * @param options - The identity client options to use for authentication.\n */\n constructor(\n tenantId: string,\n clientId: string,\n serviceConnectionId: string,\n systemAccessToken: string,\n options?: AzurePipelinesCredentialOptions,\n ) {\n if (!clientId || !tenantId || !serviceConnectionId || !systemAccessToken) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. tenantId, clientId, serviceConnectionId, and systemAccessToken are required parameters.`,\n );\n }\n this.identityClient = new IdentityClient(options);\n checkTenantId(logger, tenantId);\n logger.info(\n `Invoking AzurePipelinesCredential with tenant ID: ${tenantId}, client ID: ${clientId}, and service connection ID: ${serviceConnectionId}`,\n );\n if (!process.env.SYSTEM_OIDCREQUESTURI) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. Ensure that you're running this task in an Azure Pipeline, so that following missing system variable(s) can be defined- \"SYSTEM_OIDCREQUESTURI\"`,\n );\n }\n\n const oidcRequestUrl = `${process.env.SYSTEM_OIDCREQUESTURI}?api-version=${OIDC_API_VERSION}&serviceConnectionId=${serviceConnectionId}`;\n logger.info(\n `Invoking ClientAssertionCredential with tenant ID: ${tenantId}, client ID: ${clientId} and service connection ID: ${serviceConnectionId}`,\n );\n this.clientAssertionCredential = new ClientAssertionCredential(\n tenantId,\n clientId,\n this.requestOidcToken.bind(this, oidcRequestUrl, systemAccessToken),\n options,\n );\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} or {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions,\n ): Promise<AccessToken> {\n if (!this.clientAssertionCredential) {\n const errorMessage = `${credentialName}: is unavailable. To use Federation Identity in Azure Pipelines, the following parameters are required - \n tenantId,\n clientId,\n serviceConnectionId,\n systemAccessToken,\n \"SYSTEM_OIDCREQUESTURI\". \n See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`;\n logger.error(errorMessage);\n throw new CredentialUnavailableError(errorMessage);\n }\n logger.info(\"Invoking getToken() of Client Assertion Credential\");\n return this.clientAssertionCredential.getToken(scopes, options);\n }\n\n /**\n *\n * @param oidcRequestUrl - oidc request url\n * @param systemAccessToken - system access token\n * @returns OIDC token from Azure Pipelines\n */\n private async requestOidcToken(\n oidcRequestUrl: string,\n systemAccessToken: string,\n ): Promise<string> {\n logger.info(\"Requesting OIDC token from Azure Pipelines...\");\n logger.info(oidcRequestUrl);\n const request = createPipelineRequest({\n url: oidcRequestUrl,\n method: \"POST\",\n headers: createHttpHeaders({\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${systemAccessToken}`,\n }),\n });\n const response = await this.identityClient.sendRequest(request);\n const text = response.bodyAsText;\n if (!text) {\n logger.error(\n `${credentialName}: Authenticated Failed. Received null token from OIDC request. Response status- ${\n response.status\n }. Complete response - ${JSON.stringify(response)}`,\n );\n throw new AuthenticationError(\n response.status,\n `${credentialName}: Authenticated Failed. Received null token from OIDC request. Response status- ${\n response.status\n }. Complete response - ${JSON.stringify(response)}`,\n );\n }\n try {\n const result = JSON.parse(text);\n if (result?.oidcToken) {\n return result.oidcToken;\n } else {\n let errorMessage = `${credentialName}: Authentication Failed. oidcToken field not detected in the response.`;\n if (response.status !== 200) {\n errorMessage += `Response = ${JSON.stringify(result)}`;\n }\n logger.error(errorMessage);\n throw new AuthenticationError(response.status, errorMessage);\n }\n } catch (e: any) {\n logger.error(e.message);\n logger.error(\n `${credentialName}: Authentication Failed. oidcToken field not detected in the response. Response = ${text}`,\n );\n throw new AuthenticationError(\n response.status,\n `${credentialName}: Authentication Failed. oidcToken field not detected in the response. Response = ${text}`,\n );\n }\n }\n}\n"]}
|
@@ -1,8 +1,8 @@
|
|
1
1
|
// Copyright (c) Microsoft Corporation.
|
2
2
|
// Licensed under the MIT license.
|
3
3
|
import * as msal from "@azure/msal-node";
|
4
|
-
import { msalPlugins } from "./msalPlugins";
|
5
4
|
import { credentialLogger, formatSuccess } from "../../util/logging";
|
5
|
+
import { msalPlugins } from "./msalPlugins";
|
6
6
|
import { defaultLoggerCallback, ensureValidMsalToken, getAuthority, getKnownAuthorities, getMSALLogLevel, handleMsalError, msalToPublic, publicToMsal, } from "../utils";
|
7
7
|
import { AuthenticationRequiredError } from "../../errors";
|
8
8
|
import { IdentityClient } from "../../client/identityClient";
|
@@ -10,7 +10,7 @@ import { calculateRegionalAuthority } from "../../regionalAuthority";
|
|
10
10
|
import { getLogLevel } from "@azure/logger";
|
11
11
|
import { resolveTenantId } from "../../util/tenantIdUtils";
|
12
12
|
/**
|
13
|
-
* The logger
|
13
|
+
* The default logger used if no logger was passed in by the credential.
|
14
14
|
*/
|
15
15
|
const msalLogger = credentialLogger("MsalClient");
|
16
16
|
/**
|
@@ -22,10 +22,10 @@ const msalLogger = credentialLogger("MsalClient");
|
|
22
22
|
* @returns The MSAL configuration object.
|
23
23
|
*/
|
24
24
|
export function generateMsalConfiguration(clientId, tenantId, msalClientOptions = {}) {
|
25
|
-
var _a, _b, _c;
|
26
|
-
const resolvedTenant = resolveTenantId(msalLogger, tenantId, clientId);
|
25
|
+
var _a, _b, _c, _d;
|
26
|
+
const resolvedTenant = resolveTenantId((_a = msalClientOptions.logger) !== null && _a !== void 0 ? _a : msalLogger, tenantId, clientId);
|
27
27
|
// TODO: move and reuse getIdentityClientAuthorityHost
|
28
|
-
const authority = getAuthority(resolvedTenant, (
|
28
|
+
const authority = getAuthority(resolvedTenant, (_b = msalClientOptions.authorityHost) !== null && _b !== void 0 ? _b : process.env.AZURE_AUTHORITY_HOST);
|
29
29
|
const httpClient = new IdentityClient(Object.assign(Object.assign({}, msalClientOptions.tokenCredentialOptions), { authorityHost: authority, loggingOptions: msalClientOptions.loggingOptions }));
|
30
30
|
const msalConfig = {
|
31
31
|
auth: {
|
@@ -36,9 +36,9 @@ export function generateMsalConfiguration(clientId, tenantId, msalClientOptions
|
|
36
36
|
system: {
|
37
37
|
networkClient: httpClient,
|
38
38
|
loggerOptions: {
|
39
|
-
loggerCallback: defaultLoggerCallback((
|
39
|
+
loggerCallback: defaultLoggerCallback((_c = msalClientOptions.logger) !== null && _c !== void 0 ? _c : msalLogger),
|
40
40
|
logLevel: getMSALLogLevel(getLogLevel()),
|
41
|
-
piiLoggingEnabled: (
|
41
|
+
piiLoggingEnabled: (_d = msalClientOptions.loggingOptions) === null || _d === void 0 ? void 0 : _d.enableUnsafeSupportLogging,
|
42
42
|
},
|
43
43
|
},
|
44
44
|
};
|
@@ -55,23 +55,25 @@ export function generateMsalConfiguration(clientId, tenantId, msalClientOptions
|
|
55
55
|
* @public
|
56
56
|
*/
|
57
57
|
export function createMsalClient(clientId, tenantId, createMsalClientOptions = {}) {
|
58
|
+
var _a;
|
58
59
|
const state = {
|
59
60
|
msalConfig: generateMsalConfiguration(clientId, tenantId, createMsalClientOptions),
|
60
61
|
cachedAccount: createMsalClientOptions.authenticationRecord
|
61
62
|
? publicToMsal(createMsalClientOptions.authenticationRecord)
|
62
63
|
: null,
|
63
64
|
pluginConfiguration: msalPlugins.generatePluginConfiguration(createMsalClientOptions),
|
65
|
+
logger: (_a = createMsalClientOptions.logger) !== null && _a !== void 0 ? _a : msalLogger,
|
64
66
|
};
|
65
67
|
const publicApps = new Map();
|
66
68
|
async function getPublicApp(options = {}) {
|
67
69
|
const appKey = options.enableCae ? "CAE" : "default";
|
68
70
|
let publicClientApp = publicApps.get(appKey);
|
69
71
|
if (publicClientApp) {
|
70
|
-
|
72
|
+
state.logger.getToken.info("Existing PublicClientApplication found in cache, returning it.");
|
71
73
|
return publicClientApp;
|
72
74
|
}
|
73
75
|
// Initialize a new app and cache it
|
74
|
-
|
76
|
+
state.logger.getToken.info(`Creating new PublicClientApplication with CAE ${options.enableCae ? "enabled" : "disabled"}.`);
|
75
77
|
const cachePlugin = options.enableCae
|
76
78
|
? state.pluginConfiguration.cache.cachePluginCae
|
77
79
|
: state.pluginConfiguration.cache.cachePlugin;
|
@@ -85,11 +87,11 @@ export function createMsalClient(clientId, tenantId, createMsalClientOptions = {
|
|
85
87
|
const appKey = options.enableCae ? "CAE" : "default";
|
86
88
|
let confidentialClientApp = confidentialApps.get(appKey);
|
87
89
|
if (confidentialClientApp) {
|
88
|
-
|
90
|
+
state.logger.getToken.info("Existing ConfidentialClientApplication found in cache, returning it.");
|
89
91
|
return confidentialClientApp;
|
90
92
|
}
|
91
93
|
// Initialize a new app and cache it
|
92
|
-
|
94
|
+
state.logger.getToken.info(`Creating new ConfidentialClientApplication with CAE ${options.enableCae ? "enabled" : "disabled"}.`);
|
93
95
|
const cachePlugin = options.enableCae
|
94
96
|
? state.pluginConfiguration.cache.cachePluginCae
|
95
97
|
: state.pluginConfiguration.cache.cachePlugin;
|
@@ -100,14 +102,15 @@ export function createMsalClient(clientId, tenantId, createMsalClientOptions = {
|
|
100
102
|
}
|
101
103
|
async function getTokenSilent(app, scopes, options = {}) {
|
102
104
|
if (state.cachedAccount === null) {
|
103
|
-
|
105
|
+
state.logger.getToken.info("No cached account found in local state, attempting to load it from MSAL cache.");
|
104
106
|
const cache = app.getTokenCache();
|
105
107
|
const accounts = await cache.getAllAccounts();
|
106
108
|
if (accounts === undefined || accounts.length === 0) {
|
107
109
|
throw new AuthenticationRequiredError({ scopes });
|
108
110
|
}
|
109
111
|
if (accounts.length > 1) {
|
110
|
-
|
112
|
+
state.logger
|
113
|
+
.info(`More than one account was found authenticated for this Client ID and Tenant ID.
|
111
114
|
However, no "authenticationRecord" has been provided for this credential,
|
112
115
|
therefore we're unable to pick between these accounts.
|
113
116
|
A new login attempt will be requested, to ensure the correct account is picked.
|
@@ -131,7 +134,7 @@ To work with multiple accounts for the same Client ID and Tenant ID, please prov
|
|
131
134
|
silentRequest.tokenQueryParameters["msal_request_type"] = "consumer_passthrough";
|
132
135
|
}
|
133
136
|
}
|
134
|
-
|
137
|
+
state.logger.getToken.info("Attempting to acquire token silently");
|
135
138
|
return app.acquireTokenSilent(silentRequest);
|
136
139
|
}
|
137
140
|
/**
|
@@ -174,14 +177,14 @@ To work with multiple accounts for the same Client ID and Tenant ID, please prov
|
|
174
177
|
// At this point we should have a token, process it
|
175
178
|
ensureValidMsalToken(scopes, response, options);
|
176
179
|
state.cachedAccount = (_a = response === null || response === void 0 ? void 0 : response.account) !== null && _a !== void 0 ? _a : null;
|
177
|
-
|
180
|
+
state.logger.getToken.info(formatSuccess(scopes));
|
178
181
|
return {
|
179
182
|
token: response.accessToken,
|
180
183
|
expiresOnTimestamp: response.expiresOn.getTime(),
|
181
184
|
};
|
182
185
|
}
|
183
186
|
async function getTokenByClientSecret(scopes, clientSecret, options = {}) {
|
184
|
-
|
187
|
+
state.logger.getToken.info(`Attempting to acquire token using client secret`);
|
185
188
|
state.msalConfig.auth.clientSecret = clientSecret;
|
186
189
|
const msalApp = await getConfidentialApp(options);
|
187
190
|
try {
|
@@ -192,7 +195,7 @@ To work with multiple accounts for the same Client ID and Tenant ID, please prov
|
|
192
195
|
claims: options === null || options === void 0 ? void 0 : options.claims,
|
193
196
|
});
|
194
197
|
ensureValidMsalToken(scopes, response, options);
|
195
|
-
|
198
|
+
state.logger.getToken.info(formatSuccess(scopes));
|
196
199
|
return {
|
197
200
|
token: response.accessToken,
|
198
201
|
expiresOnTimestamp: response.expiresOn.getTime(),
|
@@ -203,7 +206,7 @@ To work with multiple accounts for the same Client ID and Tenant ID, please prov
|
|
203
206
|
}
|
204
207
|
}
|
205
208
|
async function getTokenByClientAssertion(scopes, clientAssertion, options = {}) {
|
206
|
-
|
209
|
+
state.logger.getToken.info(`Attempting to acquire token using client assertion`);
|
207
210
|
state.msalConfig.auth.clientAssertion = clientAssertion;
|
208
211
|
const msalApp = await getConfidentialApp(options);
|
209
212
|
try {
|
@@ -215,7 +218,7 @@ To work with multiple accounts for the same Client ID and Tenant ID, please prov
|
|
215
218
|
clientAssertion,
|
216
219
|
});
|
217
220
|
ensureValidMsalToken(scopes, response, options);
|
218
|
-
|
221
|
+
state.logger.getToken.info(formatSuccess(scopes));
|
219
222
|
return {
|
220
223
|
token: response.accessToken,
|
221
224
|
expiresOnTimestamp: response.expiresOn.getTime(),
|
@@ -226,7 +229,7 @@ To work with multiple accounts for the same Client ID and Tenant ID, please prov
|
|
226
229
|
}
|
227
230
|
}
|
228
231
|
async function getTokenByClientCertificate(scopes, certificate, options = {}) {
|
229
|
-
|
232
|
+
state.logger.getToken.info(`Attempting to acquire token using client certificate`);
|
230
233
|
state.msalConfig.auth.clientCertificate = certificate;
|
231
234
|
const msalApp = await getConfidentialApp(options);
|
232
235
|
try {
|
@@ -237,7 +240,7 @@ To work with multiple accounts for the same Client ID and Tenant ID, please prov
|
|
237
240
|
claims: options === null || options === void 0 ? void 0 : options.claims,
|
238
241
|
});
|
239
242
|
ensureValidMsalToken(scopes, response, options);
|
240
|
-
|
243
|
+
state.logger.getToken.info(formatSuccess(scopes));
|
241
244
|
return {
|
242
245
|
token: response.accessToken,
|
243
246
|
expiresOnTimestamp: response.expiresOn.getTime(),
|
@@ -248,7 +251,7 @@ To work with multiple accounts for the same Client ID and Tenant ID, please prov
|
|
248
251
|
}
|
249
252
|
}
|
250
253
|
async function getTokenByDeviceCode(scopes, deviceCodeCallback, options = {}) {
|
251
|
-
|
254
|
+
state.logger.getToken.info(`Attempting to acquire token using device code`);
|
252
255
|
const msalApp = await getPublicApp(options);
|
253
256
|
return withSilentAuthentication(msalApp, scopes, options, () => {
|
254
257
|
var _a, _b;
|
@@ -269,7 +272,7 @@ To work with multiple accounts for the same Client ID and Tenant ID, please prov
|
|
269
272
|
});
|
270
273
|
}
|
271
274
|
async function getTokenByUsernamePassword(scopes, username, password, options = {}) {
|
272
|
-
|
275
|
+
state.logger.getToken.info(`Attempting to acquire token using username and password`);
|
273
276
|
const msalApp = await getPublicApp(options);
|
274
277
|
return withSilentAuthentication(msalApp, scopes, options, () => {
|
275
278
|
const requestOptions = {
|
@@ -289,7 +292,7 @@ To work with multiple accounts for the same Client ID and Tenant ID, please prov
|
|
289
292
|
return msalToPublic(clientId, state.cachedAccount);
|
290
293
|
}
|
291
294
|
async function getTokenByAuthorizationCode(scopes, redirectUri, authorizationCode, clientSecret, options = {}) {
|
292
|
-
|
295
|
+
state.logger.getToken.info(`Attempting to acquire token using authorization code`);
|
293
296
|
let msalApp;
|
294
297
|
if (clientSecret) {
|
295
298
|
// If a client secret is provided, we need to use a confidential client application
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"msalClient.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,IAAI,MAAM,kBAAkB,CAAC;AAGzC,OAAO,EAAuB,WAAW,EAAE,MAAM,eAAe,CAAC;AACjE,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACrE,OAAO,EACL,qBAAqB,EACrB,oBAAoB,EACpB,YAAY,EACZ,mBAAmB,EACnB,eAAe,EACf,eAAe,EACf,YAAY,EACZ,YAAY,GACb,MAAM,UAAU,CAAC;AAElB,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAE3D,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAE7D,OAAO,EAAE,0BAA0B,EAAE,MAAM,yBAAyB,CAAC;AACrE,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAG3D;;GAEG;AACH,MAAM,UAAU,GAAG,gBAAgB,CAAC,YAAY,CAAC,CAAC;AA0HlD;;;;;;;GAOG;AACH,MAAM,UAAU,yBAAyB,CACvC,QAAgB,EAChB,QAAgB,EAChB,oBAAuC,EAAE;;IAEzC,MAAM,cAAc,GAAG,eAAe,CAAC,UAAU,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC;IAEvE,sDAAsD;IACtD,MAA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E,OAAO,EAAE,GAAG,EAAE;YAC7D,OAAO,OAAO,CAAC,kBAAkB,CAAC;gBAChC,MAAM;gBACN,WAAW;gBACX,IAAI,EAAE,iBAAiB;gBACvB,SAAS,EAAE,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,SAAS;gBAC1C,MAAM,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,MAAM;aACxB,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;IAED,OAAO;QACL,gBAAgB;QAChB,sBAAsB;QACtB,yBAAyB;QACzB,2BAA2B;QAC3B,oBAAoB;QACpB,0BAA0B;QAC1B,2BAA2B;KAC5B,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msal from \"@azure/msal-node\";\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { PluginConfiguration, msalPlugins } from \"./msalPlugins\";\nimport { credentialLogger, formatSuccess } from \"../../util/logging\";\nimport {\n defaultLoggerCallback,\n ensureValidMsalToken,\n getAuthority,\n getKnownAuthorities,\n getMSALLogLevel,\n handleMsalError,\n msalToPublic,\n publicToMsal,\n} from \"../utils\";\n\nimport { AuthenticationRequiredError } from \"../../errors\";\nimport { AuthenticationRecord, CertificateParts } from \"../types\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { MsalNodeOptions } from \"./msalNodeCommon\";\nimport { calculateRegionalAuthority } from \"../../regionalAuthority\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { resolveTenantId } from \"../../util/tenantIdUtils\";\nimport { DeviceCodePromptCallback } from \"../../credentials/deviceCodeCredentialOptions\";\n\n/**\n * The logger for all MsalClient instances.\n */\nconst msalLogger = credentialLogger(\"MsalClient\");\n\nexport interface GetTokenWithSilentAuthOptions extends GetTokenOptions {\n /**\n * Disables automatic authentication. If set to true, the method will throw an error if the user needs to authenticate.\n *\n * @remarks\n *\n * This option will be set to `false` when the user calls `authenticate` directly on a credential that supports it.\n */\n disableAutomaticAuthentication?: boolean;\n}\n\n/**\n * Represents a client for interacting with the Microsoft Authentication Library (MSAL).\n */\nexport interface MsalClient {\n /**\n * Retrieves an access token by using a user's username and password.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param username - The username provided by the developer.\n * @param password - The user's password provided by the developer.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByUsernamePassword(\n scopes: string[],\n username: string,\n password: string,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n /**\n * Retrieves an access token by prompting the user to authenticate using a device code.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param userPromptCallback - The callback function that allows developers to customize the prompt message.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByDeviceCode(\n scopes: string[],\n userPromptCallback: DeviceCodePromptCallback,\n options?: GetTokenWithSilentAuthOptions,\n ): Promise<AccessToken>;\n /**\n * Retrieves an access token by using a client certificate.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param certificate - The client certificate used for authentication.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByClientCertificate(\n scopes: string[],\n certificate: CertificateParts,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using a client assertion.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param clientAssertion - The client assertion used for authentication.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByClientAssertion(\n scopes: string[],\n clientAssertion: string,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using a client secret.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param clientSecret - The client secret of the application. This is a credential that the application can use to authenticate itself.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByClientSecret(\n scopes: string[],\n clientSecret: string,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using an authorization code flow.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param authorizationCode - An authorization code that was received from following the\n authorization code flow. This authorization code must not\n have already been used to obtain an access token.\n * @param redirectUri - The redirect URI that was used to request the authorization code.\n Must be the same URI that is configured for the App Registration.\n * @param clientSecret - An optional client secret that was generated for the App Registration.\n * @param options - Additional options that may be provided to the method.\n */\n getTokenByAuthorizationCode(\n scopes: string[],\n redirectUri: string,\n authorizationCode: string,\n clientSecret?: string,\n options?: GetTokenWithSilentAuthOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves the last authenticated account. This method expects an authentication record to have been previously loaded.\n *\n * An authentication record could be loaded by calling the `getToken` method, or by providing an `authenticationRecord` when creating a credential.\n */\n getActiveAccount(): AuthenticationRecord | undefined;\n}\n\n/**\n * Options for creating an instance of the MsalClient.\n */\nexport type MsalClientOptions = Partial<\n Omit<MsalNodeOptions, \"clientId\" | \"tenantId\" | \"disableAutomaticAuthentication\">\n>;\n\n/**\n * Generates the configuration for MSAL (Microsoft Authentication Library).\n *\n * @param clientId - The client ID of the application.\n * @param tenantId - The tenant ID of the Azure Active Directory.\n * @param msalClientOptions - Optional. Additional options for creating the MSAL client.\n * @returns The MSAL configuration object.\n */\nexport function generateMsalConfiguration(\n clientId: string,\n tenantId: string,\n msalClientOptions: MsalClientOptions = {},\n): msal.Configuration {\n const resolvedTenant = resolveTenantId(msalLogger, tenantId, clientId);\n\n // TODO: move and reuse getIdentityClientAuthorityHost\n const authority = getAuthority(\n resolvedTenant,\n msalClientOptions.authorityHost ?? process.env.AZURE_AUTHORITY_HOST,\n );\n\n const httpClient = new IdentityClient({\n ...msalClientOptions.tokenCredentialOptions,\n authorityHost: authority,\n loggingOptions: msalClientOptions.loggingOptions,\n });\n\n const msalConfig: msal.Configuration = {\n auth: {\n clientId,\n authority,\n knownAuthorities: getKnownAuthorities(\n resolvedTenant,\n authority,\n msalClientOptions.disableInstanceDiscovery,\n ),\n },\n system: {\n networkClient: httpClient,\n loggerOptions: {\n loggerCallback: defaultLoggerCallback(msalClientOptions.logger ?? msalLogger),\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: msalClientOptions.loggingOptions?.enableUnsafeSupportLogging,\n },\n },\n };\n return msalConfig;\n}\n\n/**\n * Represents the state necessary for the MSAL (Microsoft Authentication Library) client to operate.\n * This includes the MSAL configuration, cached account information, Azure region, and a flag to disable automatic authentication.\n *\n * @internal\n */\ninterface MsalClientState {\n /** The configuration for the MSAL client. */\n msalConfig: msal.Configuration;\n\n /** The cached account information, or null if no account information is cached. */\n cachedAccount: msal.AccountInfo | null;\n\n /** Configured plugins */\n pluginConfiguration: PluginConfiguration;\n\n /** Claims received from challenges, cached for the next request */\n cachedClaims?: string;\n}\n\n/**\n * Creates an instance of the MSAL (Microsoft Authentication Library) client.\n *\n * @param clientId - The client ID of the application.\n * @param tenantId - The tenant ID of the Azure Active Directory.\n * @param createMsalClientOptions - Optional. Additional options for creating the MSAL client.\n * @returns An instance of the MSAL client.\n *\n * @public\n */\nexport function createMsalClient(\n clientId: string,\n tenantId: string,\n createMsalClientOptions: MsalClientOptions = {},\n): MsalClient {\n const state: MsalClientState = {\n msalConfig: generateMsalConfiguration(clientId, tenantId, createMsalClientOptions),\n cachedAccount: createMsalClientOptions.authenticationRecord\n ? publicToMsal(createMsalClientOptions.authenticationRecord)\n : null,\n pluginConfiguration: msalPlugins.generatePluginConfiguration(createMsalClientOptions),\n };\n\n const publicApps: Map<string, msal.PublicClientApplication> = new Map();\n async function getPublicApp(\n options: GetTokenOptions = {},\n ): Promise<msal.PublicClientApplication> {\n const appKey = options.enableCae ? \"CAE\" : \"default\";\n\n let publicClientApp = publicApps.get(appKey);\n if (publicClientApp) {\n msalLogger.getToken.info(\"Existing PublicClientApplication found in cache, returning it.\");\n return publicClientApp;\n }\n\n // Initialize a new app and cache it\n msalLogger.getToken.info(\n `Creating new PublicClientApplication with CAE ${options.enableCae ? \"enabled\" : \"disabled\"}.`,\n );\n\n const cachePlugin = options.enableCae\n ? state.pluginConfiguration.cache.cachePluginCae\n : state.pluginConfiguration.cache.cachePlugin;\n\n state.msalConfig.auth.clientCapabilities = options.enableCae ? [\"cp1\"] : undefined;\n\n publicClientApp = new msal.PublicClientApplication({\n ...state.msalConfig,\n broker: { nativeBrokerPlugin: state.pluginConfiguration.broker.nativeBrokerPlugin },\n cache: { cachePlugin: await cachePlugin },\n });\n\n publicApps.set(appKey, publicClientApp);\n\n return publicClientApp;\n }\n\n const confidentialApps: Map<string, msal.ConfidentialClientApplication> = new Map();\n async function getConfidentialApp(\n options: GetTokenOptions = {},\n ): Promise<msal.ConfidentialClientApplication> {\n const appKey = options.enableCae ? \"CAE\" : \"default\";\n\n let confidentialClientApp = confidentialApps.get(appKey);\n if (confidentialClientApp) {\n msalLogger.getToken.info(\n \"Existing ConfidentialClientApplication found in cache, returning it.\",\n );\n return confidentialClientApp;\n }\n\n // Initialize a new app and cache it\n msalLogger.getToken.info(\n `Creating new ConfidentialClientApplication with CAE ${options.enableCae ? \"enabled\" : \"disabled\"}.`,\n );\n\n const cachePlugin = options.enableCae\n ? state.pluginConfiguration.cache.cachePluginCae\n : state.pluginConfiguration.cache.cachePlugin;\n\n state.msalConfig.auth.clientCapabilities = options.enableCae ? [\"cp1\"] : undefined;\n\n confidentialClientApp = new msal.ConfidentialClientApplication({\n ...state.msalConfig,\n broker: { nativeBrokerPlugin: state.pluginConfiguration.broker.nativeBrokerPlugin },\n cache: { cachePlugin: await cachePlugin },\n });\n\n confidentialApps.set(appKey, confidentialClientApp);\n\n return confidentialClientApp;\n }\n\n async function getTokenSilent(\n app: msal.ConfidentialClientApplication | msal.PublicClientApplication,\n scopes: string[],\n options: GetTokenOptions = {},\n ): Promise<msal.AuthenticationResult> {\n if (state.cachedAccount === null) {\n msalLogger.getToken.info(\n \"No cached account found in local state, attempting to load it from MSAL cache.\",\n );\n const cache = app.getTokenCache();\n const accounts = await cache.getAllAccounts();\n\n if (accounts === undefined || accounts.length === 0) {\n throw new AuthenticationRequiredError({ scopes });\n }\n\n if (accounts.length > 1) {\n msalLogger.info(`More than one account was found authenticated for this Client ID and Tenant ID.\nHowever, no \"authenticationRecord\" has been provided for this credential,\ntherefore we're unable to pick between these accounts.\nA new login attempt will be requested, to ensure the correct account is picked.\nTo work with multiple accounts for the same Client ID and Tenant ID, please provide an \"authenticationRecord\" when initializing a credential to prevent this from happening.`);\n throw new AuthenticationRequiredError({ scopes });\n }\n\n state.cachedAccount = accounts[0];\n }\n\n // Keep track and reuse the claims we received across challenges\n if (options.claims) {\n state.cachedClaims = options.claims;\n }\n\n const silentRequest: msal.SilentFlowRequest = {\n account: state.cachedAccount,\n scopes,\n claims: state.cachedClaims,\n };\n\n if (state.pluginConfiguration.broker.isEnabled) {\n silentRequest.tokenQueryParameters ||= {};\n if (state.pluginConfiguration.broker.enableMsaPassthrough) {\n silentRequest.tokenQueryParameters[\"msal_request_type\"] = \"consumer_passthrough\";\n }\n }\n\n msalLogger.getToken.info(\"Attempting to acquire token silently\");\n return app.acquireTokenSilent(silentRequest);\n }\n\n /**\n * Performs silent authentication using MSAL to acquire an access token.\n * If silent authentication fails, falls back to interactive authentication.\n *\n * @param msalApp - The MSAL application instance.\n * @param scopes - The scopes for which to acquire the access token.\n * @param options - The options for acquiring the access token.\n * @param onAuthenticationRequired - A callback function to handle interactive authentication when silent authentication fails.\n * @returns A promise that resolves to an AccessToken object containing the access token and its expiration timestamp.\n */\n async function withSilentAuthentication(\n msalApp: msal.ConfidentialClientApplication | msal.PublicClientApplication,\n scopes: Array<string>,\n options: GetTokenWithSilentAuthOptions,\n onAuthenticationRequired: () => Promise<msal.AuthenticationResult | null>,\n ): Promise<AccessToken> {\n let response: msal.AuthenticationResult | null = null;\n try {\n response = await getTokenSilent(msalApp, scopes, options);\n } catch (e: any) {\n if (e.name !== \"AuthenticationRequiredError\") {\n throw e;\n }\n if (options.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Automatic authentication has been disabled. You may call the authentication() method.\",\n });\n }\n }\n\n // Silent authentication failed\n if (response === null) {\n try {\n response = await onAuthenticationRequired();\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n // At this point we should have a token, process it\n ensureValidMsalToken(scopes, response, options);\n state.cachedAccount = response?.account ?? null;\n\n msalLogger.getToken.info(formatSuccess(scopes));\n\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n };\n }\n\n async function getTokenByClientSecret(\n scopes: string[],\n clientSecret: string,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n msalLogger.getToken.info(`Attempting to acquire token using client secret`);\n\n state.msalConfig.auth.clientSecret = clientSecret;\n\n const msalApp = await getConfidentialApp(options);\n\n try {\n const response = await msalApp.acquireTokenByClientCredential({\n scopes,\n authority: state.msalConfig.auth.authority,\n azureRegion: calculateRegionalAuthority(),\n claims: options?.claims,\n });\n ensureValidMsalToken(scopes, response, options);\n\n msalLogger.getToken.info(formatSuccess(scopes));\n\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n };\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n async function getTokenByClientAssertion(\n scopes: string[],\n clientAssertion: string,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n msalLogger.getToken.info(`Attempting to acquire token using client assertion`);\n\n state.msalConfig.auth.clientAssertion = clientAssertion;\n\n const msalApp = await getConfidentialApp(options);\n\n try {\n const response = await msalApp.acquireTokenByClientCredential({\n scopes,\n authority: state.msalConfig.auth.authority,\n azureRegion: calculateRegionalAuthority(),\n claims: options?.claims,\n clientAssertion,\n });\n ensureValidMsalToken(scopes, response, options);\n\n msalLogger.getToken.info(formatSuccess(scopes));\n\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n };\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n async function getTokenByClientCertificate(\n scopes: string[],\n certificate: CertificateParts,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n msalLogger.getToken.info(`Attempting to acquire token using client certificate`);\n\n state.msalConfig.auth.clientCertificate = certificate;\n\n const msalApp = await getConfidentialApp(options);\n try {\n const response = await msalApp.acquireTokenByClientCredential({\n scopes,\n authority: state.msalConfig.auth.authority,\n azureRegion: calculateRegionalAuthority(),\n claims: options?.claims,\n });\n ensureValidMsalToken(scopes, response, options);\n\n msalLogger.getToken.info(formatSuccess(scopes));\n\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n };\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n async function getTokenByDeviceCode(\n scopes: string[],\n deviceCodeCallback: DeviceCodePromptCallback,\n options: GetTokenWithSilentAuthOptions = {},\n ): Promise<AccessToken> {\n msalLogger.getToken.info(`Attempting to acquire token using device code`);\n\n const msalApp = await getPublicApp(options);\n\n return withSilentAuthentication(msalApp, scopes, options, () => {\n const requestOptions: msal.DeviceCodeRequest = {\n scopes,\n cancel: options?.abortSignal?.aborted ?? false,\n deviceCodeCallback,\n authority: state.msalConfig.auth.authority,\n claims: options?.claims,\n };\n const deviceCodeRequest = msalApp.acquireTokenByDeviceCode(requestOptions);\n if (options.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", () => {\n requestOptions.cancel = true;\n });\n }\n\n return deviceCodeRequest;\n });\n }\n\n async function getTokenByUsernamePassword(\n scopes: string[],\n username: string,\n password: string,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n msalLogger.getToken.info(`Attempting to acquire token using username and password`);\n\n const msalApp = await getPublicApp(options);\n\n return withSilentAuthentication(msalApp, scopes, options, () => {\n const requestOptions: msal.UsernamePasswordRequest = {\n scopes,\n username,\n password,\n authority: state.msalConfig.auth.authority,\n claims: options?.claims,\n };\n\n return msalApp.acquireTokenByUsernamePassword(requestOptions);\n });\n }\n\n function getActiveAccount(): AuthenticationRecord | undefined {\n if (!state.cachedAccount) {\n return undefined;\n }\n return msalToPublic(clientId, state.cachedAccount);\n }\n\n async function getTokenByAuthorizationCode(\n scopes: string[],\n redirectUri: string,\n authorizationCode: string,\n clientSecret?: string,\n options: GetTokenWithSilentAuthOptions = {},\n ): Promise<AccessToken> {\n msalLogger.getToken.info(`Attempting to acquire token using authorization code`);\n\n let msalApp: msal.ConfidentialClientApplication | msal.PublicClientApplication;\n if (clientSecret) {\n // If a client secret is provided, we need to use a confidential client application\n // See https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow#request-an-access-token-with-a-client_secret\n state.msalConfig.auth.clientSecret = clientSecret;\n msalApp = await getConfidentialApp(options);\n } else {\n msalApp = await getPublicApp(options);\n }\n\n return withSilentAuthentication(msalApp, scopes, options, () => {\n return msalApp.acquireTokenByCode({\n scopes,\n redirectUri,\n code: authorizationCode,\n authority: state.msalConfig.auth.authority,\n claims: options?.claims,\n });\n });\n }\n\n return {\n getActiveAccount,\n getTokenByClientSecret,\n getTokenByClientAssertion,\n getTokenByClientCertificate,\n getTokenByDeviceCode,\n getTokenByUsernamePassword,\n getTokenByAuthorizationCode,\n };\n}\n"]}
|
1
|
+
{"version":3,"file":"msalClient.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,IAAI,MAAM,kBAAkB,CAAC;AAIzC,OAAO,EAAoB,gBAAgB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACvF,OAAO,EAAuB,WAAW,EAAE,MAAM,eAAe,CAAC;AACjE,OAAO,EACL,qBAAqB,EACrB,oBAAoB,EACpB,YAAY,EACZ,mBAAmB,EACnB,eAAe,EACf,eAAe,EACf,YAAY,EACZ,YAAY,GACb,MAAM,UAAU,CAAC;AAElB,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,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poration.\n// Licensed under the MIT license.\n\nimport * as msal from \"@azure/msal-node\";\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AuthenticationRecord, CertificateParts } from \"../types\";\nimport { CredentialLogger, credentialLogger, formatSuccess } from \"../../util/logging\";\nimport { PluginConfiguration, msalPlugins } from \"./msalPlugins\";\nimport {\n defaultLoggerCallback,\n ensureValidMsalToken,\n getAuthority,\n getKnownAuthorities,\n getMSALLogLevel,\n handleMsalError,\n msalToPublic,\n publicToMsal,\n} from \"../utils\";\n\nimport { AuthenticationRequiredError } from \"../../errors\";\nimport { BrokerOptions } from \"./brokerOptions\";\nimport { DeviceCodePromptCallback } from \"../../credentials/deviceCodeCredentialOptions\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions\";\nimport { calculateRegionalAuthority } from \"../../regionalAuthority\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { resolveTenantId } from \"../../util/tenantIdUtils\";\n\n/**\n * The default logger used if no logger was passed in by the credential.\n */\nconst msalLogger = credentialLogger(\"MsalClient\");\n\nexport interface GetTokenWithSilentAuthOptions extends GetTokenOptions {\n /**\n * Disables automatic authentication. If set to true, the method will throw an error if the user needs to authenticate.\n *\n * @remarks\n *\n * This option will be set to `false` when the user calls `authenticate` directly on a credential that supports it.\n */\n disableAutomaticAuthentication?: boolean;\n}\n\n/**\n * Represents a client for interacting with the Microsoft Authentication Library (MSAL).\n */\nexport interface MsalClient {\n /**\n * Retrieves an access token by using a user's username and password.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param username - The username provided by the developer.\n * @param password - The user's password provided by the developer.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByUsernamePassword(\n scopes: string[],\n username: string,\n password: string,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n /**\n * Retrieves an access token by prompting the user to authenticate using a device code.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param userPromptCallback - The callback function that allows developers to customize the prompt message.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByDeviceCode(\n scopes: string[],\n userPromptCallback: DeviceCodePromptCallback,\n options?: GetTokenWithSilentAuthOptions,\n ): Promise<AccessToken>;\n /**\n * Retrieves an access token by using a client certificate.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param certificate - The client certificate used for authentication.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByClientCertificate(\n scopes: string[],\n certificate: CertificateParts,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using a client assertion.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param clientAssertion - The client assertion used for authentication.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByClientAssertion(\n scopes: string[],\n clientAssertion: string,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using a client secret.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param clientSecret - The client secret of the application. This is a credential that the application can use to authenticate itself.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByClientSecret(\n scopes: string[],\n clientSecret: string,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using an authorization code flow.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param authorizationCode - An authorization code that was received from following the\n authorization code flow. This authorization code must not\n have already been used to obtain an access token.\n * @param redirectUri - The redirect URI that was used to request the authorization code.\n Must be the same URI that is configured for the App Registration.\n * @param clientSecret - An optional client secret that was generated for the App Registration.\n * @param options - Additional options that may be provided to the method.\n */\n getTokenByAuthorizationCode(\n scopes: string[],\n redirectUri: string,\n authorizationCode: string,\n clientSecret?: string,\n options?: GetTokenWithSilentAuthOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves the last authenticated account. This method expects an authentication record to have been previously loaded.\n *\n * An authentication record could be loaded by calling the `getToken` method, or by providing an `authenticationRecord` when creating a credential.\n */\n getActiveAccount(): AuthenticationRecord | undefined;\n}\n\n/**\n * Represents the options for configuring the MsalClient.\n */\nexport interface MsalClientOptions {\n /**\n * Parameters that enable WAM broker authentication in the InteractiveBrowserCredential.\n */\n brokerOptions?: BrokerOptions;\n\n /**\n * Parameters that enable token cache persistence in the Identity credentials.\n */\n tokenCachePersistenceOptions?: TokenCachePersistenceOptions;\n\n /**\n * A custom authority host.\n */\n authorityHost?: IdentityClient[\"tokenCredentialOptions\"][\"authorityHost\"];\n\n /**\n * Allows users to configure settings for logging policy options, allow logging account information and personally identifiable information for customer support.\n */\n loggingOptions?: IdentityClient[\"tokenCredentialOptions\"][\"loggingOptions\"];\n\n /**\n * The token credential options for the MsalClient.\n */\n tokenCredentialOptions?: IdentityClient[\"tokenCredentialOptions\"];\n\n /**\n * Determines whether instance discovery is disabled.\n */\n disableInstanceDiscovery?: boolean;\n\n /**\n * The logger for the MsalClient.\n */\n logger?: CredentialLogger;\n\n /**\n * The authentication record for the MsalClient.\n */\n authenticationRecord?: AuthenticationRecord;\n}\n\n/**\n * Generates the configuration for MSAL (Microsoft Authentication Library).\n *\n * @param clientId - The client ID of the application.\n * @param tenantId - The tenant ID of the Azure Active Directory.\n * @param msalClientOptions - Optional. Additional options for creating the MSAL client.\n * @returns The MSAL configuration object.\n */\nexport function generateMsalConfiguration(\n clientId: string,\n tenantId: string,\n msalClientOptions: MsalClientOptions = {},\n): msal.Configuration {\n const resolvedTenant = resolveTenantId(\n msalClientOptions.logger ?? msalLogger,\n tenantId,\n clientId,\n );\n\n // TODO: move and reuse getIdentityClientAuthorityHost\n const authority = getAuthority(\n resolvedTenant,\n msalClientOptions.authorityHost ?? process.env.AZURE_AUTHORITY_HOST,\n );\n\n const httpClient = new IdentityClient({\n ...msalClientOptions.tokenCredentialOptions,\n authorityHost: authority,\n loggingOptions: msalClientOptions.loggingOptions,\n });\n\n const msalConfig: msal.Configuration = {\n auth: {\n clientId,\n authority,\n knownAuthorities: getKnownAuthorities(\n resolvedTenant,\n authority,\n msalClientOptions.disableInstanceDiscovery,\n ),\n },\n system: {\n networkClient: httpClient,\n loggerOptions: {\n loggerCallback: defaultLoggerCallback(msalClientOptions.logger ?? msalLogger),\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: msalClientOptions.loggingOptions?.enableUnsafeSupportLogging,\n },\n },\n };\n return msalConfig;\n}\n\n/**\n * Represents the state necessary for the MSAL (Microsoft Authentication Library) client to operate.\n * This includes the MSAL configuration, cached account information, Azure region, and a flag to disable automatic authentication.\n *\n * @internal\n */\ninterface MsalClientState {\n /** The configuration for the MSAL client. */\n msalConfig: msal.Configuration;\n\n /** The cached account information, or null if no account information is cached. */\n cachedAccount: msal.AccountInfo | null;\n\n /** Configured plugins */\n pluginConfiguration: PluginConfiguration;\n\n /** Claims received from challenges, cached for the next request */\n cachedClaims?: string;\n\n /** The logger instance */\n logger: CredentialLogger;\n}\n\n/**\n * Creates an instance of the MSAL (Microsoft Authentication Library) client.\n *\n * @param clientId - The client ID of the application.\n * @param tenantId - The tenant ID of the Azure Active Directory.\n * @param createMsalClientOptions - Optional. Additional options for creating the MSAL client.\n * @returns An instance of the MSAL client.\n *\n * @public\n */\nexport function createMsalClient(\n clientId: string,\n tenantId: string,\n createMsalClientOptions: MsalClientOptions = {},\n): MsalClient {\n const state: MsalClientState = {\n msalConfig: generateMsalConfiguration(clientId, tenantId, createMsalClientOptions),\n cachedAccount: createMsalClientOptions.authenticationRecord\n ? publicToMsal(createMsalClientOptions.authenticationRecord)\n : null,\n pluginConfiguration: msalPlugins.generatePluginConfiguration(createMsalClientOptions),\n logger: createMsalClientOptions.logger ?? msalLogger,\n };\n\n const publicApps: Map<string, msal.PublicClientApplication> = new Map();\n async function getPublicApp(\n options: GetTokenOptions = {},\n ): Promise<msal.PublicClientApplication> {\n const appKey = options.enableCae ? \"CAE\" : \"default\";\n\n let publicClientApp = publicApps.get(appKey);\n if (publicClientApp) {\n state.logger.getToken.info(\"Existing PublicClientApplication found in cache, returning it.\");\n return publicClientApp;\n }\n\n // Initialize a new app and cache it\n state.logger.getToken.info(\n `Creating new PublicClientApplication with CAE ${options.enableCae ? \"enabled\" : \"disabled\"}.`,\n );\n\n const cachePlugin = options.enableCae\n ? state.pluginConfiguration.cache.cachePluginCae\n : state.pluginConfiguration.cache.cachePlugin;\n\n state.msalConfig.auth.clientCapabilities = options.enableCae ? [\"cp1\"] : undefined;\n\n publicClientApp = new msal.PublicClientApplication({\n ...state.msalConfig,\n broker: { nativeBrokerPlugin: state.pluginConfiguration.broker.nativeBrokerPlugin },\n cache: { cachePlugin: await cachePlugin },\n });\n\n publicApps.set(appKey, publicClientApp);\n\n return publicClientApp;\n }\n\n const confidentialApps: Map<string, msal.ConfidentialClientApplication> = new Map();\n async function getConfidentialApp(\n options: GetTokenOptions = {},\n ): Promise<msal.ConfidentialClientApplication> {\n const appKey = options.enableCae ? \"CAE\" : \"default\";\n\n let confidentialClientApp = confidentialApps.get(appKey);\n if (confidentialClientApp) {\n state.logger.getToken.info(\n \"Existing ConfidentialClientApplication found in cache, returning it.\",\n );\n return confidentialClientApp;\n }\n\n // Initialize a new app and cache it\n state.logger.getToken.info(\n `Creating new ConfidentialClientApplication with CAE ${options.enableCae ? \"enabled\" : \"disabled\"}.`,\n );\n\n const cachePlugin = options.enableCae\n ? state.pluginConfiguration.cache.cachePluginCae\n : state.pluginConfiguration.cache.cachePlugin;\n\n state.msalConfig.auth.clientCapabilities = options.enableCae ? [\"cp1\"] : undefined;\n\n confidentialClientApp = new msal.ConfidentialClientApplication({\n ...state.msalConfig,\n broker: { nativeBrokerPlugin: state.pluginConfiguration.broker.nativeBrokerPlugin },\n cache: { cachePlugin: await cachePlugin },\n });\n\n confidentialApps.set(appKey, confidentialClientApp);\n\n return confidentialClientApp;\n }\n\n async function getTokenSilent(\n app: msal.ConfidentialClientApplication | msal.PublicClientApplication,\n scopes: string[],\n options: GetTokenOptions = {},\n ): Promise<msal.AuthenticationResult> {\n if (state.cachedAccount === null) {\n state.logger.getToken.info(\n \"No cached account found in local state, attempting to load it from MSAL cache.\",\n );\n const cache = app.getTokenCache();\n const accounts = await cache.getAllAccounts();\n\n if (accounts === undefined || accounts.length === 0) {\n throw new AuthenticationRequiredError({ scopes });\n }\n\n if (accounts.length > 1) {\n state.logger\n .info(`More than one account was found authenticated for this Client ID and Tenant ID.\nHowever, no \"authenticationRecord\" has been provided for this credential,\ntherefore we're unable to pick between these accounts.\nA new login attempt will be requested, to ensure the correct account is picked.\nTo work with multiple accounts for the same Client ID and Tenant ID, please provide an \"authenticationRecord\" when initializing a credential to prevent this from happening.`);\n throw new AuthenticationRequiredError({ scopes });\n }\n\n state.cachedAccount = accounts[0];\n }\n\n // Keep track and reuse the claims we received across challenges\n if (options.claims) {\n state.cachedClaims = options.claims;\n }\n\n const silentRequest: msal.SilentFlowRequest = {\n account: state.cachedAccount,\n scopes,\n claims: state.cachedClaims,\n };\n\n if (state.pluginConfiguration.broker.isEnabled) {\n silentRequest.tokenQueryParameters ||= {};\n if (state.pluginConfiguration.broker.enableMsaPassthrough) {\n silentRequest.tokenQueryParameters[\"msal_request_type\"] = \"consumer_passthrough\";\n }\n }\n\n state.logger.getToken.info(\"Attempting to acquire token silently\");\n return app.acquireTokenSilent(silentRequest);\n }\n\n /**\n * Performs silent authentication using MSAL to acquire an access token.\n * If silent authentication fails, falls back to interactive authentication.\n *\n * @param msalApp - The MSAL application instance.\n * @param scopes - The scopes for which to acquire the access token.\n * @param options - The options for acquiring the access token.\n * @param onAuthenticationRequired - A callback function to handle interactive authentication when silent authentication fails.\n * @returns A promise that resolves to an AccessToken object containing the access token and its expiration timestamp.\n */\n async function withSilentAuthentication(\n msalApp: msal.ConfidentialClientApplication | msal.PublicClientApplication,\n scopes: Array<string>,\n options: GetTokenWithSilentAuthOptions,\n onAuthenticationRequired: () => Promise<msal.AuthenticationResult | null>,\n ): Promise<AccessToken> {\n let response: msal.AuthenticationResult | null = null;\n try {\n response = await getTokenSilent(msalApp, scopes, options);\n } catch (e: any) {\n if (e.name !== \"AuthenticationRequiredError\") {\n throw e;\n }\n if (options.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Automatic authentication has been disabled. You may call the authentication() method.\",\n });\n }\n }\n\n // Silent authentication failed\n if (response === null) {\n try {\n response = await onAuthenticationRequired();\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n // At this point we should have a token, process it\n ensureValidMsalToken(scopes, response, options);\n state.cachedAccount = response?.account ?? null;\n\n state.logger.getToken.info(formatSuccess(scopes));\n\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n };\n }\n\n async function getTokenByClientSecret(\n scopes: string[],\n clientSecret: string,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using client secret`);\n\n state.msalConfig.auth.clientSecret = clientSecret;\n\n const msalApp = await getConfidentialApp(options);\n\n try {\n const response = await msalApp.acquireTokenByClientCredential({\n scopes,\n authority: state.msalConfig.auth.authority,\n azureRegion: calculateRegionalAuthority(),\n claims: options?.claims,\n });\n ensureValidMsalToken(scopes, response, options);\n\n state.logger.getToken.info(formatSuccess(scopes));\n\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n };\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n async function getTokenByClientAssertion(\n scopes: string[],\n clientAssertion: string,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using client assertion`);\n\n state.msalConfig.auth.clientAssertion = clientAssertion;\n\n const msalApp = await getConfidentialApp(options);\n\n try {\n const response = await msalApp.acquireTokenByClientCredential({\n scopes,\n authority: state.msalConfig.auth.authority,\n azureRegion: calculateRegionalAuthority(),\n claims: options?.claims,\n clientAssertion,\n });\n ensureValidMsalToken(scopes, response, options);\n\n state.logger.getToken.info(formatSuccess(scopes));\n\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n };\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n async function getTokenByClientCertificate(\n scopes: string[],\n certificate: CertificateParts,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using client certificate`);\n\n state.msalConfig.auth.clientCertificate = certificate;\n\n const msalApp = await getConfidentialApp(options);\n try {\n const response = await msalApp.acquireTokenByClientCredential({\n scopes,\n authority: state.msalConfig.auth.authority,\n azureRegion: calculateRegionalAuthority(),\n claims: options?.claims,\n });\n ensureValidMsalToken(scopes, response, options);\n\n state.logger.getToken.info(formatSuccess(scopes));\n\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n };\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n async function getTokenByDeviceCode(\n scopes: string[],\n deviceCodeCallback: DeviceCodePromptCallback,\n options: GetTokenWithSilentAuthOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using device code`);\n\n const msalApp = await getPublicApp(options);\n\n return withSilentAuthentication(msalApp, scopes, options, () => {\n const requestOptions: msal.DeviceCodeRequest = {\n scopes,\n cancel: options?.abortSignal?.aborted ?? false,\n deviceCodeCallback,\n authority: state.msalConfig.auth.authority,\n claims: options?.claims,\n };\n const deviceCodeRequest = msalApp.acquireTokenByDeviceCode(requestOptions);\n if (options.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", () => {\n requestOptions.cancel = true;\n });\n }\n\n return deviceCodeRequest;\n });\n }\n\n async function getTokenByUsernamePassword(\n scopes: string[],\n username: string,\n password: string,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using username and password`);\n\n const msalApp = await getPublicApp(options);\n\n return withSilentAuthentication(msalApp, scopes, options, () => {\n const requestOptions: msal.UsernamePasswordRequest = {\n scopes,\n username,\n password,\n authority: state.msalConfig.auth.authority,\n claims: options?.claims,\n };\n\n return msalApp.acquireTokenByUsernamePassword(requestOptions);\n });\n }\n\n function getActiveAccount(): AuthenticationRecord | undefined {\n if (!state.cachedAccount) {\n return undefined;\n }\n return msalToPublic(clientId, state.cachedAccount);\n }\n\n async function getTokenByAuthorizationCode(\n scopes: string[],\n redirectUri: string,\n authorizationCode: string,\n clientSecret?: string,\n options: GetTokenWithSilentAuthOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using authorization code`);\n\n let msalApp: msal.ConfidentialClientApplication | msal.PublicClientApplication;\n if (clientSecret) {\n // If a client secret is provided, we need to use a confidential client application\n // See https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow#request-an-access-token-with-a-client_secret\n state.msalConfig.auth.clientSecret = clientSecret;\n msalApp = await getConfidentialApp(options);\n } else {\n msalApp = await getPublicApp(options);\n }\n\n return withSilentAuthentication(msalApp, scopes, options, () => {\n return msalApp.acquireTokenByCode({\n scopes,\n redirectUri,\n code: authorizationCode,\n authority: state.msalConfig.auth.authority,\n claims: options?.claims,\n });\n });\n }\n\n return {\n getActiveAccount,\n getTokenByClientSecret,\n getTokenByClientAssertion,\n getTokenByClientCertificate,\n getTokenByDeviceCode,\n getTokenByUsernamePassword,\n getTokenByAuthorizationCode,\n };\n}\n"]}
|
package/package.json
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"name": "@azure/identity",
|
3
3
|
"sdk-type": "client",
|
4
|
-
"version": "4.3.
|
4
|
+
"version": "4.3.1-alpha.20240618.4",
|
5
5
|
"description": "Provides credential implementations for Azure SDK libraries that can authenticate with Microsoft Entra ID",
|
6
6
|
"main": "dist/index.js",
|
7
7
|
"module": "dist-esm/src/index.js",
|
@@ -125,8 +125,8 @@
|
|
125
125
|
},
|
126
126
|
"devDependencies": {
|
127
127
|
"@azure-tools/test-recorder": "^3.0.0",
|
128
|
-
"@azure/dev-tool": "
|
129
|
-
"@azure/eslint-plugin-azure-sdk": "
|
128
|
+
"@azure/dev-tool": ">=1.0.0-alpha <1.0.0-alphb",
|
129
|
+
"@azure/eslint-plugin-azure-sdk": ">=3.0.0-alpha <3.0.0-alphb",
|
130
130
|
"@azure/keyvault-keys": "^4.2.0",
|
131
131
|
"@azure-tools/test-utils": "^1.0.1",
|
132
132
|
"@microsoft/api-extractor": "^7.31.1",
|