@azure/identity 2.1.0-alpha.20220311.2 → 2.1.0-alpha.20220321.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of @azure/identity might be problematic. Click here for more details.
- package/CHANGELOG.md +4 -0
- package/README.md +2 -2
- package/dist/index.js +46 -5
- package/dist/index.js.map +1 -1
- package/dist-esm/src/client/identityClient.js +37 -1
- package/dist-esm/src/client/identityClient.js.map +1 -1
- package/dist-esm/src/msal/browserFlows/msalBrowserCommon.js +1 -1
- package/dist-esm/src/msal/browserFlows/msalBrowserCommon.js.map +1 -1
- package/dist-esm/src/msal/flows.js.map +1 -1
- package/dist-esm/src/msal/nodeFlows/msalNodeCommon.js +4 -3
- package/dist-esm/src/msal/nodeFlows/msalNodeCommon.js.map +1 -1
- package/dist-esm/src/msal/utils.js +5 -1
- package/dist-esm/src/msal/utils.js.map +1 -1
- package/dist-esm/src/tokenCredentialOptions.js.map +1 -1
- package/package.json +1 -1
- package/types/identity.d.ts +11 -0
|
@@ -33,7 +33,7 @@ export function getIdentityClientAuthorityHost(options) {
|
|
|
33
33
|
*/
|
|
34
34
|
export class IdentityClient extends ServiceClient {
|
|
35
35
|
constructor(options) {
|
|
36
|
-
var _a;
|
|
36
|
+
var _a, _b;
|
|
37
37
|
const packageDetails = `azsdk-js-identity/2.1.0-beta.2`;
|
|
38
38
|
const userAgentPrefix = ((_a = options === null || options === void 0 ? void 0 : options.userAgentOptions) === null || _a === void 0 ? void 0 : _a.userAgentPrefix)
|
|
39
39
|
? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
|
|
@@ -49,6 +49,7 @@ export class IdentityClient extends ServiceClient {
|
|
|
49
49
|
}, baseUri }));
|
|
50
50
|
this.authorityHost = baseUri;
|
|
51
51
|
this.abortControllers = new Map();
|
|
52
|
+
this.allowLoggingAccountIdentifiers = (_b = options === null || options === void 0 ? void 0 : options.loggingOptions) === null || _b === void 0 ? void 0 : _b.allowLoggingAccountIdentifiers;
|
|
52
53
|
}
|
|
53
54
|
async sendTokenRequest(request, expiresOnParser) {
|
|
54
55
|
logger.info(`IdentityClient: sending token request to [${request.url}]`);
|
|
@@ -63,6 +64,7 @@ export class IdentityClient extends ServiceClient {
|
|
|
63
64
|
if (!parsedBody.access_token) {
|
|
64
65
|
return null;
|
|
65
66
|
}
|
|
67
|
+
this.logIdentifiers(response);
|
|
66
68
|
const token = {
|
|
67
69
|
accessToken: {
|
|
68
70
|
token: parsedBody.access_token,
|
|
@@ -184,6 +186,7 @@ export class IdentityClient extends ServiceClient {
|
|
|
184
186
|
abortSignal: this.generateAbortSignal(noCorrelationId),
|
|
185
187
|
});
|
|
186
188
|
const response = await this.sendRequest(request);
|
|
189
|
+
this.logIdentifiers(response);
|
|
187
190
|
return {
|
|
188
191
|
body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,
|
|
189
192
|
headers: response.headers.toJSON(),
|
|
@@ -200,11 +203,44 @@ export class IdentityClient extends ServiceClient {
|
|
|
200
203
|
abortSignal: this.generateAbortSignal(this.getCorrelationId(options)),
|
|
201
204
|
});
|
|
202
205
|
const response = await this.sendRequest(request);
|
|
206
|
+
this.logIdentifiers(response);
|
|
203
207
|
return {
|
|
204
208
|
body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,
|
|
205
209
|
headers: response.headers.toJSON(),
|
|
206
210
|
status: response.status,
|
|
207
211
|
};
|
|
208
212
|
}
|
|
213
|
+
/**
|
|
214
|
+
* If allowLoggingAccountIdentifiers was set on the constructor options
|
|
215
|
+
* we try to log the account identifiers by parsing the received access token.
|
|
216
|
+
*
|
|
217
|
+
* The account identifiers we try to log are:
|
|
218
|
+
* - `appid`: The application or Client Identifier.
|
|
219
|
+
* - `upn`: User Principal Name.
|
|
220
|
+
* - It might not be available in some authentication scenarios.
|
|
221
|
+
* - If it's not available, we put a placeholder: "No User Principal Name available".
|
|
222
|
+
* - `tid`: Tenant Identifier.
|
|
223
|
+
* - `oid`: Object Identifier of the authenticated user.
|
|
224
|
+
*/
|
|
225
|
+
logIdentifiers(response) {
|
|
226
|
+
if (!this.allowLoggingAccountIdentifiers || !response.bodyAsText) {
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const unavailableUpn = "No User Principal Name available";
|
|
230
|
+
try {
|
|
231
|
+
const parsed = response.parsedBody || JSON.parse(response.bodyAsText);
|
|
232
|
+
const accessToken = parsed.access_token;
|
|
233
|
+
if (!accessToken) {
|
|
234
|
+
// Without an access token allowLoggingAccountIdentifiers isn't useful.
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
const base64Metadata = accessToken.split(".")[1];
|
|
238
|
+
const { appid, upn, tid, oid } = JSON.parse(Buffer.from(base64Metadata, "base64").toString("utf8"));
|
|
239
|
+
logger.info(`[Authenticated account] Client ID: ${appid}. Tenant ID: ${tid}. User Principal Name: ${upn || unavailableUpn}. Object ID (user): ${oid}`);
|
|
240
|
+
}
|
|
241
|
+
catch (e) {
|
|
242
|
+
logger.warning("allowLoggingAccountIdentifiers was set, but we couldn't log the account information. Error:", e.message);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
209
245
|
}
|
|
210
246
|
//# sourceMappingURL=identityClient.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"identityClient.js","sourceRoot":"","sources":["../../../src/client/identityClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EACL,iBAAiB,EACjB,qBAAqB,GAEtB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,eAAe,EAAmB,MAAM,yBAAyB,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,uBAAuB,EAAE,MAAM,WAA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OAAO,CAAC,CAAC;QACjD,OAAO;YACL,IAAI,EAAE,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS;YACvE,OAAO,EAAE,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE;YAClC,MAAM,EAAE,QAAQ,CAAC,MAAM;SACxB,CAAC;IACJ,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { INetworkModule, NetworkRequestOptions, NetworkResponse } from \"@azure/msal-common\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { SpanStatusCode } from \"@azure/core-tracing\";\nimport { ServiceClient } from \"@azure/core-client\";\nimport { isNode } from \"@azure/core-util\";\nimport {\n createHttpHeaders,\n createPipelineRequest,\n PipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { AbortController, AbortSignalLike } from \"@azure/abort-controller\";\nimport { AuthenticationError, AuthenticationErrorName } from \"../errors\";\nimport { getIdentityTokenEndpointSuffix } from \"../util/identityTokenEndpoint\";\nimport { DefaultAuthorityHost } from \"../constants\";\nimport { createSpan } from \"../util/tracing\";\nimport { logger } from \"../util/logging\";\nimport { TokenCredentialOptions } from \"../tokenCredentialOptions\";\n\nconst noCorrelationId = \"noCorrelationId\";\n\n/**\n * An internal type used to communicate details of a token request's\n * response that should not be sent back as part of the access token.\n */\nexport interface TokenResponse {\n /**\n * The AccessToken to be returned from getToken.\n */\n accessToken: AccessToken;\n\n /**\n * The refresh token if the 'offline_access' scope was used.\n */\n refreshToken?: string;\n}\n\n/**\n * Internal type roughly matching the raw responses of the authentication endpoints.\n *\n * @internal\n */\nexport interface TokenResponseParsedBody {\n token?: string;\n access_token?: string;\n refresh_token?: string;\n expires_in: number;\n expires_on?: number | string;\n}\n\n/**\n * @internal\n */\nexport function getIdentityClientAuthorityHost(options?: TokenCredentialOptions): string {\n // The authorityHost can come from options or from the AZURE_AUTHORITY_HOST environment variable.\n let authorityHost = options?.authorityHost;\n\n // The AZURE_AUTHORITY_HOST environment variable can only be provided in Node.js.\n if (isNode) {\n authorityHost = authorityHost ?? process.env.AZURE_AUTHORITY_HOST;\n }\n\n // If the authorityHost is not provided, we use the default one from the public cloud: https://login.microsoftonline.com\n return authorityHost ?? DefaultAuthorityHost;\n}\n\n/**\n * The network module used by the Identity credentials.\n *\n * It allows for credentials to abort any pending request independently of the MSAL flow,\n * by calling to the `abortRequests()` method.\n *\n */\nexport class IdentityClient extends ServiceClient implements INetworkModule {\n public authorityHost: string;\n private abortControllers: Map<string, AbortController[] | undefined>;\n\n constructor(options?: TokenCredentialOptions) {\n const packageDetails = `azsdk-js-identity/2.1.0-beta.2`;\n const userAgentPrefix = options?.userAgentOptions?.userAgentPrefix\n ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`\n : `${packageDetails}`;\n\n const baseUri = getIdentityClientAuthorityHost(options);\n if (!baseUri.startsWith(\"https:\")) {\n throw new Error(\"The authorityHost address must use the 'https' protocol.\");\n }\n\n super({\n requestContentType: \"application/json; charset=utf-8\",\n retryOptions: {\n maxRetries: 3,\n },\n ...options,\n userAgentOptions: {\n userAgentPrefix,\n },\n baseUri,\n });\n\n this.authorityHost = baseUri;\n this.abortControllers = new Map();\n }\n\n async sendTokenRequest(\n request: PipelineRequest,\n expiresOnParser?: (responseBody: TokenResponseParsedBody) => number\n ): Promise<TokenResponse | null> {\n logger.info(`IdentityClient: sending token request to [${request.url}]`);\n const response = await this.sendRequest(request);\n\n expiresOnParser =\n expiresOnParser ||\n ((responseBody: TokenResponseParsedBody) => {\n return Date.now() + responseBody.expires_in * 1000;\n });\n\n if (response.bodyAsText && (response.status === 200 || response.status === 201)) {\n const parsedBody: TokenResponseParsedBody = JSON.parse(response.bodyAsText);\n\n if (!parsedBody.access_token) {\n return null;\n }\n\n const token = {\n accessToken: {\n token: parsedBody.access_token,\n expiresOnTimestamp: expiresOnParser(parsedBody),\n },\n refreshToken: parsedBody.refresh_token,\n };\n\n logger.info(\n `IdentityClient: [${request.url}] token acquired, expires on ${token.accessToken.expiresOnTimestamp}`\n );\n return token;\n } else {\n const error = new AuthenticationError(response.status, response.bodyAsText);\n logger.warning(\n `IdentityClient: authentication error. HTTP status: ${response.status}, ${error.errorResponse.errorDescription}`\n );\n throw error;\n }\n }\n\n async refreshAccessToken(\n tenantId: string,\n clientId: string,\n scopes: string,\n refreshToken: string | undefined,\n clientSecret: string | undefined,\n expiresOnParser?: (responseBody: TokenResponseParsedBody) => number,\n options?: GetTokenOptions\n ): Promise<TokenResponse | null> {\n if (refreshToken === undefined) {\n return null;\n }\n logger.info(\n `IdentityClient: refreshing access token with client ID: ${clientId}, scopes: ${scopes} started`\n );\n\n const { span, updatedOptions } = createSpan(\"IdentityClient-refreshAccessToken\", options);\n\n const refreshParams = {\n grant_type: \"refresh_token\",\n client_id: clientId,\n refresh_token: refreshToken,\n scope: scopes,\n };\n\n if (clientSecret !== undefined) {\n (refreshParams as any).client_secret = clientSecret;\n }\n\n const query = new URLSearchParams(refreshParams);\n\n try {\n const urlSuffix = getIdentityTokenEndpointSuffix(tenantId);\n const request = createPipelineRequest({\n url: `${this.authorityHost}/${tenantId}/${urlSuffix}`,\n method: \"POST\",\n body: query.toString(),\n abortSignal: options && options.abortSignal,\n headers: createHttpHeaders({\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n }),\n tracingOptions: updatedOptions?.tracingOptions,\n });\n\n const response = await this.sendTokenRequest(request, expiresOnParser);\n logger.info(`IdentityClient: refreshed token for client ID: ${clientId}`);\n return response;\n } catch (err) {\n if (\n err.name === AuthenticationErrorName &&\n err.errorResponse.error === \"interaction_required\"\n ) {\n // It's likely that the refresh token has expired, so\n // return null so that the credential implementation will\n // initiate the authentication flow again.\n logger.info(`IdentityClient: interaction required for client ID: ${clientId}`);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message,\n });\n\n return null;\n } else {\n logger.warning(\n `IdentityClient: failed refreshing token for client ID: ${clientId}: ${err}`\n );\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message,\n });\n throw err;\n }\n } finally {\n span.end();\n }\n }\n\n // Here is a custom layer that allows us to abort requests that go through MSAL,\n // since MSAL doesn't allow us to pass options all the way through.\n\n generateAbortSignal(correlationId: string): AbortSignalLike {\n const controller = new AbortController();\n const controllers = this.abortControllers.get(correlationId) || [];\n controllers.push(controller);\n this.abortControllers.set(correlationId, controllers);\n const existingOnAbort = controller.signal.onabort;\n controller.signal.onabort = (...params) => {\n this.abortControllers.set(correlationId, undefined);\n if (existingOnAbort) {\n existingOnAbort(...params);\n }\n };\n return controller.signal;\n }\n\n abortRequests(correlationId?: string): void {\n const key = correlationId || noCorrelationId;\n const controllers = [\n ...(this.abortControllers.get(key) || []),\n // MSAL passes no correlation ID to the get requests...\n ...(this.abortControllers.get(noCorrelationId) || []),\n ];\n if (!controllers.length) {\n return;\n }\n for (const controller of controllers) {\n controller.abort();\n }\n this.abortControllers.set(key, undefined);\n }\n\n getCorrelationId(options?: NetworkRequestOptions): string {\n const parameter = options?.body\n ?.split(\"&\")\n .map((part) => part.split(\"=\"))\n .find(([key]) => key === \"client-request-id\");\n return parameter && parameter.length ? parameter[1] || noCorrelationId : noCorrelationId;\n }\n\n // The MSAL network module methods follow\n\n async sendGetRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions\n ): Promise<NetworkResponse<T>> {\n const request = createPipelineRequest({\n url,\n method: \"GET\",\n body: options?.body,\n headers: createHttpHeaders(options?.headers),\n abortSignal: this.generateAbortSignal(noCorrelationId),\n });\n\n const response = await this.sendRequest(request);\n return {\n body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,\n headers: response.headers.toJSON(),\n status: response.status,\n };\n }\n\n async sendPostRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions\n ): Promise<NetworkResponse<T>> {\n const request = createPipelineRequest({\n url,\n method: \"POST\",\n body: options?.body,\n headers: createHttpHeaders(options?.headers),\n // MSAL doesn't send the correlation ID on the get requests.\n abortSignal: this.generateAbortSignal(this.getCorrelationId(options)),\n });\n\n const response = await this.sendRequest(request);\n return {\n body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,\n headers: response.headers.toJSON(),\n status: response.status,\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"identityClient.js","sourceRoot":"","sources":["../../../src/client/identityClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EACL,iBAAiB,EACjB,qBAAqB,GAGtB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,eAAe,EAAmB,MAAM,yBAAyB,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,uBAAuB,EAAE,MAAM,WAAW,CAAC;AACzE,OAAO,EAAE,8BAA8B,EAAE,MAAM,+BAA+B,CAAC;AAC/E,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAGzC,MAAM,eAAe,GAAG,iBAAiB,CAAC;AA+B1C;;GAEG;AACH,MAAM,UAAU,8BAA8B,CAAC,OAAgC;IAC7E,iGAAiG;IACjG,IAAI,aAAa,GAAG,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,aAAa,CAAC;IAE3C,iFAAiF;IACjF,IAAI,MAAM,EAAE;QACV,aAAa,GAAG,aAAa,aAAb,aAAa,cAAb,aAAa,GAAI,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC;KACnE;IAED,wHAAwH;IACxH,OAAO,aAAa,aAAb,aAA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B;QAC/C,IAAI,CAAC,IAAI,CAAC,8BAA8B,IAAI,CAAC,QAAQ,CAAC,UAAU,EAAE;YAChE,OAAO;SACR;QACD,MAAM,cAAc,GAAG,kCAAkC,CAAC;QAC1D,IAAI;YACF,MAAM,MAAM,GAAI,QAAgB,CAAC,UAAU,IAAI,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;YAC/E,MAAM,WAAW,GAAG,MAAM,CAAC,YAAY,CAAC;YACxC,IAAI,CAAC,WAAW,EAAE;gBAChB,uEAAuE;gBACvE,OAAO;aACR;YACD,MAAM,cAAc,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YACjD,MAAM,EAAE,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,KAAK,CACzC,MAAM,CAAC,IAAI,CAAC,cAAc,EAAE,QAAQ,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CACvD,CAAC;YAEF,MAAM,CAAC,IAAI,CACT,sCAAsC,KAAK,gBAAgB,GAAG,0BAC5D,GAAG,IAAI,cACT,uBAAuB,GAAG,EAAE,CAC7B,CAAC;SACH;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,CAAC,OAAO,CACZ,6FAA6F,EAC7F,CAAC,CAAC,OAAO,CACV,CAAC;SACH;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { INetworkModule, NetworkRequestOptions, NetworkResponse } from \"@azure/msal-common\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { SpanStatusCode } from \"@azure/core-tracing\";\nimport { ServiceClient } from \"@azure/core-client\";\nimport { isNode } from \"@azure/core-util\";\nimport {\n createHttpHeaders,\n createPipelineRequest,\n PipelineRequest,\n PipelineResponse,\n} from \"@azure/core-rest-pipeline\";\nimport { AbortController, AbortSignalLike } from \"@azure/abort-controller\";\nimport { AuthenticationError, AuthenticationErrorName } from \"../errors\";\nimport { getIdentityTokenEndpointSuffix } from \"../util/identityTokenEndpoint\";\nimport { DefaultAuthorityHost } from \"../constants\";\nimport { createSpan } from \"../util/tracing\";\nimport { logger } from \"../util/logging\";\nimport { TokenCredentialOptions } from \"../tokenCredentialOptions\";\n\nconst noCorrelationId = \"noCorrelationId\";\n\n/**\n * An internal type used to communicate details of a token request's\n * response that should not be sent back as part of the access token.\n */\nexport interface TokenResponse {\n /**\n * The AccessToken to be returned from getToken.\n */\n accessToken: AccessToken;\n\n /**\n * The refresh token if the 'offline_access' scope was used.\n */\n refreshToken?: string;\n}\n\n/**\n * Internal type roughly matching the raw responses of the authentication endpoints.\n *\n * @internal\n */\nexport interface TokenResponseParsedBody {\n token?: string;\n access_token?: string;\n refresh_token?: string;\n expires_in: number;\n expires_on?: number | string;\n}\n\n/**\n * @internal\n */\nexport function getIdentityClientAuthorityHost(options?: TokenCredentialOptions): string {\n // The authorityHost can come from options or from the AZURE_AUTHORITY_HOST environment variable.\n let authorityHost = options?.authorityHost;\n\n // The AZURE_AUTHORITY_HOST environment variable can only be provided in Node.js.\n if (isNode) {\n authorityHost = authorityHost ?? process.env.AZURE_AUTHORITY_HOST;\n }\n\n // If the authorityHost is not provided, we use the default one from the public cloud: https://login.microsoftonline.com\n return authorityHost ?? DefaultAuthorityHost;\n}\n\n/**\n * The network module used by the Identity credentials.\n *\n * It allows for credentials to abort any pending request independently of the MSAL flow,\n * by calling to the `abortRequests()` method.\n *\n */\nexport class IdentityClient extends ServiceClient implements INetworkModule {\n public authorityHost: string;\n private allowLoggingAccountIdentifiers?: boolean;\n private abortControllers: Map<string, AbortController[] | undefined>;\n\n constructor(options?: TokenCredentialOptions) {\n const packageDetails = `azsdk-js-identity/2.1.0-beta.2`;\n const userAgentPrefix = options?.userAgentOptions?.userAgentPrefix\n ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`\n : `${packageDetails}`;\n\n const baseUri = getIdentityClientAuthorityHost(options);\n if (!baseUri.startsWith(\"https:\")) {\n throw new Error(\"The authorityHost address must use the 'https' protocol.\");\n }\n\n super({\n requestContentType: \"application/json; charset=utf-8\",\n retryOptions: {\n maxRetries: 3,\n },\n ...options,\n userAgentOptions: {\n userAgentPrefix,\n },\n baseUri,\n });\n\n this.authorityHost = baseUri;\n this.abortControllers = new Map();\n this.allowLoggingAccountIdentifiers = options?.loggingOptions?.allowLoggingAccountIdentifiers;\n }\n\n async sendTokenRequest(\n request: PipelineRequest,\n expiresOnParser?: (responseBody: TokenResponseParsedBody) => number\n ): Promise<TokenResponse | null> {\n logger.info(`IdentityClient: sending token request to [${request.url}]`);\n const response = await this.sendRequest(request);\n\n expiresOnParser =\n expiresOnParser ||\n ((responseBody: TokenResponseParsedBody) => {\n return Date.now() + responseBody.expires_in * 1000;\n });\n\n if (response.bodyAsText && (response.status === 200 || response.status === 201)) {\n const parsedBody: TokenResponseParsedBody = JSON.parse(response.bodyAsText);\n\n if (!parsedBody.access_token) {\n return null;\n }\n\n this.logIdentifiers(response);\n\n const token = {\n accessToken: {\n token: parsedBody.access_token,\n expiresOnTimestamp: expiresOnParser(parsedBody),\n },\n refreshToken: parsedBody.refresh_token,\n };\n\n logger.info(\n `IdentityClient: [${request.url}] token acquired, expires on ${token.accessToken.expiresOnTimestamp}`\n );\n return token;\n } else {\n const error = new AuthenticationError(response.status, response.bodyAsText);\n logger.warning(\n `IdentityClient: authentication error. HTTP status: ${response.status}, ${error.errorResponse.errorDescription}`\n );\n throw error;\n }\n }\n\n async refreshAccessToken(\n tenantId: string,\n clientId: string,\n scopes: string,\n refreshToken: string | undefined,\n clientSecret: string | undefined,\n expiresOnParser?: (responseBody: TokenResponseParsedBody) => number,\n options?: GetTokenOptions\n ): Promise<TokenResponse | null> {\n if (refreshToken === undefined) {\n return null;\n }\n logger.info(\n `IdentityClient: refreshing access token with client ID: ${clientId}, scopes: ${scopes} started`\n );\n\n const { span, updatedOptions } = createSpan(\"IdentityClient-refreshAccessToken\", options);\n\n const refreshParams = {\n grant_type: \"refresh_token\",\n client_id: clientId,\n refresh_token: refreshToken,\n scope: scopes,\n };\n\n if (clientSecret !== undefined) {\n (refreshParams as any).client_secret = clientSecret;\n }\n\n const query = new URLSearchParams(refreshParams);\n\n try {\n const urlSuffix = getIdentityTokenEndpointSuffix(tenantId);\n const request = createPipelineRequest({\n url: `${this.authorityHost}/${tenantId}/${urlSuffix}`,\n method: \"POST\",\n body: query.toString(),\n abortSignal: options && options.abortSignal,\n headers: createHttpHeaders({\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n }),\n tracingOptions: updatedOptions?.tracingOptions,\n });\n\n const response = await this.sendTokenRequest(request, expiresOnParser);\n logger.info(`IdentityClient: refreshed token for client ID: ${clientId}`);\n return response;\n } catch (err) {\n if (\n err.name === AuthenticationErrorName &&\n err.errorResponse.error === \"interaction_required\"\n ) {\n // It's likely that the refresh token has expired, so\n // return null so that the credential implementation will\n // initiate the authentication flow again.\n logger.info(`IdentityClient: interaction required for client ID: ${clientId}`);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message,\n });\n\n return null;\n } else {\n logger.warning(\n `IdentityClient: failed refreshing token for client ID: ${clientId}: ${err}`\n );\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message,\n });\n throw err;\n }\n } finally {\n span.end();\n }\n }\n\n // Here is a custom layer that allows us to abort requests that go through MSAL,\n // since MSAL doesn't allow us to pass options all the way through.\n\n generateAbortSignal(correlationId: string): AbortSignalLike {\n const controller = new AbortController();\n const controllers = this.abortControllers.get(correlationId) || [];\n controllers.push(controller);\n this.abortControllers.set(correlationId, controllers);\n const existingOnAbort = controller.signal.onabort;\n controller.signal.onabort = (...params) => {\n this.abortControllers.set(correlationId, undefined);\n if (existingOnAbort) {\n existingOnAbort(...params);\n }\n };\n return controller.signal;\n }\n\n abortRequests(correlationId?: string): void {\n const key = correlationId || noCorrelationId;\n const controllers = [\n ...(this.abortControllers.get(key) || []),\n // MSAL passes no correlation ID to the get requests...\n ...(this.abortControllers.get(noCorrelationId) || []),\n ];\n if (!controllers.length) {\n return;\n }\n for (const controller of controllers) {\n controller.abort();\n }\n this.abortControllers.set(key, undefined);\n }\n\n getCorrelationId(options?: NetworkRequestOptions): string {\n const parameter = options?.body\n ?.split(\"&\")\n .map((part) => part.split(\"=\"))\n .find(([key]) => key === \"client-request-id\");\n return parameter && parameter.length ? parameter[1] || noCorrelationId : noCorrelationId;\n }\n\n // The MSAL network module methods follow\n\n async sendGetRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions\n ): Promise<NetworkResponse<T>> {\n const request = createPipelineRequest({\n url,\n method: \"GET\",\n body: options?.body,\n headers: createHttpHeaders(options?.headers),\n abortSignal: this.generateAbortSignal(noCorrelationId),\n });\n\n const response = await this.sendRequest(request);\n\n this.logIdentifiers(response);\n\n return {\n body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,\n headers: response.headers.toJSON(),\n status: response.status,\n };\n }\n\n async sendPostRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions\n ): Promise<NetworkResponse<T>> {\n const request = createPipelineRequest({\n url,\n method: \"POST\",\n body: options?.body,\n headers: createHttpHeaders(options?.headers),\n // MSAL doesn't send the correlation ID on the get requests.\n abortSignal: this.generateAbortSignal(this.getCorrelationId(options)),\n });\n\n const response = await this.sendRequest(request);\n\n this.logIdentifiers(response);\n\n return {\n body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,\n headers: response.headers.toJSON(),\n status: response.status,\n };\n }\n\n /**\n * If allowLoggingAccountIdentifiers was set on the constructor options\n * we try to log the account identifiers by parsing the received access token.\n *\n * The account identifiers we try to log are:\n * - `appid`: The application or Client Identifier.\n * - `upn`: User Principal Name.\n * - It might not be available in some authentication scenarios.\n * - If it's not available, we put a placeholder: \"No User Principal Name available\".\n * - `tid`: Tenant Identifier.\n * - `oid`: Object Identifier of the authenticated user.\n */\n private logIdentifiers(response: PipelineResponse): void {\n if (!this.allowLoggingAccountIdentifiers || !response.bodyAsText) {\n return;\n }\n const unavailableUpn = \"No User Principal Name available\";\n try {\n const parsed = (response as any).parsedBody || JSON.parse(response.bodyAsText);\n const accessToken = parsed.access_token;\n if (!accessToken) {\n // Without an access token allowLoggingAccountIdentifiers isn't useful.\n return;\n }\n const base64Metadata = accessToken.split(\".\")[1];\n const { appid, upn, tid, oid } = JSON.parse(\n Buffer.from(base64Metadata, \"base64\").toString(\"utf8\")\n );\n\n logger.info(\n `[Authenticated account] Client ID: ${appid}. Tenant ID: ${tid}. User Principal Name: ${\n upn || unavailableUpn\n }. Object ID (user): ${oid}`\n );\n } catch (e) {\n logger.warning(\n \"allowLoggingAccountIdentifiers was set, but we couldn't log the account information. Error:\",\n e.message\n );\n }\n }\n}\n"]}
|
|
@@ -16,7 +16,7 @@ export function defaultBrowserMsalConfig(options) {
|
|
|
16
16
|
auth: {
|
|
17
17
|
clientId: options.clientId,
|
|
18
18
|
authority,
|
|
19
|
-
knownAuthorities: getKnownAuthorities(tenantId, authority),
|
|
19
|
+
knownAuthorities: getKnownAuthorities(tenantId, authority, options.disableAuthorityValidation),
|
|
20
20
|
// If the users picked redirect as their login style,
|
|
21
21
|
// but they didn't provide a redirectUri,
|
|
22
22
|
// we can try to use the current page we're in as a default value.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"msalBrowserCommon.js","sourceRoot":"","sources":["../../../../src/msal/browserFlows/msalBrowserCommon.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAE3E,OAAO,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AACvF,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,iBAAiB,E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CAAC,OAAO,CAAC,SAAS,EAAE;YACtB,OAAO,CAAC,SAAS,GAAG,YAAY,CAAC,QAAQ,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC;SAChE;QAED,uDAAuD;QACvD,MAAM,IAAI,CAAC,cAAc,EAAE,CAAC;QAE5B,IAAI,CAAC,CAAC,MAAM,IAAI,CAAC,gBAAgB,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,8BAA8B,EAAE;YAC5E,MAAM,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;SAC1B;QACD,OAAO,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;YAC/C,IAAI,GAAG,CAAC,IAAI,KAAK,6BAA6B,EAAE;gBAC9C,MAAM,GAAG,CAAC;aACX;YACD,IAAI,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,8BAA8B,EAAE;gBAC3C,MAAM,IAAI,2BAA2B,CAAC;oBACpC,MAAM;oBACN,eAAe,EAAE,OAAO;oBACxB,OAAO,EACL,uFAAuF;iBAC1F,CAAC,CAAC;aACJ;YACD,IAAI,CAAC,MAAM,CAAC,IAAI,CACd,oEAAoE,IAAI,CAAC,UAAU,EAAE,CACtF,CAAC;YACF,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACjC,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalBrowser from \"@azure/msal-browser\";\nimport { AccessToken } from \"@azure/core-auth\";\n\nimport { DefaultTenantId } from \"../../constants\";\nimport { resolveTenantId } from \"../../util/resolveTenantId\";\nimport { processMultiTenantRequest } from \"../../util/validateMultiTenant\";\nimport { BrowserLoginStyle } from \"../../credentials/interactiveBrowserCredentialOptions\";\nimport { AuthenticationRequiredError, CredentialUnavailableError } from \"../../errors\";\nimport { getAuthority, getKnownAuthorities, MsalBaseUtilities } from \"../utils\";\nimport { MsalFlow, MsalFlowOptions } from \"../flows\";\nimport { AuthenticationRecord } from \"../types\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\n\n/**\n * Union of the constructor parameters that all MSAL flow types take.\n * Some properties might not be used by some flow types.\n */\nexport interface MsalBrowserFlowOptions extends MsalFlowOptions {\n redirectUri?: string;\n loginStyle: BrowserLoginStyle;\n loginHint?: string;\n}\n\n/**\n * The common methods we use to work with the MSAL browser flows.\n * @internal\n */\nexport interface MsalBrowserFlow extends MsalFlow {\n login(scopes?: string[]): Promise<AuthenticationRecord | undefined>;\n handleRedirect(): Promise<AuthenticationRecord | undefined>;\n}\n\n/**\n * Generates a MSAL configuration that generally works for browsers\n * @internal\n */\nexport function defaultBrowserMsalConfig(\n options: MsalBrowserFlowOptions\n): msalBrowser.Configuration {\n const tenantId = options.tenantId || DefaultTenantId;\n const authority = getAuthority(tenantId, options.authorityHost);\n return {\n auth: {\n clientId: options.clientId!,\n authority,\n knownAuthorities: getKnownAuthorities(\n tenantId,\n authority,\n options.disableAuthorityValidation\n ),\n // If the users picked redirect as their login style,\n // but they didn't provide a redirectUri,\n // we can try to use the current page we're in as a default value.\n redirectUri: options.redirectUri || self.location.origin,\n },\n };\n}\n\n/**\n * MSAL partial base client for the browsers.\n *\n * It completes the input configuration with some default values.\n * It also provides with utility protected methods that can be used from any of the clients,\n * which includes handlers for successful responses and errors.\n *\n * @internal\n */\nexport abstract class MsalBrowser extends MsalBaseUtilities implements MsalBrowserFlow {\n protected loginStyle: BrowserLoginStyle;\n protected clientId: string;\n protected tenantId: string;\n protected authorityHost?: string;\n protected account: AuthenticationRecord | undefined;\n protected msalConfig: msalBrowser.Configuration;\n protected disableAutomaticAuthentication?: boolean;\n protected app?: msalBrowser.PublicClientApplication;\n\n constructor(options: MsalBrowserFlowOptions) {\n super(options);\n this.logger = options.logger;\n this.loginStyle = options.loginStyle;\n if (!options.clientId) {\n throw new CredentialUnavailableError(\"A client ID is required in browsers\");\n }\n this.clientId = options.clientId;\n this.tenantId = resolveTenantId(this.logger, options.tenantId, options.clientId);\n this.authorityHost = options.authorityHost;\n this.msalConfig = defaultBrowserMsalConfig(options);\n this.disableAutomaticAuthentication = options.disableAutomaticAuthentication;\n\n if (options.authenticationRecord) {\n this.account = {\n ...options.authenticationRecord,\n tenantId: this.tenantId,\n };\n }\n }\n\n /**\n * In the browsers we don't need to init()\n */\n async init(): Promise<void> {\n // Nothing to do here.\n }\n\n /**\n * Attempts to handle a redirection request the least amount of times possible.\n */\n public abstract handleRedirect(): Promise<AuthenticationRecord | undefined>;\n\n /**\n * Clears MSAL's cache.\n */\n async logout(): Promise<void> {\n this.app?.logout();\n }\n\n /**\n * Uses MSAL to retrieve the active account.\n */\n public abstract getActiveAccount(): Promise<AuthenticationRecord | undefined>;\n\n /**\n * Uses MSAL to trigger a redirect or a popup login.\n */\n public abstract login(scopes?: string | string[]): Promise<AuthenticationRecord | undefined>;\n\n /**\n * Attempts to retrieve a token from cache.\n */\n public abstract getTokenSilent(scopes: string[]): Promise<AccessToken>;\n\n /**\n * Attempts to retrieve the token in the browser.\n */\n protected abstract doGetToken(scopes: string[]): Promise<AccessToken>;\n\n /**\n * Attempts to retrieve an authenticated token from MSAL.\n */\n public async getToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {}\n ): Promise<AccessToken> {\n const tenantId = processMultiTenantRequest(this.tenantId, options) || this.tenantId;\n\n if (!options.authority) {\n options.authority = getAuthority(tenantId, this.authorityHost);\n }\n\n // We ensure that redirection is handled at this point.\n await this.handleRedirect();\n\n if (!(await this.getActiveAccount()) && !this.disableAutomaticAuthentication) {\n await this.login(scopes);\n }\n return this.getTokenSilent(scopes).catch((err) => {\n if (err.name !== \"AuthenticationRequiredError\") {\n throw err;\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 this.logger.info(\n `Silent authentication failed, falling back to interactive method ${this.loginStyle}`\n );\n return this.doGetToken(scopes);\n });\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flows.js","sourceRoot":"","sources":["../../../src/msal/flows.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken } from \"@azure/core-auth\";\n\nimport { CredentialLogger } from \"../util/logging\";\nimport { AuthenticationRecord } from \"./types\";\nimport { CredentialFlowGetTokenOptions } from \"./credentials\";\n\n/**\n * Union of the constructor parameters that all MSAL flow types take.\n * @internal\n */\nexport interface MsalFlowOptions {\n logger: CredentialLogger;\n clientId?: string;\n tenantId?: string;\n authorityHost?: string;\n authenticationRecord?: AuthenticationRecord;\n disableAutomaticAuthentication?: boolean;\n}\n\n/**\n * The common methods we use to work with the MSAL flows.\n * @internal\n */\nexport interface MsalFlow {\n /**\n * Allows for any setup before any request is processed.\n */\n init(options?: CredentialFlowGetTokenOptions): Promise<void>;\n /**\n * Tries to load the active account, either from memory or from MSAL.\n */\n getActiveAccount(): Promise<AuthenticationRecord | undefined>;\n /**\n * Tries to retrieve the token silently using MSAL.\n */\n getTokenSilent(scopes?: string[], options?: CredentialFlowGetTokenOptions): Promise<AccessToken>;\n /**\n * Calls to the implementation's doGetToken method.\n */\n getToken(scopes?: string[], options?: CredentialFlowGetTokenOptions): Promise<AccessToken>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"flows.js","sourceRoot":"","sources":["../../../src/msal/flows.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken } from \"@azure/core-auth\";\n\nimport { CredentialLogger } from \"../util/logging\";\nimport { AuthenticationRecord } from \"./types\";\nimport { CredentialFlowGetTokenOptions } from \"./credentials\";\n\n/**\n * Union of the constructor parameters that all MSAL flow types take.\n * @internal\n */\nexport interface MsalFlowOptions {\n logger: CredentialLogger;\n clientId?: string;\n tenantId?: string;\n authorityHost?: string;\n authenticationRecord?: AuthenticationRecord;\n disableAutomaticAuthentication?: boolean;\n disableAuthorityValidation?: boolean;\n}\n\n/**\n * The common methods we use to work with the MSAL flows.\n * @internal\n */\nexport interface MsalFlow {\n /**\n * Allows for any setup before any request is processed.\n */\n init(options?: CredentialFlowGetTokenOptions): Promise<void>;\n /**\n * Tries to load the active account, either from memory or from MSAL.\n */\n getActiveAccount(): Promise<AuthenticationRecord | undefined>;\n /**\n * Tries to retrieve the token silently using MSAL.\n */\n getTokenSilent(scopes?: string[], options?: CredentialFlowGetTokenOptions): Promise<AccessToken>;\n /**\n * Calls to the implementation's doGetToken method.\n */\n getToken(scopes?: string[], options?: CredentialFlowGetTokenOptions): Promise<AccessToken>;\n}\n"]}
|
|
@@ -64,17 +64,17 @@ export class MsalNode extends MsalBaseUtilities {
|
|
|
64
64
|
const tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);
|
|
65
65
|
this.authorityHost = options.authorityHost || process.env.AZURE_AUTHORITY_HOST;
|
|
66
66
|
const authority = getAuthority(tenantId, this.authorityHost);
|
|
67
|
-
this.identityClient = new IdentityClient(Object.assign(Object.assign({}, options.tokenCredentialOptions), { authorityHost: authority }));
|
|
67
|
+
this.identityClient = new IdentityClient(Object.assign(Object.assign({}, options.tokenCredentialOptions), { authorityHost: authority, loggingOptions: options.loggingOptions }));
|
|
68
68
|
let clientCapabilities = ["cp1"];
|
|
69
69
|
if (process.env.AZURE_IDENTITY_DISABLE_CP1) {
|
|
70
70
|
clientCapabilities = [];
|
|
71
71
|
}
|
|
72
|
-
|
|
72
|
+
const configuration = {
|
|
73
73
|
auth: {
|
|
74
74
|
clientId,
|
|
75
75
|
authority,
|
|
76
|
-
knownAuthorities: getKnownAuthorities(tenantId, authority),
|
|
77
76
|
clientCapabilities,
|
|
77
|
+
knownAuthorities: getKnownAuthorities(tenantId, authority, options.disableAuthorityValidation),
|
|
78
78
|
},
|
|
79
79
|
// Cache is defined in this.prepare();
|
|
80
80
|
system: {
|
|
@@ -84,6 +84,7 @@ export class MsalNode extends MsalBaseUtilities {
|
|
|
84
84
|
},
|
|
85
85
|
},
|
|
86
86
|
};
|
|
87
|
+
return configuration;
|
|
87
88
|
}
|
|
88
89
|
/**
|
|
89
90
|
* Prepares the MSAL applications.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"msalNodeCommon.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalNodeCommon.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,QAAQ,MAAM,kBAAkB,CAAC;AAK7C,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAE7D,OAAO,EAAE,uBAAuB,EAAE,MAAM,iBAAiB,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAI3D,OAAO,EACL,qBAAqB,EACrB,YAAY,EACZ,mBAAmB,EACnB,iBAAiB,EACjB,YAAY,EACZ,YAAY,GACb,MAAM,UAAU,CAAC;AAElB,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAiB5D;;;GAGG;AACH,IAAI,mBAAmB,GAEP,SAAS,CAAC;AAE1B;;;GAGG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG;IACtC,cAAc,CAAC,cAA8D;QAC3E,mBAAmB,GAAG,cAAc,CAAC;IACvC,CAAC;CACF,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,OAAgB,QAAS,SAAQ,iBAAiB;IAmBtD,YAAY,OAAwB;;QAClC,KAAK,CAAC,OAAO,CAAC,CAAC;QAZP,yBAAoB,GAAY,KAAK,CAAC;QAa9C,IAAI,CAA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,IAAI,2BAA2B,CAAC;oBACpC,MAAM;oBACN,eAAe,EAAE,OAAO;oBACxB,OAAO,EACL,uFAAuF;iBAC1F,CAAC,CAAC;aACJ;YACD,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,mEAAmE,CAAC,CAAC;YACtF,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;SACzC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalNode from \"@azure/msal-node\";\nimport * as msalCommon from \"@azure/msal-common\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\n\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { DeveloperSignOnClientId } from \"../../constants\";\nimport { resolveTenantId } from \"../../util/resolveTenantId\";\nimport { AuthenticationRequiredError } from \"../../errors\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { MsalFlow, MsalFlowOptions } from \"../flows\";\nimport { AuthenticationRecord } from \"../types\";\nimport {\n defaultLoggerCallback,\n getAuthority,\n getKnownAuthorities,\n MsalBaseUtilities,\n msalToPublic,\n publicToMsal,\n} from \"../utils\";\nimport { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions\";\nimport { processMultiTenantRequest } from \"../../util/validateMultiTenant\";\nimport { RegionalAuthority } from \"../../regionalAuthority\";\n\n/**\n * Union of the constructor parameters that all MSAL flow types for Node.\n * @internal\n */\nexport interface MsalNodeOptions extends MsalFlowOptions {\n tokenCachePersistenceOptions?: TokenCachePersistenceOptions;\n tokenCredentialOptions: TokenCredentialOptions;\n /**\n * Specifies a regional authority. Please refer to the {@link RegionalAuthority} type for the accepted values.\n * If {@link RegionalAuthority.AutoDiscoverRegion} is specified, we will try to discover the regional authority endpoint.\n * If the property is not specified, uses a non-regional authority endpoint.\n */\n regionalAuthority?: string;\n}\n\n/**\n * The current persistence provider, undefined by default.\n * @internal\n */\nlet persistenceProvider:\n | ((options?: TokenCachePersistenceOptions) => Promise<msalCommon.ICachePlugin>)\n | undefined = undefined;\n\n/**\n * An object that allows setting the persistence provider.\n * @internal\n */\nexport const msalNodeFlowCacheControl = {\n setPersistence(pluginProvider: Exclude<typeof persistenceProvider, undefined>): void {\n persistenceProvider = pluginProvider;\n },\n};\n\n/**\n * MSAL partial base client for Node.js.\n *\n * It completes the input configuration with some default values.\n * It also provides with utility protected methods that can be used from any of the clients,\n * which includes handlers for successful responses and errors.\n *\n * @internal\n */\nexport abstract class MsalNode extends MsalBaseUtilities implements MsalFlow {\n protected publicApp: msalNode.PublicClientApplication | undefined;\n protected confidentialApp: msalNode.ConfidentialClientApplication | undefined;\n protected msalConfig: msalNode.Configuration;\n protected clientId: string;\n protected tenantId: string;\n protected authorityHost?: string;\n protected identityClient?: IdentityClient;\n protected requiresConfidential: boolean = false;\n protected azureRegion?: string;\n protected createCachePlugin: (() => Promise<msalCommon.ICachePlugin>) | undefined;\n\n /**\n * MSAL currently caches the tokens depending on the claims used to retrieve them.\n * In cases like CAE, in which we use claims to update the tokens, trying to retrieve the token without the claims will yield the original token.\n * To ensure we always get the latest token, we have to keep track of the claims.\n */\n private cachedClaims: string | undefined;\n\n constructor(options: MsalNodeOptions) {\n super(options);\n this.msalConfig = this.defaultNodeMsalConfig(options);\n this.tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);\n this.clientId = this.msalConfig.auth.clientId;\n\n // If persistence has been configured\n if (persistenceProvider !== undefined && options.tokenCachePersistenceOptions?.enabled) {\n this.createCachePlugin = () => persistenceProvider!(options.tokenCachePersistenceOptions);\n } else if (options.tokenCachePersistenceOptions?.enabled) {\n throw new Error(\n [\n \"Persistent token caching was requested, but no persistence provider was configured.\",\n \"You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)\",\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n \"`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`.\",\n ].join(\" \")\n );\n }\n\n this.azureRegion = options.regionalAuthority ?? process.env.AZURE_REGIONAL_AUTHORITY_NAME;\n if (this.azureRegion === RegionalAuthority.AutoDiscoverRegion) {\n this.azureRegion = \"AUTO_DISCOVER\";\n }\n }\n\n /**\n * Generates a MSAL configuration that generally works for Node.js\n */\n protected defaultNodeMsalConfig(options: MsalNodeOptions): msalNode.Configuration {\n const clientId = options.clientId || DeveloperSignOnClientId;\n const tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);\n\n this.authorityHost = options.authorityHost || process.env.AZURE_AUTHORITY_HOST;\n const authority = getAuthority(tenantId, this.authorityHost);\n\n this.identityClient = new IdentityClient({\n ...options.tokenCredentialOptions,\n authorityHost: authority,\n });\n\n let clientCapabilities: string[] = [\"cp1\"];\n if (process.env.AZURE_IDENTITY_DISABLE_CP1) {\n clientCapabilities = [];\n }\n\n return {\n auth: {\n clientId,\n authority,\n knownAuthorities: getKnownAuthorities(tenantId, authority),\n clientCapabilities,\n },\n // Cache is defined in this.prepare();\n system: {\n networkClient: this.identityClient,\n loggerOptions: {\n loggerCallback: defaultLoggerCallback(options.logger),\n },\n },\n };\n }\n\n /**\n * Prepares the MSAL applications.\n */\n async init(options?: CredentialFlowGetTokenOptions): Promise<void> {\n if (options?.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", () => {\n // This will abort any pending request in the IdentityClient,\n // based on the received or generated correlationId\n this.identityClient!.abortRequests(options.correlationId);\n });\n }\n\n if (this.publicApp || this.confidentialApp) {\n return;\n }\n\n if (this.createCachePlugin !== undefined) {\n this.msalConfig.cache = {\n cachePlugin: await this.createCachePlugin(),\n };\n }\n\n this.publicApp = new msalNode.PublicClientApplication(this.msalConfig);\n // The confidential client requires either a secret, assertion or certificate.\n if (\n this.msalConfig.auth.clientSecret ||\n this.msalConfig.auth.clientAssertion ||\n this.msalConfig.auth.clientCertificate\n ) {\n this.confidentialApp = new msalNode.ConfidentialClientApplication(this.msalConfig);\n } else {\n if (this.requiresConfidential) {\n throw new Error(\n \"Unable to generate the MSAL confidential client. Missing either the client's secret, certificate or assertion.\"\n );\n }\n }\n }\n\n /**\n * Allows the cancellation of a MSAL request.\n */\n protected withCancellation(\n promise: Promise<msalCommon.AuthenticationResult | null>,\n abortSignal?: AbortSignalLike,\n onCancel?: () => void\n ): Promise<msalCommon.AuthenticationResult | null> {\n return new Promise((resolve, reject) => {\n promise\n .then((msalToken) => {\n return resolve(msalToken!);\n })\n .catch(reject);\n if (abortSignal) {\n abortSignal.addEventListener(\"abort\", () => {\n onCancel?.();\n });\n }\n });\n }\n\n /**\n * Returns the existing account, attempts to load the account from MSAL.\n */\n async getActiveAccount(): Promise<AuthenticationRecord | undefined> {\n if (this.account) {\n return this.account;\n }\n const cache = this.confidentialApp?.getTokenCache() ?? this.publicApp?.getTokenCache();\n const accountsByTenant = await cache?.getAllAccounts();\n\n if (!accountsByTenant) {\n return;\n }\n\n if (accountsByTenant.length === 1) {\n this.account = msalToPublic(this.clientId, accountsByTenant[0]);\n } else {\n this.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 return;\n }\n\n return this.account;\n }\n\n /**\n * Attempts to retrieve a token from cache.\n */\n async getTokenSilent(\n scopes: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<AccessToken> {\n await this.getActiveAccount();\n if (!this.account) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Silent authentication failed. We couldn't retrieve an active account from the cache.\",\n });\n }\n\n const silentRequest: msalNode.SilentFlowRequest = {\n // To be able to re-use the account, the Token Cache must also have been provided.\n account: publicToMsal(this.account),\n correlationId: options?.correlationId,\n scopes,\n authority: options?.authority,\n claims: options?.claims,\n };\n\n try {\n this.logger.info(\"Attempting to acquire token silently\");\n const response =\n (await this.confidentialApp?.acquireTokenSilent(silentRequest)) ??\n (await this.publicApp!.acquireTokenSilent(silentRequest));\n return this.handleResult(scopes, this.clientId, response || undefined);\n } catch (err) {\n throw this.handleError(scopes, err, options);\n }\n }\n\n /**\n * Attempts to retrieve an authenticated token from MSAL.\n */\n protected abstract doGetToken(scopes: string[], options?: GetTokenOptions): Promise<AccessToken>;\n\n /**\n * Wrapper around each MSAL flow get token operation: doGetToken.\n * If disableAutomaticAuthentication is sent through the constructor, it will prevent MSAL from requesting the user input.\n */\n public async getToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {}\n ): Promise<AccessToken> {\n const tenantId = processMultiTenantRequest(this.tenantId, options) || this.tenantId;\n\n options.authority = getAuthority(tenantId, this.authorityHost);\n\n options.correlationId = options?.correlationId || this.generateUuid();\n await this.init(options);\n\n try {\n // MSAL now caches tokens based on their claims,\n // so now one has to keep track fo claims in order to retrieve the newer tokens from acquireTokenSilent\n // This update happened on PR: https://github.com/AzureAD/microsoft-authentication-library-for-js/pull/4533\n const optionsClaims = (options as any).claims;\n if (optionsClaims) {\n this.cachedClaims = optionsClaims;\n }\n if (this.cachedClaims && !optionsClaims) {\n (options as any).claims = this.cachedClaims;\n }\n // We don't return the promise since we want to catch errors right here.\n return await this.getTokenSilent(scopes, options);\n } catch (err) {\n if (err.name !== \"AuthenticationRequiredError\") {\n throw err;\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 this.logger.info(`Silent authentication failed, falling back to interactive method.`);\n return this.doGetToken(scopes, options);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"msalNodeCommon.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalNodeCommon.ts"],"names":[],"mappings":"AAAA,uCA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microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalNode from \"@azure/msal-node\";\nimport * as msalCommon from \"@azure/msal-common\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { LogPolicyOptions } from \"@azure/core-rest-pipeline\";\n\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { DeveloperSignOnClientId } from \"../../constants\";\nimport { resolveTenantId } from \"../../util/resolveTenantId\";\nimport { AuthenticationRequiredError } from \"../../errors\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { MsalFlow, MsalFlowOptions } from \"../flows\";\nimport { AuthenticationRecord } from \"../types\";\nimport {\n defaultLoggerCallback,\n getAuthority,\n getKnownAuthorities,\n MsalBaseUtilities,\n msalToPublic,\n publicToMsal,\n} from \"../utils\";\nimport { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions\";\nimport { processMultiTenantRequest } from \"../../util/validateMultiTenant\";\nimport { RegionalAuthority } from \"../../regionalAuthority\";\n\n/**\n * Union of the constructor parameters that all MSAL flow types for Node.\n * @internal\n */\nexport interface MsalNodeOptions extends MsalFlowOptions {\n tokenCachePersistenceOptions?: TokenCachePersistenceOptions;\n tokenCredentialOptions: TokenCredentialOptions;\n /**\n * Specifies a regional authority. Please refer to the {@link RegionalAuthority} type for the accepted values.\n * If {@link RegionalAuthority.AutoDiscoverRegion} is specified, we will try to discover the regional authority endpoint.\n * If the property is not specified, uses a non-regional authority endpoint.\n */\n regionalAuthority?: string;\n /**\n * Allows logging account information once the authentication flow succeeds.\n */\n loggingOptions?: LogPolicyOptions & {\n allowLoggingAccountIdentifiers?: boolean;\n };\n}\n\n/**\n * The current persistence provider, undefined by default.\n * @internal\n */\nlet persistenceProvider:\n | ((options?: TokenCachePersistenceOptions) => Promise<msalCommon.ICachePlugin>)\n | undefined = undefined;\n\n/**\n * An object that allows setting the persistence provider.\n * @internal\n */\nexport const msalNodeFlowCacheControl = {\n setPersistence(pluginProvider: Exclude<typeof persistenceProvider, undefined>): void {\n persistenceProvider = pluginProvider;\n },\n};\n\n/**\n * MSAL partial base client for Node.js.\n *\n * It completes the input configuration with some default values.\n * It also provides with utility protected methods that can be used from any of the clients,\n * which includes handlers for successful responses and errors.\n *\n * @internal\n */\nexport abstract class MsalNode extends MsalBaseUtilities implements MsalFlow {\n protected publicApp: msalNode.PublicClientApplication | undefined;\n protected confidentialApp: msalNode.ConfidentialClientApplication | undefined;\n protected msalConfig: msalNode.Configuration;\n protected clientId: string;\n protected tenantId: string;\n protected authorityHost?: string;\n protected identityClient?: IdentityClient;\n protected requiresConfidential: boolean = false;\n protected azureRegion?: string;\n protected createCachePlugin: (() => Promise<msalCommon.ICachePlugin>) | undefined;\n\n /**\n * MSAL currently caches the tokens depending on the claims used to retrieve them.\n * In cases like CAE, in which we use claims to update the tokens, trying to retrieve the token without the claims will yield the original token.\n * To ensure we always get the latest token, we have to keep track of the claims.\n */\n private cachedClaims: string | undefined;\n\n constructor(options: MsalNodeOptions) {\n super(options);\n this.msalConfig = this.defaultNodeMsalConfig(options);\n this.tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);\n this.clientId = this.msalConfig.auth.clientId;\n\n // If persistence has been configured\n if (persistenceProvider !== undefined && options.tokenCachePersistenceOptions?.enabled) {\n this.createCachePlugin = () => persistenceProvider!(options.tokenCachePersistenceOptions);\n } else if (options.tokenCachePersistenceOptions?.enabled) {\n throw new Error(\n [\n \"Persistent token caching was requested, but no persistence provider was configured.\",\n \"You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)\",\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n \"`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`.\",\n ].join(\" \")\n );\n }\n\n this.azureRegion = options.regionalAuthority ?? process.env.AZURE_REGIONAL_AUTHORITY_NAME;\n if (this.azureRegion === RegionalAuthority.AutoDiscoverRegion) {\n this.azureRegion = \"AUTO_DISCOVER\";\n }\n }\n\n /**\n * Generates a MSAL configuration that generally works for Node.js\n */\n protected defaultNodeMsalConfig(options: MsalNodeOptions): msalNode.Configuration {\n const clientId = options.clientId || DeveloperSignOnClientId;\n const tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);\n\n this.authorityHost = options.authorityHost || process.env.AZURE_AUTHORITY_HOST;\n const authority = getAuthority(tenantId, this.authorityHost);\n\n this.identityClient = new IdentityClient({\n ...options.tokenCredentialOptions,\n authorityHost: authority,\n loggingOptions: options.loggingOptions,\n });\n\n let clientCapabilities: string[] = [\"cp1\"];\n if (process.env.AZURE_IDENTITY_DISABLE_CP1) {\n clientCapabilities = [];\n }\n\n const configuration: msalNode.Configuration = {\n auth: {\n clientId,\n authority,\n clientCapabilities,\n knownAuthorities: getKnownAuthorities(\n tenantId,\n authority,\n options.disableAuthorityValidation\n ),\n },\n // Cache is defined in this.prepare();\n system: {\n networkClient: this.identityClient,\n loggerOptions: {\n loggerCallback: defaultLoggerCallback(options.logger),\n },\n },\n };\n\n return configuration;\n }\n\n /**\n * Prepares the MSAL applications.\n */\n async init(options?: CredentialFlowGetTokenOptions): Promise<void> {\n if (options?.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", () => {\n // This will abort any pending request in the IdentityClient,\n // based on the received or generated correlationId\n this.identityClient!.abortRequests(options.correlationId);\n });\n }\n\n if (this.publicApp || this.confidentialApp) {\n return;\n }\n\n if (this.createCachePlugin !== undefined) {\n this.msalConfig.cache = {\n cachePlugin: await this.createCachePlugin(),\n };\n }\n\n this.publicApp = new msalNode.PublicClientApplication(this.msalConfig);\n // The confidential client requires either a secret, assertion or certificate.\n if (\n this.msalConfig.auth.clientSecret ||\n this.msalConfig.auth.clientAssertion ||\n this.msalConfig.auth.clientCertificate\n ) {\n this.confidentialApp = new msalNode.ConfidentialClientApplication(this.msalConfig);\n } else {\n if (this.requiresConfidential) {\n throw new Error(\n \"Unable to generate the MSAL confidential client. Missing either the client's secret, certificate or assertion.\"\n );\n }\n }\n }\n\n /**\n * Allows the cancellation of a MSAL request.\n */\n protected withCancellation(\n promise: Promise<msalCommon.AuthenticationResult | null>,\n abortSignal?: AbortSignalLike,\n onCancel?: () => void\n ): Promise<msalCommon.AuthenticationResult | null> {\n return new Promise((resolve, reject) => {\n promise\n .then((msalToken) => {\n return resolve(msalToken!);\n })\n .catch(reject);\n if (abortSignal) {\n abortSignal.addEventListener(\"abort\", () => {\n onCancel?.();\n });\n }\n });\n }\n\n /**\n * Returns the existing account, attempts to load the account from MSAL.\n */\n async getActiveAccount(): Promise<AuthenticationRecord | undefined> {\n if (this.account) {\n return this.account;\n }\n const cache = this.confidentialApp?.getTokenCache() ?? this.publicApp?.getTokenCache();\n const accountsByTenant = await cache?.getAllAccounts();\n\n if (!accountsByTenant) {\n return;\n }\n\n if (accountsByTenant.length === 1) {\n this.account = msalToPublic(this.clientId, accountsByTenant[0]);\n } else {\n this.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 return;\n }\n\n return this.account;\n }\n\n /**\n * Attempts to retrieve a token from cache.\n */\n async getTokenSilent(\n scopes: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<AccessToken> {\n await this.getActiveAccount();\n if (!this.account) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Silent authentication failed. We couldn't retrieve an active account from the cache.\",\n });\n }\n\n const silentRequest: msalNode.SilentFlowRequest = {\n // To be able to re-use the account, the Token Cache must also have been provided.\n account: publicToMsal(this.account),\n correlationId: options?.correlationId,\n scopes,\n authority: options?.authority,\n claims: options?.claims,\n };\n\n try {\n this.logger.info(\"Attempting to acquire token silently\");\n const response =\n (await this.confidentialApp?.acquireTokenSilent(silentRequest)) ??\n (await this.publicApp!.acquireTokenSilent(silentRequest));\n return this.handleResult(scopes, this.clientId, response || undefined);\n } catch (err) {\n throw this.handleError(scopes, err, options);\n }\n }\n\n /**\n * Attempts to retrieve an authenticated token from MSAL.\n */\n protected abstract doGetToken(scopes: string[], options?: GetTokenOptions): Promise<AccessToken>;\n\n /**\n * Wrapper around each MSAL flow get token operation: doGetToken.\n * If disableAutomaticAuthentication is sent through the constructor, it will prevent MSAL from requesting the user input.\n */\n public async getToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {}\n ): Promise<AccessToken> {\n const tenantId = processMultiTenantRequest(this.tenantId, options) || this.tenantId;\n\n options.authority = getAuthority(tenantId, this.authorityHost);\n\n options.correlationId = options?.correlationId || this.generateUuid();\n await this.init(options);\n\n try {\n // MSAL now caches tokens based on their claims,\n // so now one has to keep track fo claims in order to retrieve the newer tokens from acquireTokenSilent\n // This update happened on PR: https://github.com/AzureAD/microsoft-authentication-library-for-js/pull/4533\n const optionsClaims = (options as any).claims;\n if (optionsClaims) {\n this.cachedClaims = optionsClaims;\n }\n if (this.cachedClaims && !optionsClaims) {\n (options as any).claims = this.cachedClaims;\n }\n // We don't return the promise since we want to catch errors right here.\n return await this.getTokenSilent(scopes, options);\n } catch (err) {\n if (err.name !== \"AuthenticationRequiredError\") {\n throw err;\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 this.logger.info(`Silent authentication failed, falling back to interactive method.`);\n return this.doGetToken(scopes, options);\n }\n }\n}\n"]}
|
|
@@ -55,12 +55,16 @@ export function getAuthority(tenantId, host) {
|
|
|
55
55
|
}
|
|
56
56
|
/**
|
|
57
57
|
* Generates the known authorities.
|
|
58
|
+
* If `disableAuthorityValidation` is passed, it returns the authority host as a known host, thus disabling the authority validation.
|
|
58
59
|
* If the Tenant Id is `adfs`, the authority can't be validated since the format won't match the expected one.
|
|
59
60
|
* For that reason, we have to force MSAL to disable validating the authority
|
|
60
61
|
* by sending it within the known authorities in the MSAL configuration.
|
|
61
62
|
* @internal
|
|
62
63
|
*/
|
|
63
|
-
export function getKnownAuthorities(tenantId, authorityHost) {
|
|
64
|
+
export function getKnownAuthorities(tenantId, authorityHost, disableAuthorityValidation) {
|
|
65
|
+
if (disableAuthorityValidation) {
|
|
66
|
+
return [authorityHost];
|
|
67
|
+
}
|
|
64
68
|
if (tenantId === "adfs" && authorityHost) {
|
|
65
69
|
return [authorityHost];
|
|
66
70
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/msal/utils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,UAAU,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAE1C,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAErD,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,EAAoB,WAAW,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,EAAE,0BAA0B,EAAE,2BAA2B,EAAE,MAAM,WAAW,CAAC;AACpF,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAIrE;;;GAGG;AACH,MAAM,iCAAiC,GAAG,KAAK,CAAC;AAEhD;;;GAGG;AACH,MAAM,UAAU,oBAAoB,CAClC,MAAyB,EACzB,MAAwB,EACxB,SAAqB,EACrB,eAAiC;IAEjC,MAAM,KAAK,GAAG,CAAC,OAAe,EAAS,EAAE;QACvC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC9B,OAAO,IAAI,2BAA2B,CAAC;YACrC,MAAM,EAAE,KAAK,CAA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CAAC,EAAE,MAAM,EAAE,eAAe,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IAC9F,CAAC;CACF;AAED,qBAAqB;AAErB,MAAM,UAAU,YAAY,CAAC,OAA6B;IACxD,MAAM,CAAC,WAAW,CAAC,GAAG,OAAO,CAAC,SAAS,CAAC,KAAK,CAAC,0BAA0B,CAAC,IAAI,EAAE,CAAC;IAChF,uCACK,OAAO,KACV,cAAc,EAAE,OAAO,CAAC,aAAa,EACrC,WAAW,IACX;AACJ,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,QAAgB,EAAE,OAAwB;IACrE,MAAM,MAAM,GAAG;QACb,SAAS,EAAE,YAAY,CAAC,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,WAAW,CAAC;QAC9D,aAAa,EAAE,OAAO,CAAC,aAAa;QACpC,QAAQ,EAAE,OAAO,CAAC,QAAQ,IAAI,eAAe;QAC7C,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,QAAQ;QACR,OAAO,EAAE,iCAAiC;KAC3C,CAAC;IACF,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,6BAA6B,CAAC,MAA4B;IACxE,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;AAChC,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,+BAA+B,CAAC,gBAAwB;IACtE,MAAM,MAAM,GAAgD,IAAI,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;IAEzF,IAAI,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,OAAO,KAAK,iCAAiC,EAAE;QAC1E,MAAM,KAAK,CAAC,0CAA0C,CAAC,CAAC;KACzD;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalCommon from \"@azure/msal-common\";\nimport { isNode } from \"@azure/core-util\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AbortError } from \"@azure/abort-controller\";\n\nimport { v4 as uuidv4 } from \"uuid\";\nimport { CredentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { CredentialUnavailableError, AuthenticationRequiredError } from \"../errors\";\nimport { DefaultAuthorityHost, DefaultTenantId } from \"../constants\";\nimport { AuthenticationRecord, MsalAccountInfo, MsalResult, MsalToken } from \"./types\";\nimport { MsalFlowOptions } from \"./flows\";\n\n/**\n * Latest AuthenticationRecord version\n * @internal\n */\nconst LatestAuthenticationRecordVersion = \"1.0\";\n\n/**\n * Ensures the validity of the MSAL token\n * @internal\n */\nexport function ensureValidMsalToken(\n scopes: string | string[],\n logger: CredentialLogger,\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions\n): void {\n const error = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message,\n });\n };\n if (!msalToken) {\n throw error(\"No response\");\n }\n if (!msalToken.expiresOn) {\n throw error(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw error(`Response had no \"accessToken\" property.`);\n }\n}\n\n/**\n * Generates a valid authority by combining a host with a tenantId.\n * @internal\n */\nexport function getAuthority(tenantId: string, host?: string): string {\n if (!host) {\n host = DefaultAuthorityHost;\n }\n if (new RegExp(`${tenantId}/?$`).test(host)) {\n return host;\n }\n if (host.endsWith(\"/\")) {\n return host + tenantId;\n } else {\n return `${host}/${tenantId}`;\n }\n}\n\n/**\n * Generates the known authorities.\n * If the Tenant Id is `adfs`, the authority can't be validated since the format won't match the expected one.\n * For that reason, we have to force MSAL to disable validating the authority\n * by sending it within the known authorities in the MSAL configuration.\n * @internal\n */\nexport function getKnownAuthorities(tenantId: string, authorityHost: string): string[] {\n if (tenantId === \"adfs\" && authorityHost) {\n return [authorityHost];\n }\n return [];\n}\n\n/**\n * Generates a logger that can be passed to the MSAL clients.\n * @param logger - The logger of the credential.\n * @internal\n */\nexport const defaultLoggerCallback: (\n logger: CredentialLogger,\n platform?: \"Node\" | \"Browser\"\n) => msalCommon.ILoggerCallback =\n (logger: CredentialLogger, platform: \"Node\" | \"Browser\" = isNode ? \"Node\" : \"Browser\") =>\n (level, message, containsPii): void => {\n if (containsPii) {\n return;\n }\n switch (level) {\n case msalCommon.LogLevel.Error:\n logger.info(`MSAL ${platform} V2 error: ${message}`);\n return;\n case msalCommon.LogLevel.Info:\n logger.info(`MSAL ${platform} V2 info message: ${message}`);\n return;\n case msalCommon.LogLevel.Verbose:\n logger.info(`MSAL ${platform} V2 verbose message: ${message}`);\n return;\n case msalCommon.LogLevel.Warning:\n logger.info(`MSAL ${platform} V2 warning: ${message}`);\n return;\n }\n };\n\n/**\n * The common utility functions for the MSAL clients.\n * Defined as a class so that the classes extending this one can have access to its methods and protected properties.\n *\n * It keeps track of a logger and an in-memory copy of the AuthenticationRecord.\n *\n * @internal\n */\nexport class MsalBaseUtilities {\n protected logger: CredentialLogger;\n protected account: AuthenticationRecord | undefined;\n\n constructor(options: MsalFlowOptions) {\n this.logger = options.logger;\n this.account = options.authenticationRecord;\n }\n\n /**\n * Generates a UUID\n */\n generateUuid(): string {\n return uuidv4();\n }\n\n /**\n * Handles the MSAL authentication result.\n * If the result has an account, we update the local account reference.\n * If the token received is invalid, an error will be thrown depending on what's missing.\n */\n protected handleResult(\n scopes: string | string[],\n clientId: string,\n result?: MsalResult,\n getTokenOptions?: GetTokenOptions\n ): AccessToken {\n if (result?.account) {\n this.account = msalToPublic(clientId, result.account);\n }\n ensureValidMsalToken(scopes, this.logger, result, getTokenOptions);\n this.logger.getToken.info(formatSuccess(scopes));\n return {\n token: result!.accessToken!,\n expiresOnTimestamp: result!.expiresOn!.getTime(),\n };\n }\n\n /**\n * Handles MSAL errors.\n */\n protected handleError(scopes: string[], error: Error, getTokenOptions?: GetTokenOptions): Error {\n if (\n error.name === \"AuthError\" ||\n error.name === \"ClientAuthError\" ||\n error.name === \"BrowserAuthError\"\n ) {\n const msalError = error as msalCommon.AuthError;\n switch (msalError.errorCode) {\n case \"endpoints_resolution_error\":\n this.logger.info(formatError(scopes, error.message));\n return new CredentialUnavailableError(error.message);\n case \"device_code_polling_cancelled\":\n return new AbortError(\"The authentication has been aborted by the caller.\");\n case \"consent_required\":\n case \"interaction_required\":\n case \"login_required\":\n this.logger.info(\n formatError(scopes, `Authentication returned errorCode ${msalError.errorCode}`)\n );\n break;\n default:\n this.logger.info(formatError(scopes, `Failed to acquire token: ${error.message}`));\n break;\n }\n }\n if (\n error.name === \"ClientConfigurationError\" ||\n error.name === \"BrowserConfigurationAuthError\" ||\n error.name === \"AbortError\"\n ) {\n return error;\n }\n return new AuthenticationRequiredError({ scopes, getTokenOptions, message: error.message });\n }\n}\n\n// transformations.ts\n\nexport function publicToMsal(account: AuthenticationRecord): msalCommon.AccountInfo {\n const [environment] = account.authority.match(/([a-z]*\\.[a-z]*\\.[a-z]*)/) || [];\n return {\n ...account,\n localAccountId: account.homeAccountId,\n environment,\n };\n}\n\nexport function msalToPublic(clientId: string, account: MsalAccountInfo): AuthenticationRecord {\n const record = {\n authority: getAuthority(account.tenantId, account.environment),\n homeAccountId: account.homeAccountId,\n tenantId: account.tenantId || DefaultTenantId,\n username: account.username,\n clientId,\n version: LatestAuthenticationRecordVersion,\n };\n return record;\n}\n\n/**\n * Serializes an `AuthenticationRecord` into a string.\n *\n * The output of a serialized authentication record will contain the following properties:\n *\n * - \"authority\"\n * - \"homeAccountId\"\n * - \"clientId\"\n * - \"tenantId\"\n * - \"username\"\n * - \"version\"\n *\n * To later convert this string to a serialized `AuthenticationRecord`, please use the exported function `deserializeAuthenticationRecord()`.\n */\nexport function serializeAuthenticationRecord(record: AuthenticationRecord): string {\n return JSON.stringify(record);\n}\n\n/**\n * Deserializes a previously serialized authentication record from a string into an object.\n *\n * The input string must contain the following properties:\n *\n * - \"authority\"\n * - \"homeAccountId\"\n * - \"clientId\"\n * - \"tenantId\"\n * - \"username\"\n * - \"version\"\n *\n * If the version we receive is unsupported, an error will be thrown.\n *\n * At the moment, the only available version is: \"1.0\", which is always set when the authentication record is serialized.\n *\n * @param serializedRecord - Authentication record previously serialized into string.\n * @returns AuthenticationRecord.\n */\nexport function deserializeAuthenticationRecord(serializedRecord: string): AuthenticationRecord {\n const parsed: AuthenticationRecord & { version?: string } = JSON.parse(serializedRecord);\n\n if (parsed.version && parsed.version !== LatestAuthenticationRecordVersion) {\n throw Error(\"Unsupported AuthenticationRecord version\");\n }\n\n return parsed;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/msal/utils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,UAAU,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAE1C,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAErD,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,EAAoB,WAAW,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,EAAE,0BAA0B,EAAE,2BAA2B,EAAE,MAAM,WAAW,CAAC;AACpF,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAIrE;;;GAGG;AACH,MAAM,iCAAiC,GAAG,KAAK,CAAC;AAEhD;;;GAGG;AACH,MAAM,UAAU,oBAAoB,CAClC,MAAyB,EACzB,MAAwB,EACxB,SAAqB,EACrB,eAAiC;IAEjC,MAAM,KAAK,GAAG,CAAC,OAAe,EAAS,EAAE;QACvC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC9B,OAAO,IAAI,2BAA2B,CAAC;YACrC,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAA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MIT license.\n\nimport * as msalCommon from \"@azure/msal-common\";\nimport { isNode } from \"@azure/core-util\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AbortError } from \"@azure/abort-controller\";\n\nimport { v4 as uuidv4 } from \"uuid\";\nimport { CredentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { CredentialUnavailableError, AuthenticationRequiredError } from \"../errors\";\nimport { DefaultAuthorityHost, DefaultTenantId } from \"../constants\";\nimport { AuthenticationRecord, MsalAccountInfo, MsalResult, MsalToken } from \"./types\";\nimport { MsalFlowOptions } from \"./flows\";\n\n/**\n * Latest AuthenticationRecord version\n * @internal\n */\nconst LatestAuthenticationRecordVersion = \"1.0\";\n\n/**\n * Ensures the validity of the MSAL token\n * @internal\n */\nexport function ensureValidMsalToken(\n scopes: string | string[],\n logger: CredentialLogger,\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions\n): void {\n const error = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message,\n });\n };\n if (!msalToken) {\n throw error(\"No response\");\n }\n if (!msalToken.expiresOn) {\n throw error(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw error(`Response had no \"accessToken\" property.`);\n }\n}\n\n/**\n * Generates a valid authority by combining a host with a tenantId.\n * @internal\n */\nexport function getAuthority(tenantId: string, host?: string): string {\n if (!host) {\n host = DefaultAuthorityHost;\n }\n if (new RegExp(`${tenantId}/?$`).test(host)) {\n return host;\n }\n if (host.endsWith(\"/\")) {\n return host + tenantId;\n } else {\n return `${host}/${tenantId}`;\n }\n}\n\n/**\n * Generates the known authorities.\n * If `disableAuthorityValidation` is passed, it returns the authority host as a known host, thus disabling the authority validation.\n * If the Tenant Id is `adfs`, the authority can't be validated since the format won't match the expected one.\n * For that reason, we have to force MSAL to disable validating the authority\n * by sending it within the known authorities in the MSAL configuration.\n * @internal\n */\nexport function getKnownAuthorities(\n tenantId: string,\n authorityHost: string,\n disableAuthorityValidation?: boolean\n): string[] {\n if (disableAuthorityValidation) {\n return [authorityHost];\n }\n if (tenantId === \"adfs\" && authorityHost) {\n return [authorityHost];\n }\n return [];\n}\n\n/**\n * Generates a logger that can be passed to the MSAL clients.\n * @param logger - The logger of the credential.\n * @internal\n */\nexport const defaultLoggerCallback: (\n logger: CredentialLogger,\n platform?: \"Node\" | \"Browser\"\n) => msalCommon.ILoggerCallback =\n (logger: CredentialLogger, platform: \"Node\" | \"Browser\" = isNode ? \"Node\" : \"Browser\") =>\n (level, message, containsPii): void => {\n if (containsPii) {\n return;\n }\n switch (level) {\n case msalCommon.LogLevel.Error:\n logger.info(`MSAL ${platform} V2 error: ${message}`);\n return;\n case msalCommon.LogLevel.Info:\n logger.info(`MSAL ${platform} V2 info message: ${message}`);\n return;\n case msalCommon.LogLevel.Verbose:\n logger.info(`MSAL ${platform} V2 verbose message: ${message}`);\n return;\n case msalCommon.LogLevel.Warning:\n logger.info(`MSAL ${platform} V2 warning: ${message}`);\n return;\n }\n };\n\n/**\n * The common utility functions for the MSAL clients.\n * Defined as a class so that the classes extending this one can have access to its methods and protected properties.\n *\n * It keeps track of a logger and an in-memory copy of the AuthenticationRecord.\n *\n * @internal\n */\nexport class MsalBaseUtilities {\n protected logger: CredentialLogger;\n protected account: AuthenticationRecord | undefined;\n\n constructor(options: MsalFlowOptions) {\n this.logger = options.logger;\n this.account = options.authenticationRecord;\n }\n\n /**\n * Generates a UUID\n */\n generateUuid(): string {\n return uuidv4();\n }\n\n /**\n * Handles the MSAL authentication result.\n * If the result has an account, we update the local account reference.\n * If the token received is invalid, an error will be thrown depending on what's missing.\n */\n protected handleResult(\n scopes: string | string[],\n clientId: string,\n result?: MsalResult,\n getTokenOptions?: GetTokenOptions\n ): AccessToken {\n if (result?.account) {\n this.account = msalToPublic(clientId, result.account);\n }\n ensureValidMsalToken(scopes, this.logger, result, getTokenOptions);\n this.logger.getToken.info(formatSuccess(scopes));\n return {\n token: result!.accessToken!,\n expiresOnTimestamp: result!.expiresOn!.getTime(),\n };\n }\n\n /**\n * Handles MSAL errors.\n */\n protected handleError(scopes: string[], error: Error, getTokenOptions?: GetTokenOptions): Error {\n if (\n error.name === \"AuthError\" ||\n error.name === \"ClientAuthError\" ||\n error.name === \"BrowserAuthError\"\n ) {\n const msalError = error as msalCommon.AuthError;\n switch (msalError.errorCode) {\n case \"endpoints_resolution_error\":\n this.logger.info(formatError(scopes, error.message));\n return new CredentialUnavailableError(error.message);\n case \"device_code_polling_cancelled\":\n return new AbortError(\"The authentication has been aborted by the caller.\");\n case \"consent_required\":\n case \"interaction_required\":\n case \"login_required\":\n this.logger.info(\n formatError(scopes, `Authentication returned errorCode ${msalError.errorCode}`)\n );\n break;\n default:\n this.logger.info(formatError(scopes, `Failed to acquire token: ${error.message}`));\n break;\n }\n }\n if (\n error.name === \"ClientConfigurationError\" ||\n error.name === \"BrowserConfigurationAuthError\" ||\n error.name === \"AbortError\"\n ) {\n return error;\n }\n return new AuthenticationRequiredError({ scopes, getTokenOptions, message: error.message });\n }\n}\n\n// transformations.ts\n\nexport function publicToMsal(account: AuthenticationRecord): msalCommon.AccountInfo {\n const [environment] = account.authority.match(/([a-z]*\\.[a-z]*\\.[a-z]*)/) || [];\n return {\n ...account,\n localAccountId: account.homeAccountId,\n environment,\n };\n}\n\nexport function msalToPublic(clientId: string, account: MsalAccountInfo): AuthenticationRecord {\n const record = {\n authority: getAuthority(account.tenantId, account.environment),\n homeAccountId: account.homeAccountId,\n tenantId: account.tenantId || DefaultTenantId,\n username: account.username,\n clientId,\n version: LatestAuthenticationRecordVersion,\n };\n return record;\n}\n\n/**\n * Serializes an `AuthenticationRecord` into a string.\n *\n * The output of a serialized authentication record will contain the following properties:\n *\n * - \"authority\"\n * - \"homeAccountId\"\n * - \"clientId\"\n * - \"tenantId\"\n * - \"username\"\n * - \"version\"\n *\n * To later convert this string to a serialized `AuthenticationRecord`, please use the exported function `deserializeAuthenticationRecord()`.\n */\nexport function serializeAuthenticationRecord(record: AuthenticationRecord): string {\n return JSON.stringify(record);\n}\n\n/**\n * Deserializes a previously serialized authentication record from a string into an object.\n *\n * The input string must contain the following properties:\n *\n * - \"authority\"\n * - \"homeAccountId\"\n * - \"clientId\"\n * - \"tenantId\"\n * - \"username\"\n * - \"version\"\n *\n * If the version we receive is unsupported, an error will be thrown.\n *\n * At the moment, the only available version is: \"1.0\", which is always set when the authentication record is serialized.\n *\n * @param serializedRecord - Authentication record previously serialized into string.\n * @returns AuthenticationRecord.\n */\nexport function deserializeAuthenticationRecord(serializedRecord: string): AuthenticationRecord {\n const parsed: AuthenticationRecord & { version?: string } = JSON.parse(serializedRecord);\n\n if (parsed.version && parsed.version !== LatestAuthenticationRecordVersion) {\n throw Error(\"Unsupported AuthenticationRecord version\");\n }\n\n return parsed;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tokenCredentialOptions.js","sourceRoot":"","sources":["../../src/tokenCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { CommonClientOptions } from \"@azure/core-client\";\n\n/**\n * Provides options to configure how the Identity library makes authentication\n * requests to Azure Active Directory.\n */\nexport interface TokenCredentialOptions extends CommonClientOptions {\n /**\n * The authority host to use for authentication requests.\n * Possible values are available through {@link AzureAuthorityHosts}.\n * The default is \"https://login.microsoftonline.com\".\n */\n authorityHost?: string;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tokenCredentialOptions.js","sourceRoot":"","sources":["../../src/tokenCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { CommonClientOptions } from \"@azure/core-client\";\nimport { LogPolicyOptions } from \"@azure/core-rest-pipeline\";\n\n/**\n * Provides options to configure how the Identity library makes authentication\n * requests to Azure Active Directory.\n */\nexport interface TokenCredentialOptions extends CommonClientOptions {\n /**\n * The authority host to use for authentication requests.\n * Possible values are available through {@link AzureAuthorityHosts}.\n * The default is \"https://login.microsoftonline.com\".\n */\n authorityHost?: string;\n /**\n * If set to true, disables the automatic validation of the authority host.\n */\n disableAuthorityValidation?: boolean;\n /**\n * Allows logging account information once the authentication flow succeeds.\n */\n loggingOptions?: LogPolicyOptions & {\n allowLoggingAccountIdentifiers?: boolean;\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": "2.1.0-alpha.
|
|
4
|
+
"version": "2.1.0-alpha.20220321.2",
|
|
5
5
|
"description": "Provides credential implementations for Azure SDK libraries that can authenticate with Azure Active Directory",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"module": "dist-esm/src/index.js",
|
package/types/identity.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { AccessToken } from '@azure/core-auth';
|
|
|
2
2
|
import { AzureLogger } from '@azure/logger';
|
|
3
3
|
import { CommonClientOptions } from '@azure/core-client';
|
|
4
4
|
import { GetTokenOptions } from '@azure/core-auth';
|
|
5
|
+
import { LogPolicyOptions } from '@azure/core-rest-pipeline';
|
|
5
6
|
import { TokenCredential } from '@azure/core-auth';
|
|
6
7
|
|
|
7
8
|
export { AccessToken }
|
|
@@ -1148,6 +1149,16 @@ export declare interface TokenCredentialOptions extends CommonClientOptions {
|
|
|
1148
1149
|
* The default is "https://login.microsoftonline.com".
|
|
1149
1150
|
*/
|
|
1150
1151
|
authorityHost?: string;
|
|
1152
|
+
/**
|
|
1153
|
+
* If set to true, disables the automatic validation of the authority host.
|
|
1154
|
+
*/
|
|
1155
|
+
disableAuthorityValidation?: boolean;
|
|
1156
|
+
/**
|
|
1157
|
+
* Allows logging account information once the authentication flow succeeds.
|
|
1158
|
+
*/
|
|
1159
|
+
loggingOptions?: LogPolicyOptions & {
|
|
1160
|
+
allowLoggingAccountIdentifiers?: boolean;
|
|
1161
|
+
};
|
|
1151
1162
|
}
|
|
1152
1163
|
|
|
1153
1164
|
/**
|