@azure/identity 4.10.1-alpha.20250606.1 → 4.10.1-alpha.20250610.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.
- package/dist/browser/errors.d.ts +1 -1
- package/dist/browser/errors.js.map +1 -1
- package/dist/browser/msal/browserFlows/msalBrowserCommon.d.ts +1 -1
- package/dist/browser/msal/browserFlows/msalBrowserCommon.js +1 -1
- package/dist/browser/msal/browserFlows/msalBrowserCommon.js.map +1 -1
- package/dist/commonjs/credentials/clientCertificateCredential.d.ts +1 -1
- package/dist/commonjs/credentials/clientCertificateCredential.js +1 -1
- package/dist/commonjs/credentials/clientCertificateCredential.js.map +1 -1
- package/dist/commonjs/credentials/managedIdentityCredential/index.d.ts +1 -1
- package/dist/commonjs/credentials/managedIdentityCredential/index.js +1 -1
- package/dist/commonjs/credentials/managedIdentityCredential/index.js.map +1 -1
- package/dist/commonjs/errors.d.ts +1 -1
- package/dist/commonjs/errors.js.map +1 -1
- package/dist/commonjs/msal/browserFlows/msalBrowserCommon.d.ts +1 -1
- package/dist/commonjs/msal/browserFlows/msalBrowserCommon.js +1 -1
- package/dist/commonjs/msal/browserFlows/msalBrowserCommon.js.map +1 -1
- package/dist/esm/credentials/clientCertificateCredential.d.ts +1 -1
- package/dist/esm/credentials/clientCertificateCredential.js +1 -1
- package/dist/esm/credentials/clientCertificateCredential.js.map +1 -1
- package/dist/esm/credentials/managedIdentityCredential/index.d.ts +1 -1
- package/dist/esm/credentials/managedIdentityCredential/index.js +1 -1
- package/dist/esm/credentials/managedIdentityCredential/index.js.map +1 -1
- package/dist/esm/errors.d.ts +1 -1
- package/dist/esm/errors.js.map +1 -1
- package/dist/esm/msal/browserFlows/msalBrowserCommon.d.ts +1 -1
- package/dist/esm/msal/browserFlows/msalBrowserCommon.js +1 -1
- package/dist/esm/msal/browserFlows/msalBrowserCommon.js.map +1 -1
- package/dist/workerd/credentials/clientCertificateCredential.d.ts +1 -1
- package/dist/workerd/credentials/clientCertificateCredential.js +1 -1
- package/dist/workerd/credentials/clientCertificateCredential.js.map +1 -1
- package/dist/workerd/credentials/managedIdentityCredential/index.d.ts +1 -1
- package/dist/workerd/credentials/managedIdentityCredential/index.js +1 -1
- package/dist/workerd/credentials/managedIdentityCredential/index.js.map +1 -1
- package/dist/workerd/errors.d.ts +1 -1
- package/dist/workerd/errors.js.map +1 -1
- package/dist/workerd/msal/browserFlows/msalBrowserCommon.d.ts +1 -1
- package/dist/workerd/msal/browserFlows/msalBrowserCommon.js +1 -1
- package/dist/workerd/msal/browserFlows/msalBrowserCommon.js.map +1 -1
- package/package.json +1 -1
package/dist/browser/errors.d.ts
CHANGED
@@ -2,7 +2,7 @@ import type { GetTokenOptions } from "@azure/core-auth";
|
|
2
2
|
/**
|
3
3
|
* See the official documentation for more details:
|
4
4
|
*
|
5
|
-
* https://learn.microsoft.com/
|
5
|
+
* https://learn.microsoft.com/azure/active-directory/develop/v1-protocols-oauth-code#error-response-1
|
6
6
|
*
|
7
7
|
* NOTE: This documentation is for v1 OAuth support but the same error
|
8
8
|
* response details still apply to v2.
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAyDlC,SAAS,eAAe,CAAC,aAAkB;IACzC,OAAO,CACL,aAAa;QACb,OAAO,aAAa,CAAC,KAAK,KAAK,QAAQ;QACvC,OAAO,aAAa,CAAC,iBAAiB,KAAK,QAAQ,CACpD,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,4BAA4B,CAAC;AAE3E;;;;GAIG;AACH,MAAM,OAAO,0BAA2B,SAAQ,KAAK;IACnD,YAAY,OAAgB,EAAE,OAA6B;QACzD,2JAA2J;QAC3J,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,8BAA8B,CAAC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AC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { GetTokenOptions } from \"@azure/core-auth\";\n\n/**\n * See the official documentation for more details:\n *\n * https://learn.microsoft.com/en-us/azure/active-directory/develop/v1-protocols-oauth-code#error-response-1\n *\n * NOTE: This documentation is for v1 OAuth support but the same error\n * response details still apply to v2.\n */\nexport interface ErrorResponse {\n /**\n * The string identifier for the error.\n */\n error: string;\n\n /**\n * The error's description.\n */\n errorDescription: string;\n\n /**\n * An array of codes pertaining to the error(s) that occurred.\n */\n errorCodes?: number[];\n\n /**\n * The timestamp at which the error occurred.\n */\n timestamp?: string;\n\n /**\n * The trace identifier for this error occurrence.\n */\n traceId?: string;\n\n /**\n * The correlation ID to be used for tracking the source of the error.\n */\n correlationId?: string;\n}\n\n/**\n * Used for internal deserialization of OAuth responses. Public model is ErrorResponse\n * @internal\n */\nexport interface OAuthErrorResponse {\n error: string;\n error_description: string;\n error_codes?: number[];\n timestamp?: string;\n trace_id?: string;\n correlation_id?: string;\n}\n\nfunction isErrorResponse(errorResponse: any): errorResponse is OAuthErrorResponse {\n return (\n errorResponse &&\n typeof errorResponse.error === \"string\" &&\n typeof errorResponse.error_description === \"string\"\n );\n}\n\n/**\n * The Error.name value of an CredentialUnavailable\n */\nexport const CredentialUnavailableErrorName = \"CredentialUnavailableError\";\n\n/**\n * This signifies that the credential that was tried in a chained credential\n * was not available to be used as the credential. Rather than treating this as\n * an error that should halt the chain, it's caught and the chain continues\n */\nexport class CredentialUnavailableError extends Error {\n constructor(message?: string, options?: { cause?: unknown }) {\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n super(message, options);\n this.name = CredentialUnavailableErrorName;\n }\n}\n\n/**\n * The Error.name value of an AuthenticationError\n */\nexport const AuthenticationErrorName = \"AuthenticationError\";\n\n/**\n * Provides details about a failure to authenticate with Azure Active\n * Directory. The `errorResponse` field contains more details about\n * the specific failure.\n */\nexport class AuthenticationError extends Error {\n /**\n * The HTTP status code returned from the authentication request.\n */\n public readonly statusCode: number;\n\n /**\n * The error response details.\n */\n public readonly errorResponse: ErrorResponse;\n\n constructor(\n statusCode: number,\n errorBody: object | string | undefined | null,\n options?: { cause?: unknown },\n ) {\n let errorResponse: ErrorResponse = {\n error: \"unknown\",\n errorDescription: \"An unknown error occurred and no additional details are available.\",\n };\n\n if (isErrorResponse(errorBody)) {\n errorResponse = convertOAuthErrorResponseToErrorResponse(errorBody);\n } else if (typeof errorBody === \"string\") {\n try {\n // Most error responses will contain JSON-formatted error details\n // in the response body\n const oauthErrorResponse: OAuthErrorResponse = JSON.parse(errorBody);\n errorResponse = convertOAuthErrorResponseToErrorResponse(oauthErrorResponse);\n } catch (e: any) {\n if (statusCode === 400) {\n errorResponse = {\n error: \"invalid_request\",\n errorDescription: `The service indicated that the request was invalid.\\n\\n${errorBody}`,\n };\n } else {\n errorResponse = {\n error: \"unknown_error\",\n errorDescription: `An unknown error has occurred. Response body:\\n\\n${errorBody}`,\n };\n }\n }\n } else {\n errorResponse = {\n error: \"unknown_error\",\n errorDescription: \"An unknown error occurred and no additional details are available.\",\n };\n }\n\n super(\n `${errorResponse.error} Status code: ${statusCode}\\nMore details:\\n${errorResponse.errorDescription},`,\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n options,\n );\n this.statusCode = statusCode;\n this.errorResponse = errorResponse;\n\n // Ensure that this type reports the correct name\n this.name = AuthenticationErrorName;\n }\n}\n\n/**\n * The Error.name value of an AggregateAuthenticationError\n */\nexport const AggregateAuthenticationErrorName = \"AggregateAuthenticationError\";\n\n/**\n * Provides an `errors` array containing {@link AuthenticationError} instance\n * for authentication failures from credentials in a {@link ChainedTokenCredential}.\n */\nexport class AggregateAuthenticationError extends Error {\n /**\n * The array of error objects that were thrown while trying to authenticate\n * with the credentials in a {@link ChainedTokenCredential}.\n */\n public errors: any[];\n\n constructor(errors: any[], errorMessage?: string) {\n const errorDetail = errors.join(\"\\n\");\n super(`${errorMessage}\\n${errorDetail}`);\n this.errors = errors;\n\n // Ensure that this type reports the correct name\n this.name = AggregateAuthenticationErrorName;\n }\n}\n\nfunction convertOAuthErrorResponseToErrorResponse(errorBody: OAuthErrorResponse): ErrorResponse {\n return {\n error: errorBody.error,\n errorDescription: errorBody.error_description,\n correlationId: errorBody.correlation_id,\n errorCodes: errorBody.error_codes,\n timestamp: errorBody.timestamp,\n traceId: errorBody.trace_id,\n };\n}\n\n/**\n * Optional parameters to the {@link AuthenticationRequiredError}\n */\nexport interface AuthenticationRequiredErrorOptions {\n /**\n * The list of scopes for which the token will have access.\n */\n scopes: string[];\n /**\n * The options passed to the getToken request.\n */\n getTokenOptions?: GetTokenOptions;\n /**\n * The message of the error.\n */\n message?: string;\n /**\n * The underlying cause, if any, that caused the authentication to fail.\n */\n cause?: unknown;\n}\n\n/**\n * Error used to enforce authentication after trying to retrieve a token silently.\n */\nexport class AuthenticationRequiredError extends Error {\n /**\n * The list of scopes for which the token will have access.\n */\n public scopes: string[];\n /**\n * The options passed to the getToken request.\n */\n public getTokenOptions?: GetTokenOptions;\n\n constructor(\n /**\n * Optional parameters. A message can be specified. The {@link GetTokenOptions} of the request can also be specified to more easily associate the error with the received parameters.\n */\n options: AuthenticationRequiredErrorOptions,\n ) {\n super(\n options.message,\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n options.cause ? { cause: options.cause } : undefined,\n );\n this.scopes = options.scopes;\n this.getTokenOptions = options.getTokenOptions;\n this.name = \"AuthenticationRequiredError\";\n }\n}\n"]}
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAyDlC,SAAS,eAAe,CAAC,aAAkB;IACzC,OAAO,CACL,aAAa;QACb,OAAO,aAAa,CAAC,KAAK,KAAK,QAAQ;QACvC,OAAO,aAAa,CAAC,iB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AO;QACf,2JAA2J;QAC3J,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CACrD,CAAC;QACF,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC7B,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC;QAC/C,IAAI,CAAC,IAAI,GAAG,6BAA6B,CAAC;IAC5C,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { GetTokenOptions } from \"@azure/core-auth\";\n\n/**\n * See the official documentation for more details:\n *\n * https://learn.microsoft.com/azure/active-directory/develop/v1-protocols-oauth-code#error-response-1\n *\n * NOTE: This documentation is for v1 OAuth support but the same error\n * response details still apply to v2.\n */\nexport interface ErrorResponse {\n /**\n * The string identifier for the error.\n */\n error: string;\n\n /**\n * The error's description.\n */\n errorDescription: string;\n\n /**\n * An array of codes pertaining to the error(s) that occurred.\n */\n errorCodes?: number[];\n\n /**\n * The timestamp at which the error occurred.\n */\n timestamp?: string;\n\n /**\n * The trace identifier for this error occurrence.\n */\n traceId?: string;\n\n /**\n * The correlation ID to be used for tracking the source of the error.\n */\n correlationId?: string;\n}\n\n/**\n * Used for internal deserialization of OAuth responses. Public model is ErrorResponse\n * @internal\n */\nexport interface OAuthErrorResponse {\n error: string;\n error_description: string;\n error_codes?: number[];\n timestamp?: string;\n trace_id?: string;\n correlation_id?: string;\n}\n\nfunction isErrorResponse(errorResponse: any): errorResponse is OAuthErrorResponse {\n return (\n errorResponse &&\n typeof errorResponse.error === \"string\" &&\n typeof errorResponse.error_description === \"string\"\n );\n}\n\n/**\n * The Error.name value of an CredentialUnavailable\n */\nexport const CredentialUnavailableErrorName = \"CredentialUnavailableError\";\n\n/**\n * This signifies that the credential that was tried in a chained credential\n * was not available to be used as the credential. Rather than treating this as\n * an error that should halt the chain, it's caught and the chain continues\n */\nexport class CredentialUnavailableError extends Error {\n constructor(message?: string, options?: { cause?: unknown }) {\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n super(message, options);\n this.name = CredentialUnavailableErrorName;\n }\n}\n\n/**\n * The Error.name value of an AuthenticationError\n */\nexport const AuthenticationErrorName = \"AuthenticationError\";\n\n/**\n * Provides details about a failure to authenticate with Azure Active\n * Directory. The `errorResponse` field contains more details about\n * the specific failure.\n */\nexport class AuthenticationError extends Error {\n /**\n * The HTTP status code returned from the authentication request.\n */\n public readonly statusCode: number;\n\n /**\n * The error response details.\n */\n public readonly errorResponse: ErrorResponse;\n\n constructor(\n statusCode: number,\n errorBody: object | string | undefined | null,\n options?: { cause?: unknown },\n ) {\n let errorResponse: ErrorResponse = {\n error: \"unknown\",\n errorDescription: \"An unknown error occurred and no additional details are available.\",\n };\n\n if (isErrorResponse(errorBody)) {\n errorResponse = convertOAuthErrorResponseToErrorResponse(errorBody);\n } else if (typeof errorBody === \"string\") {\n try {\n // Most error responses will contain JSON-formatted error details\n // in the response body\n const oauthErrorResponse: OAuthErrorResponse = JSON.parse(errorBody);\n errorResponse = convertOAuthErrorResponseToErrorResponse(oauthErrorResponse);\n } catch (e: any) {\n if (statusCode === 400) {\n errorResponse = {\n error: \"invalid_request\",\n errorDescription: `The service indicated that the request was invalid.\\n\\n${errorBody}`,\n };\n } else {\n errorResponse = {\n error: \"unknown_error\",\n errorDescription: `An unknown error has occurred. Response body:\\n\\n${errorBody}`,\n };\n }\n }\n } else {\n errorResponse = {\n error: \"unknown_error\",\n errorDescription: \"An unknown error occurred and no additional details are available.\",\n };\n }\n\n super(\n `${errorResponse.error} Status code: ${statusCode}\\nMore details:\\n${errorResponse.errorDescription},`,\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n options,\n );\n this.statusCode = statusCode;\n this.errorResponse = errorResponse;\n\n // Ensure that this type reports the correct name\n this.name = AuthenticationErrorName;\n }\n}\n\n/**\n * The Error.name value of an AggregateAuthenticationError\n */\nexport const AggregateAuthenticationErrorName = \"AggregateAuthenticationError\";\n\n/**\n * Provides an `errors` array containing {@link AuthenticationError} instance\n * for authentication failures from credentials in a {@link ChainedTokenCredential}.\n */\nexport class AggregateAuthenticationError extends Error {\n /**\n * The array of error objects that were thrown while trying to authenticate\n * with the credentials in a {@link ChainedTokenCredential}.\n */\n public errors: any[];\n\n constructor(errors: any[], errorMessage?: string) {\n const errorDetail = errors.join(\"\\n\");\n super(`${errorMessage}\\n${errorDetail}`);\n this.errors = errors;\n\n // Ensure that this type reports the correct name\n this.name = AggregateAuthenticationErrorName;\n }\n}\n\nfunction convertOAuthErrorResponseToErrorResponse(errorBody: OAuthErrorResponse): ErrorResponse {\n return {\n error: errorBody.error,\n errorDescription: errorBody.error_description,\n correlationId: errorBody.correlation_id,\n errorCodes: errorBody.error_codes,\n timestamp: errorBody.timestamp,\n traceId: errorBody.trace_id,\n };\n}\n\n/**\n * Optional parameters to the {@link AuthenticationRequiredError}\n */\nexport interface AuthenticationRequiredErrorOptions {\n /**\n * The list of scopes for which the token will have access.\n */\n scopes: string[];\n /**\n * The options passed to the getToken request.\n */\n getTokenOptions?: GetTokenOptions;\n /**\n * The message of the error.\n */\n message?: string;\n /**\n * The underlying cause, if any, that caused the authentication to fail.\n */\n cause?: unknown;\n}\n\n/**\n * Error used to enforce authentication after trying to retrieve a token silently.\n */\nexport class AuthenticationRequiredError extends Error {\n /**\n * The list of scopes for which the token will have access.\n */\n public scopes: string[];\n /**\n * The options passed to the getToken request.\n */\n public getTokenOptions?: GetTokenOptions;\n\n constructor(\n /**\n * Optional parameters. A message can be specified. The {@link GetTokenOptions} of the request can also be specified to more easily associate the error with the received parameters.\n */\n options: AuthenticationRequiredErrorOptions,\n ) {\n super(\n options.message,\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n options.cause ? { cause: options.cause } : undefined,\n );\n this.scopes = options.scopes;\n this.getTokenOptions = options.getTokenOptions;\n this.name = \"AuthenticationRequiredError\";\n }\n}\n"]}
|
@@ -12,7 +12,7 @@ export interface MsalBrowserClient {
|
|
12
12
|
}
|
13
13
|
/**
|
14
14
|
* Uses MSAL Browser 2.X for browser authentication,
|
15
|
-
* which uses the [Auth Code Flow](https://learn.microsoft.com/
|
15
|
+
* which uses the [Auth Code Flow](https://learn.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow).
|
16
16
|
* @internal
|
17
17
|
*/
|
18
18
|
export declare function createMsalBrowserClient(options: MsalBrowserFlowOptions): MsalBrowserClient;
|
@@ -45,7 +45,7 @@ function generateMsalBrowserConfiguration(options) {
|
|
45
45
|
const redirectHash = isLocationDefined ? self.location.hash : undefined;
|
46
46
|
/**
|
47
47
|
* Uses MSAL Browser 2.X for browser authentication,
|
48
|
-
* which uses the [Auth Code Flow](https://learn.microsoft.com/
|
48
|
+
* which uses the [Auth Code Flow](https://learn.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow).
|
49
49
|
* @internal
|
50
50
|
*/
|
51
51
|
export function createMsalBrowserClient(options) {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"msalBrowserCommon.js","sourceRoot":"","sources":["../../../../src/msal/browserFlows/msalBrowserCommon.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,WAAW,MAAM,qBAAqB,CAAC;AAGnD,OAAO,EACL,qBAAqB,EACrB,oBAAoB,EACpB,YAAY,EACZ,mBAAmB,EACnB,eAAe,EACf,eAAe,EACf,YAAY,EACZ,YAAY,GACb,MAAM,aAAa,CAAC;AAIrB,OAAO,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAE1F,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EACL,yBAAyB,EACz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E,CAAC;gBAC/C,MAAM,GAAG,CAAC;YACZ,CAAC;YACD,IAAI,eAAe,aAAf,eAAe,uBAAf,eAAe,CAAE,8BAA8B,EAAE,CAAC;gBACpD,MAAM,IAAI,2BAA2B,CAAC;oBACpC,MAAM;oBACN,eAAe;oBACf,OAAO,EACL,qFAAqF;iBACxF,CAAC,CAAC;YACL,CAAC;YACD,MAAM,CAAC,IAAI,CAAC,oEAAoE,UAAU,EAAE,CAAC,CAAC;YAC9F,OAAO,mBAAmB,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;QACtD,CAAC;IACH,CAAC;IACD,OAAO;QACL,gBAAgB;QAChB,QAAQ;KACT,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport * as msalBrowser from \"@azure/msal-browser\";\n\nimport type { MsalBrowserFlowOptions } from \"./msalBrowserOptions.js\";\nimport {\n defaultLoggerCallback,\n ensureValidMsalToken,\n getAuthority,\n getKnownAuthorities,\n getMSALLogLevel,\n handleMsalError,\n msalToPublic,\n publicToMsal,\n} from \"../utils.js\";\n\nimport type { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport type { AuthenticationRecord, MsalResult } from \"../types.js\";\nimport { AuthenticationRequiredError, CredentialUnavailableError } from \"../../errors.js\";\nimport type { CredentialFlowGetTokenOptions } from \"../credentials.js\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { formatSuccess } from \"../../util/logging.js\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n resolveTenantId,\n} from \"../../util/tenantIdUtils.js\";\nimport { DefaultTenantId } from \"../../constants.js\";\n\n// We keep a copy of the redirect hash.\n// Check if self and location object is defined.\nconst isLocationDefined = typeof self !== \"undefined\" && self.location !== undefined;\n\n/**\n * Generates a MSAL configuration that generally works for browsers\n * @internal\n */\nfunction generateMsalBrowserConfiguration(\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(tenantId, authority, options.disableInstanceDiscovery),\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 || (isLocationDefined ? self.location.origin : undefined),\n },\n cache: {\n cacheLocation: \"sessionStorage\",\n storeAuthStateInCookie: true, // Set to true to improve the experience on IE11 and Edge.\n },\n system: {\n loggerOptions: {\n loggerCallback: defaultLoggerCallback(options.logger, \"Browser\"),\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: options.loggingOptions?.enableUnsafeSupportLogging,\n },\n },\n };\n}\n\n/**\n * Methods that are used by InteractiveBrowserCredential\n * @internal\n */\nexport interface MsalBrowserClient {\n getActiveAccount(): Promise<AuthenticationRecord | undefined>;\n getToken(scopes: string[], options: CredentialFlowGetTokenOptions): Promise<AccessToken>;\n}\n\n// We keep a copy of the redirect hash.\nconst redirectHash = isLocationDefined ? self.location.hash : undefined;\n\n/**\n * Uses MSAL Browser 2.X for browser authentication,\n * which uses the [Auth Code Flow](https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow).\n * @internal\n */\nexport function createMsalBrowserClient(options: MsalBrowserFlowOptions): MsalBrowserClient {\n const loginStyle = options.loginStyle;\n if (!options.clientId) {\n throw new CredentialUnavailableError(\"A client ID is required in browsers\");\n }\n const clientId = options.clientId;\n const logger = options.logger;\n const tenantId = resolveTenantId(logger, options.tenantId, options.clientId);\n const additionallyAllowedTenantIds: string[] = resolveAdditionallyAllowedTenantIds(\n options?.tokenCredentialOptions?.additionallyAllowedTenants,\n );\n const authorityHost = options.authorityHost;\n const msalConfig = generateMsalBrowserConfiguration(options);\n const disableAutomaticAuthentication = options.disableAutomaticAuthentication;\n const loginHint = options.loginHint;\n\n let account: AuthenticationRecord | undefined;\n if (options.authenticationRecord) {\n account = {\n ...options.authenticationRecord,\n tenantId,\n };\n }\n\n // This variable should only be used through calling `getApp` function\n let app: msalBrowser.IPublicClientApplication;\n /**\n * Return the MSAL account if not set yet\n * @returns MSAL application\n */\n async function getApp(): Promise<msalBrowser.IPublicClientApplication> {\n if (!app) {\n // Prepare the MSAL application\n app = await msalBrowser.PublicClientApplication.createPublicClientApplication(msalConfig);\n\n // setting the account right after the app is created.\n if (account) {\n app.setActiveAccount(publicToMsal(account));\n }\n }\n\n return app;\n }\n\n /**\n * Loads the account based on the result of the authentication.\n * If no result was received, tries to load the account from the cache.\n * @param result - Result object received from MSAL.\n */\n async function handleBrowserResult(\n result?: msalBrowser.AuthenticationResult,\n ): Promise<AuthenticationRecord | undefined> {\n try {\n const msalApp = await getApp();\n if (result && result.account) {\n logger.info(`MSAL Browser V2 authentication successful.`);\n msalApp.setActiveAccount(result.account);\n return msalToPublic(clientId, result.account);\n }\n } catch (e: any) {\n logger.info(`Failed to acquire token through MSAL. ${e.message}`);\n }\n return;\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 function handleResult(\n scopes: string | string[],\n result?: MsalResult,\n getTokenOptions?: GetTokenOptions,\n ): AccessToken {\n if (result?.account) {\n account = msalToPublic(clientId, result.account);\n }\n ensureValidMsalToken(scopes, result, getTokenOptions);\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: result.accessToken,\n expiresOnTimestamp: result.expiresOn.getTime(),\n refreshAfterTimestamp: result.refreshOn?.getTime(),\n tokenType: \"Bearer\",\n };\n }\n\n /**\n * Uses MSAL to handle the redirect.\n */\n async function handleRedirect(): Promise<AuthenticationRecord | undefined> {\n const msalApp = await getApp();\n return handleBrowserResult((await msalApp.handleRedirectPromise(redirectHash)) || undefined);\n }\n\n /**\n * Uses MSAL to retrieve the active account.\n */\n async function getActiveAccount(): Promise<AuthenticationRecord | undefined> {\n const msalApp = await getApp();\n const activeAccount = msalApp.getActiveAccount();\n if (!activeAccount) {\n return;\n }\n return msalToPublic(clientId, activeAccount);\n }\n\n /**\n * Uses MSAL to trigger a redirect or a popup login.\n */\n async function login(scopes: string | string[] = []): Promise<AuthenticationRecord | undefined> {\n const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];\n const loginRequest: msalBrowser.RedirectRequest = {\n scopes: arrayScopes,\n loginHint: loginHint,\n };\n const msalApp = await getApp();\n switch (loginStyle) {\n case \"redirect\": {\n await app.loginRedirect(loginRequest);\n return;\n }\n case \"popup\":\n return handleBrowserResult(await msalApp.loginPopup(loginRequest));\n }\n }\n\n /**\n * Tries to retrieve the token silently using MSAL.\n */\n async function getTokenSilent(\n scopes: string[],\n getTokenOptions?: CredentialFlowGetTokenOptions,\n ): Promise<AccessToken> {\n const activeAccount = await getActiveAccount();\n if (!activeAccount) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions,\n message:\n \"Silent authentication failed. We couldn't retrieve an active account from the cache.\",\n });\n }\n\n const parameters: msalBrowser.SilentRequest = {\n authority: getTokenOptions?.authority || msalConfig.auth.authority!,\n correlationId: getTokenOptions?.correlationId,\n claims: getTokenOptions?.claims,\n account: publicToMsal(activeAccount),\n forceRefresh: false,\n scopes,\n };\n\n try {\n logger.info(\"Attempting to acquire token silently\");\n const msalApp = await getApp();\n const response = await msalApp.acquireTokenSilent(parameters);\n return handleResult(scopes, response);\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n /**\n * Attempts to retrieve the token in the browser through interactive methods.\n */\n async function getTokenInteractive(\n scopes: string[],\n getTokenOptions?: CredentialFlowGetTokenOptions,\n ): Promise<AccessToken> {\n const activeAccount = await getActiveAccount();\n if (!activeAccount) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions,\n message:\n \"Silent authentication failed. We couldn't retrieve an active account from the cache.\",\n });\n }\n\n const parameters: msalBrowser.RedirectRequest = {\n authority: getTokenOptions?.authority || msalConfig.auth.authority!,\n correlationId: getTokenOptions?.correlationId,\n claims: getTokenOptions?.claims,\n account: publicToMsal(activeAccount),\n loginHint: loginHint,\n scopes,\n };\n const msalApp = await getApp();\n switch (loginStyle) {\n case \"redirect\":\n // This will go out of the page.\n // Once the InteractiveBrowserCredential is initialized again,\n // we'll load the MSAL account in the constructor.\n\n await msalApp.acquireTokenRedirect(parameters);\n return { token: \"\", expiresOnTimestamp: 0, tokenType: \"Bearer\" };\n case \"popup\":\n return handleResult(scopes, await app.acquireTokenPopup(parameters));\n }\n }\n\n /**\n * Attempts to get token through the silent flow.\n * If failed, get token through interactive method with `doGetToken` method.\n */\n async function getToken(\n scopes: string[],\n getTokenOptions: CredentialFlowGetTokenOptions = {},\n ): Promise<AccessToken> {\n const getTokenTenantId =\n processMultiTenantRequest(tenantId, getTokenOptions, additionallyAllowedTenantIds) ||\n tenantId;\n\n if (!getTokenOptions.authority) {\n getTokenOptions.authority = getAuthority(getTokenTenantId, authorityHost);\n }\n\n // We ensure that redirection is handled at this point.\n await handleRedirect();\n\n if (!(await getActiveAccount()) && !disableAutomaticAuthentication) {\n await login(scopes);\n }\n\n // Attempts to get the token silently; else, falls back to interactive method.\n try {\n return await getTokenSilent(scopes, getTokenOptions);\n } catch (err: any) {\n if (err.name !== \"AuthenticationRequiredError\") {\n throw err;\n }\n if (getTokenOptions?.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions,\n message:\n \"Automatic authentication has been disabled. You may call the authenticate() method.\",\n });\n }\n logger.info(`Silent authentication failed, falling back to interactive method ${loginStyle}`);\n return getTokenInteractive(scopes, getTokenOptions);\n }\n }\n return {\n getActiveAccount,\n getToken,\n };\n}\n"]}
|
1
|
+
{"version":3,"file":"msalBrowserCommon.js","sourceRoot":"","sources":["../../../../src/msal/browserFlows/msalBrowserCommon.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,WAAW,MAAM,qBAAqB,CAAC;AAGnD,OAAO,EACL,qBAAqB,EACr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C,CAAC,MAAM,gBAAgB,EAAE,CAAC,IAAI,CAAC,8BAA8B,EAAE,CAAC;YACnE,MAAM,KAAK,CAAC,MAAM,CAAC,CAAC;QACtB,CAAC;QAED,8EAA8E;QAC9E,IAAI,CAAC;YACH,OAAO,MAAM,cAAc,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;QACvD,CAAC;QAAC,OAAO,GAAQ,EAAE,CAAC;YAClB,IAAI,GAAG,CAAC,IAAI,KAAK,6BAA6B,EAAE,CAAC;gBAC/C,MAAM,GAAG,CAAC;YACZ,CAAC;YACD,IAAI,eAAe,aAAf,eAAe,uBAAf,eAAe,CAAE,8BAA8B,EAAE,CAAC;gBACpD,MAAM,IAAI,2BAA2B,CAAC;oBACpC,MAAM;oBACN,eAAe;oBACf,OAAO,EACL,qFAAqF;iBACxF,CAAC,CAAC;YACL,CAAC;YACD,MAAM,CAAC,IAAI,CAAC,oEAAoE,UAAU,EAAE,CAAC,CAAC;YAC9F,OAAO,mBAAmB,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;QACtD,CAAC;IACH,CAAC;IACD,OAAO;QACL,gBAAgB;QAChB,QAAQ;KACT,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport * as msalBrowser from \"@azure/msal-browser\";\n\nimport type { MsalBrowserFlowOptions } from \"./msalBrowserOptions.js\";\nimport {\n defaultLoggerCallback,\n ensureValidMsalToken,\n getAuthority,\n getKnownAuthorities,\n getMSALLogLevel,\n handleMsalError,\n msalToPublic,\n publicToMsal,\n} from \"../utils.js\";\n\nimport type { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport type { AuthenticationRecord, MsalResult } from \"../types.js\";\nimport { AuthenticationRequiredError, CredentialUnavailableError } from \"../../errors.js\";\nimport type { CredentialFlowGetTokenOptions } from \"../credentials.js\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { formatSuccess } from \"../../util/logging.js\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n resolveTenantId,\n} from \"../../util/tenantIdUtils.js\";\nimport { DefaultTenantId } from \"../../constants.js\";\n\n// We keep a copy of the redirect hash.\n// Check if self and location object is defined.\nconst isLocationDefined = typeof self !== \"undefined\" && self.location !== undefined;\n\n/**\n * Generates a MSAL configuration that generally works for browsers\n * @internal\n */\nfunction generateMsalBrowserConfiguration(\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(tenantId, authority, options.disableInstanceDiscovery),\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 || (isLocationDefined ? self.location.origin : undefined),\n },\n cache: {\n cacheLocation: \"sessionStorage\",\n storeAuthStateInCookie: true, // Set to true to improve the experience on IE11 and Edge.\n },\n system: {\n loggerOptions: {\n loggerCallback: defaultLoggerCallback(options.logger, \"Browser\"),\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: options.loggingOptions?.enableUnsafeSupportLogging,\n },\n },\n };\n}\n\n/**\n * Methods that are used by InteractiveBrowserCredential\n * @internal\n */\nexport interface MsalBrowserClient {\n getActiveAccount(): Promise<AuthenticationRecord | undefined>;\n getToken(scopes: string[], options: CredentialFlowGetTokenOptions): Promise<AccessToken>;\n}\n\n// We keep a copy of the redirect hash.\nconst redirectHash = isLocationDefined ? self.location.hash : undefined;\n\n/**\n * Uses MSAL Browser 2.X for browser authentication,\n * which uses the [Auth Code Flow](https://learn.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow).\n * @internal\n */\nexport function createMsalBrowserClient(options: MsalBrowserFlowOptions): MsalBrowserClient {\n const loginStyle = options.loginStyle;\n if (!options.clientId) {\n throw new CredentialUnavailableError(\"A client ID is required in browsers\");\n }\n const clientId = options.clientId;\n const logger = options.logger;\n const tenantId = resolveTenantId(logger, options.tenantId, options.clientId);\n const additionallyAllowedTenantIds: string[] = resolveAdditionallyAllowedTenantIds(\n options?.tokenCredentialOptions?.additionallyAllowedTenants,\n );\n const authorityHost = options.authorityHost;\n const msalConfig = generateMsalBrowserConfiguration(options);\n const disableAutomaticAuthentication = options.disableAutomaticAuthentication;\n const loginHint = options.loginHint;\n\n let account: AuthenticationRecord | undefined;\n if (options.authenticationRecord) {\n account = {\n ...options.authenticationRecord,\n tenantId,\n };\n }\n\n // This variable should only be used through calling `getApp` function\n let app: msalBrowser.IPublicClientApplication;\n /**\n * Return the MSAL account if not set yet\n * @returns MSAL application\n */\n async function getApp(): Promise<msalBrowser.IPublicClientApplication> {\n if (!app) {\n // Prepare the MSAL application\n app = await msalBrowser.PublicClientApplication.createPublicClientApplication(msalConfig);\n\n // setting the account right after the app is created.\n if (account) {\n app.setActiveAccount(publicToMsal(account));\n }\n }\n\n return app;\n }\n\n /**\n * Loads the account based on the result of the authentication.\n * If no result was received, tries to load the account from the cache.\n * @param result - Result object received from MSAL.\n */\n async function handleBrowserResult(\n result?: msalBrowser.AuthenticationResult,\n ): Promise<AuthenticationRecord | undefined> {\n try {\n const msalApp = await getApp();\n if (result && result.account) {\n logger.info(`MSAL Browser V2 authentication successful.`);\n msalApp.setActiveAccount(result.account);\n return msalToPublic(clientId, result.account);\n }\n } catch (e: any) {\n logger.info(`Failed to acquire token through MSAL. ${e.message}`);\n }\n return;\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 function handleResult(\n scopes: string | string[],\n result?: MsalResult,\n getTokenOptions?: GetTokenOptions,\n ): AccessToken {\n if (result?.account) {\n account = msalToPublic(clientId, result.account);\n }\n ensureValidMsalToken(scopes, result, getTokenOptions);\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: result.accessToken,\n expiresOnTimestamp: result.expiresOn.getTime(),\n refreshAfterTimestamp: result.refreshOn?.getTime(),\n tokenType: \"Bearer\",\n };\n }\n\n /**\n * Uses MSAL to handle the redirect.\n */\n async function handleRedirect(): Promise<AuthenticationRecord | undefined> {\n const msalApp = await getApp();\n return handleBrowserResult((await msalApp.handleRedirectPromise(redirectHash)) || undefined);\n }\n\n /**\n * Uses MSAL to retrieve the active account.\n */\n async function getActiveAccount(): Promise<AuthenticationRecord | undefined> {\n const msalApp = await getApp();\n const activeAccount = msalApp.getActiveAccount();\n if (!activeAccount) {\n return;\n }\n return msalToPublic(clientId, activeAccount);\n }\n\n /**\n * Uses MSAL to trigger a redirect or a popup login.\n */\n async function login(scopes: string | string[] = []): Promise<AuthenticationRecord | undefined> {\n const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];\n const loginRequest: msalBrowser.RedirectRequest = {\n scopes: arrayScopes,\n loginHint: loginHint,\n };\n const msalApp = await getApp();\n switch (loginStyle) {\n case \"redirect\": {\n await app.loginRedirect(loginRequest);\n return;\n }\n case \"popup\":\n return handleBrowserResult(await msalApp.loginPopup(loginRequest));\n }\n }\n\n /**\n * Tries to retrieve the token silently using MSAL.\n */\n async function getTokenSilent(\n scopes: string[],\n getTokenOptions?: CredentialFlowGetTokenOptions,\n ): Promise<AccessToken> {\n const activeAccount = await getActiveAccount();\n if (!activeAccount) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions,\n message:\n \"Silent authentication failed. We couldn't retrieve an active account from the cache.\",\n });\n }\n\n const parameters: msalBrowser.SilentRequest = {\n authority: getTokenOptions?.authority || msalConfig.auth.authority!,\n correlationId: getTokenOptions?.correlationId,\n claims: getTokenOptions?.claims,\n account: publicToMsal(activeAccount),\n forceRefresh: false,\n scopes,\n };\n\n try {\n logger.info(\"Attempting to acquire token silently\");\n const msalApp = await getApp();\n const response = await msalApp.acquireTokenSilent(parameters);\n return handleResult(scopes, response);\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n /**\n * Attempts to retrieve the token in the browser through interactive methods.\n */\n async function getTokenInteractive(\n scopes: string[],\n getTokenOptions?: CredentialFlowGetTokenOptions,\n ): Promise<AccessToken> {\n const activeAccount = await getActiveAccount();\n if (!activeAccount) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions,\n message:\n \"Silent authentication failed. We couldn't retrieve an active account from the cache.\",\n });\n }\n\n const parameters: msalBrowser.RedirectRequest = {\n authority: getTokenOptions?.authority || msalConfig.auth.authority!,\n correlationId: getTokenOptions?.correlationId,\n claims: getTokenOptions?.claims,\n account: publicToMsal(activeAccount),\n loginHint: loginHint,\n scopes,\n };\n const msalApp = await getApp();\n switch (loginStyle) {\n case \"redirect\":\n // This will go out of the page.\n // Once the InteractiveBrowserCredential is initialized again,\n // we'll load the MSAL account in the constructor.\n\n await msalApp.acquireTokenRedirect(parameters);\n return { token: \"\", expiresOnTimestamp: 0, tokenType: \"Bearer\" };\n case \"popup\":\n return handleResult(scopes, await app.acquireTokenPopup(parameters));\n }\n }\n\n /**\n * Attempts to get token through the silent flow.\n * If failed, get token through interactive method with `doGetToken` method.\n */\n async function getToken(\n scopes: string[],\n getTokenOptions: CredentialFlowGetTokenOptions = {},\n ): Promise<AccessToken> {\n const getTokenTenantId =\n processMultiTenantRequest(tenantId, getTokenOptions, additionallyAllowedTenantIds) ||\n tenantId;\n\n if (!getTokenOptions.authority) {\n getTokenOptions.authority = getAuthority(getTokenTenantId, authorityHost);\n }\n\n // We ensure that redirection is handled at this point.\n await handleRedirect();\n\n if (!(await getActiveAccount()) && !disableAutomaticAuthentication) {\n await login(scopes);\n }\n\n // Attempts to get the token silently; else, falls back to interactive method.\n try {\n return await getTokenSilent(scopes, getTokenOptions);\n } catch (err: any) {\n if (err.name !== \"AuthenticationRequiredError\") {\n throw err;\n }\n if (getTokenOptions?.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions,\n message:\n \"Automatic authentication has been disabled. You may call the authenticate() method.\",\n });\n }\n logger.info(`Silent authentication failed, falling back to interactive method ${loginStyle}`);\n return getTokenInteractive(scopes, getTokenOptions);\n }\n }\n return {\n getActiveAccount,\n getToken,\n };\n}\n"]}
|
@@ -7,7 +7,7 @@ import type { ClientCertificateCredentialPEMConfiguration, ClientCertificatePEMC
|
|
7
7
|
* certificate that is assigned to an App Registration. More information
|
8
8
|
* on how to configure certificate authentication can be found here:
|
9
9
|
*
|
10
|
-
* https://learn.microsoft.com/
|
10
|
+
* https://learn.microsoft.com/azure/active-directory/develop/active-directory-certificate-credentials#register-your-certificate-with-azure-ad
|
11
11
|
*
|
12
12
|
*/
|
13
13
|
export declare class ClientCertificateCredential implements TokenCredential {
|
@@ -17,7 +17,7 @@ const logger = (0, logging_js_1.credentialLogger)(credentialName);
|
|
17
17
|
* certificate that is assigned to an App Registration. More information
|
18
18
|
* on how to configure certificate authentication can be found here:
|
19
19
|
*
|
20
|
-
* https://learn.microsoft.com/
|
20
|
+
* https://learn.microsoft.com/azure/active-directory/develop/active-directory-certificate-credentials#register-your-certificate-with-azure-ad
|
21
21
|
*
|
22
22
|
*/
|
23
23
|
class ClientCertificateCredential {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"clientCertificateCredential.js","sourceRoot":"","sources":["../../../src/credentials/clientCertificateCredential.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAiMlC,4CA2CC;AAxOD,mEAAmE;AACnE,6CAA2D;AAC3D,+DAGkC;AAIlC,mDAAsD;AACtD,+CAA4C;AAC5C,mDAAmD;AAOnD,MAAM,cAAc,GAAG,6BAA6B,CAAC;AACrD,MAAM,MAAM,GAAG,IAAA,6BAAgB,EAAC,cAAc,CAAC,CAAC;AAEhD;;;;;;;GAOG;AACH,MAAa,2BAA2B;IAsDtC,YACE,QAAgB,EAChB,QAAgB,EAChB,8BAAoF,EACpF,UAA8C,EAAE;QAEhD,IAAI,CAAC,QAAQ,IAAI,CAAC,QAAQ,EAAE,CAAC;YAC3B,MAAM,IAAI,KAAK,CA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,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport type { MsalClient } from \"../msal/nodeFlows/msalClient.js\";\nimport { createMsalClient } from \"../msal/nodeFlows/msalClient.js\";\nimport { createHash, createPrivateKey } from \"node:crypto\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils.js\";\n\nimport type { CertificateParts } from \"../msal/types.js\";\nimport type { ClientCertificateCredentialOptions } from \"./clientCertificateCredentialOptions.js\";\nimport { credentialLogger } from \"../util/logging.js\";\nimport { readFile } from \"node:fs/promises\";\nimport { tracingClient } from \"../util/tracing.js\";\nimport type {\n ClientCertificateCredentialPEMConfiguration,\n ClientCertificatePEMCertificate,\n ClientCertificatePEMCertificatePath,\n} from \"./clientCertificateCredentialModels.js\";\n\nconst credentialName = \"ClientCertificateCredential\";\nconst logger = credentialLogger(credentialName);\n\n/**\n * Enables authentication to Microsoft Entra ID using a PEM-encoded\n * certificate that is assigned to an App Registration. More information\n * on how to configure certificate authentication can be found here:\n *\n * https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-certificate-credentials#register-your-certificate-with-azure-ad\n *\n */\nexport class ClientCertificateCredential implements TokenCredential {\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private certificateConfiguration: ClientCertificateCredentialPEMConfiguration;\n private sendCertificateChain?: boolean;\n private msalClient: MsalClient;\n\n /**\n * Creates an instance of the ClientCertificateCredential with the details\n * needed to authenticate against Microsoft Entra ID with a certificate.\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param certificatePath - The path to a PEM-encoded public/private key certificate on the filesystem.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n certificatePath: string,\n options?: ClientCertificateCredentialOptions,\n );\n /**\n * Creates an instance of the ClientCertificateCredential with the details\n * needed to authenticate against Microsoft Entra ID with a certificate.\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param configuration - Other parameters required, including the path of the certificate on the filesystem.\n * If the type is ignored, we will throw the value of the path to a PEM certificate.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n configuration: ClientCertificatePEMCertificatePath,\n options?: ClientCertificateCredentialOptions,\n );\n /**\n * Creates an instance of the ClientCertificateCredential with the details\n * needed to authenticate against Microsoft Entra ID with a certificate.\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param configuration - Other parameters required, including the PEM-encoded certificate as a string.\n * If the type is ignored, we will throw the value of the PEM-encoded certificate.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n configuration: ClientCertificatePEMCertificate,\n options?: ClientCertificateCredentialOptions,\n );\n constructor(\n tenantId: string,\n clientId: string,\n certificatePathOrConfiguration: string | ClientCertificateCredentialPEMConfiguration,\n options: ClientCertificateCredentialOptions = {},\n ) {\n if (!tenantId || !clientId) {\n throw new Error(`${credentialName}: tenantId and clientId are required parameters.`);\n }\n\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n\n this.sendCertificateChain = options.sendCertificateChain;\n\n this.certificateConfiguration = {\n ...(typeof certificatePathOrConfiguration === \"string\"\n ? {\n certificatePath: certificatePathOrConfiguration,\n }\n : certificatePathOrConfiguration),\n };\n const certificate = (this.certificateConfiguration as ClientCertificatePEMCertificate)\n .certificate;\n const certificatePath = (this.certificateConfiguration as ClientCertificatePEMCertificatePath)\n .certificatePath;\n if (!this.certificateConfiguration || !(certificate || certificatePath)) {\n throw new Error(\n `${credentialName}: Provide either a PEM certificate in string form, or the path to that certificate in the filesystem. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`,\n );\n }\n if (certificate && certificatePath) {\n throw new Error(\n `${credentialName}: To avoid unexpected behaviors, providing both the contents of a PEM certificate and the path to a PEM certificate is forbidden. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`,\n );\n }\n this.msalClient = createMsalClient(clientId, tenantId, {\n ...options,\n logger,\n tokenCredentialOptions: 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} 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 async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger,\n );\n\n const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];\n const certificate = await this.buildClientCertificate();\n return this.msalClient.getTokenByClientCertificate(arrayScopes, certificate, newOptions);\n });\n }\n\n private async buildClientCertificate(): Promise<CertificateParts> {\n const parts = await parseCertificate(\n this.certificateConfiguration,\n this.sendCertificateChain ?? false,\n );\n\n let privateKey: string;\n if (this.certificateConfiguration.certificatePassword !== undefined) {\n privateKey = createPrivateKey({\n key: parts.certificateContents,\n passphrase: this.certificateConfiguration.certificatePassword,\n format: \"pem\",\n })\n .export({\n format: \"pem\",\n type: \"pkcs8\",\n })\n .toString();\n } else {\n privateKey = parts.certificateContents;\n }\n\n return {\n thumbprint: parts.thumbprint,\n thumbprintSha256: parts.thumbprintSha256,\n privateKey,\n x5c: parts.x5c,\n };\n }\n}\n\n/**\n * Parses a certificate into its relevant parts\n *\n * @param certificateConfiguration - The certificate contents or path to the certificate\n * @param sendCertificateChain - true if the entire certificate chain should be sent for SNI, false otherwise\n * @returns The parsed certificate parts and the certificate contents\n */\nexport async function parseCertificate(\n certificateConfiguration: ClientCertificateCredentialPEMConfiguration,\n sendCertificateChain: boolean,\n): Promise<Omit<CertificateParts, \"privateKey\"> & { certificateContents: string }> {\n const certificate = (certificateConfiguration as ClientCertificatePEMCertificate).certificate;\n const certificatePath = (certificateConfiguration as ClientCertificatePEMCertificatePath)\n .certificatePath;\n const certificateContents = certificate || (await readFile(certificatePath!, \"utf8\"));\n const x5c = sendCertificateChain ? certificateContents : undefined;\n\n const certificatePattern =\n /(-+BEGIN CERTIFICATE-+)(\\n\\r?|\\r\\n?)([A-Za-z0-9+/\\n\\r]+=*)(\\n\\r?|\\r\\n?)(-+END CERTIFICATE-+)/g;\n const publicKeys: string[] = [];\n\n // Match all possible certificates, in the order they are in the file. These will form the chain that is used for x5c\n let match;\n do {\n match = certificatePattern.exec(certificateContents);\n if (match) {\n publicKeys.push(match[3]);\n }\n } while (match);\n\n if (publicKeys.length === 0) {\n throw new Error(\"The file at the specified path does not contain a PEM-encoded certificate.\");\n }\n\n const thumbprint = createHash(\"sha1\")\n .update(Buffer.from(publicKeys[0], \"base64\"))\n .digest(\"hex\")\n .toUpperCase();\n\n const thumbprintSha256 = createHash(\"sha256\")\n .update(Buffer.from(publicKeys[0], \"base64\"))\n .digest(\"hex\")\n .toUpperCase();\n\n return {\n certificateContents,\n thumbprintSha256,\n thumbprint,\n x5c,\n };\n}\n"]}
|
1
|
+
{"version":3,"file":"clientCertificateCredential.js","sourceRoot":"","sources":["../../../src/credentials/clientCertificateCredential.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAiMlC,4CA2CC;AAxOD,mEAAmE;AACnE,6CAA2D;AAC3D,+DAGkC;AAIlC,mDAAsD;AACtD,+CAA4C;AAC5C,mDAAmD;AAOnD,MAAM,cAAc,GAAG,6BAA6B,CAAC;AACrD,MAAM,MAAM,GAAG,IAAA,6BAAgB,EAAC,cAAc,CAAC,CAAC;AAEhD;;;;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AAU,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC;SAC5C,MAAM,CAAC,KAAK,CAAC;SACb,WAAW,EAAE,CAAC;IAEjB,OAAO;QACL,mBAAmB;QACnB,gBAAgB;QAChB,UAAU;QACV,GAAG;KACJ,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport type { MsalClient } from \"../msal/nodeFlows/msalClient.js\";\nimport { createMsalClient } from \"../msal/nodeFlows/msalClient.js\";\nimport { createHash, createPrivateKey } from \"node:crypto\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils.js\";\n\nimport type { CertificateParts } from \"../msal/types.js\";\nimport type { ClientCertificateCredentialOptions } from \"./clientCertificateCredentialOptions.js\";\nimport { credentialLogger } from \"../util/logging.js\";\nimport { readFile } from \"node:fs/promises\";\nimport { tracingClient } from \"../util/tracing.js\";\nimport type {\n ClientCertificateCredentialPEMConfiguration,\n ClientCertificatePEMCertificate,\n ClientCertificatePEMCertificatePath,\n} from \"./clientCertificateCredentialModels.js\";\n\nconst credentialName = \"ClientCertificateCredential\";\nconst logger = credentialLogger(credentialName);\n\n/**\n * Enables authentication to Microsoft Entra ID using a PEM-encoded\n * certificate that is assigned to an App Registration. More information\n * on how to configure certificate authentication can be found here:\n *\n * https://learn.microsoft.com/azure/active-directory/develop/active-directory-certificate-credentials#register-your-certificate-with-azure-ad\n *\n */\nexport class ClientCertificateCredential implements TokenCredential {\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private certificateConfiguration: ClientCertificateCredentialPEMConfiguration;\n private sendCertificateChain?: boolean;\n private msalClient: MsalClient;\n\n /**\n * Creates an instance of the ClientCertificateCredential with the details\n * needed to authenticate against Microsoft Entra ID with a certificate.\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param certificatePath - The path to a PEM-encoded public/private key certificate on the filesystem.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n certificatePath: string,\n options?: ClientCertificateCredentialOptions,\n );\n /**\n * Creates an instance of the ClientCertificateCredential with the details\n * needed to authenticate against Microsoft Entra ID with a certificate.\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param configuration - Other parameters required, including the path of the certificate on the filesystem.\n * If the type is ignored, we will throw the value of the path to a PEM certificate.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n configuration: ClientCertificatePEMCertificatePath,\n options?: ClientCertificateCredentialOptions,\n );\n /**\n * Creates an instance of the ClientCertificateCredential with the details\n * needed to authenticate against Microsoft Entra ID with a certificate.\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param configuration - Other parameters required, including the PEM-encoded certificate as a string.\n * If the type is ignored, we will throw the value of the PEM-encoded certificate.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n configuration: ClientCertificatePEMCertificate,\n options?: ClientCertificateCredentialOptions,\n );\n constructor(\n tenantId: string,\n clientId: string,\n certificatePathOrConfiguration: string | ClientCertificateCredentialPEMConfiguration,\n options: ClientCertificateCredentialOptions = {},\n ) {\n if (!tenantId || !clientId) {\n throw new Error(`${credentialName}: tenantId and clientId are required parameters.`);\n }\n\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n\n this.sendCertificateChain = options.sendCertificateChain;\n\n this.certificateConfiguration = {\n ...(typeof certificatePathOrConfiguration === \"string\"\n ? {\n certificatePath: certificatePathOrConfiguration,\n }\n : certificatePathOrConfiguration),\n };\n const certificate = (this.certificateConfiguration as ClientCertificatePEMCertificate)\n .certificate;\n const certificatePath = (this.certificateConfiguration as ClientCertificatePEMCertificatePath)\n .certificatePath;\n if (!this.certificateConfiguration || !(certificate || certificatePath)) {\n throw new Error(\n `${credentialName}: Provide either a PEM certificate in string form, or the path to that certificate in the filesystem. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`,\n );\n }\n if (certificate && certificatePath) {\n throw new Error(\n `${credentialName}: To avoid unexpected behaviors, providing both the contents of a PEM certificate and the path to a PEM certificate is forbidden. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`,\n );\n }\n this.msalClient = createMsalClient(clientId, tenantId, {\n ...options,\n logger,\n tokenCredentialOptions: 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} 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 async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger,\n );\n\n const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];\n const certificate = await this.buildClientCertificate();\n return this.msalClient.getTokenByClientCertificate(arrayScopes, certificate, newOptions);\n });\n }\n\n private async buildClientCertificate(): Promise<CertificateParts> {\n const parts = await parseCertificate(\n this.certificateConfiguration,\n this.sendCertificateChain ?? false,\n );\n\n let privateKey: string;\n if (this.certificateConfiguration.certificatePassword !== undefined) {\n privateKey = createPrivateKey({\n key: parts.certificateContents,\n passphrase: this.certificateConfiguration.certificatePassword,\n format: \"pem\",\n })\n .export({\n format: \"pem\",\n type: \"pkcs8\",\n })\n .toString();\n } else {\n privateKey = parts.certificateContents;\n }\n\n return {\n thumbprint: parts.thumbprint,\n thumbprintSha256: parts.thumbprintSha256,\n privateKey,\n x5c: parts.x5c,\n };\n }\n}\n\n/**\n * Parses a certificate into its relevant parts\n *\n * @param certificateConfiguration - The certificate contents or path to the certificate\n * @param sendCertificateChain - true if the entire certificate chain should be sent for SNI, false otherwise\n * @returns The parsed certificate parts and the certificate contents\n */\nexport async function parseCertificate(\n certificateConfiguration: ClientCertificateCredentialPEMConfiguration,\n sendCertificateChain: boolean,\n): Promise<Omit<CertificateParts, \"privateKey\"> & { certificateContents: string }> {\n const certificate = (certificateConfiguration as ClientCertificatePEMCertificate).certificate;\n const certificatePath = (certificateConfiguration as ClientCertificatePEMCertificatePath)\n .certificatePath;\n const certificateContents = certificate || (await readFile(certificatePath!, \"utf8\"));\n const x5c = sendCertificateChain ? certificateContents : undefined;\n\n const certificatePattern =\n /(-+BEGIN CERTIFICATE-+)(\\n\\r?|\\r\\n?)([A-Za-z0-9+/\\n\\r]+=*)(\\n\\r?|\\r\\n?)(-+END CERTIFICATE-+)/g;\n const publicKeys: string[] = [];\n\n // Match all possible certificates, in the order they are in the file. These will form the chain that is used for x5c\n let match;\n do {\n match = certificatePattern.exec(certificateContents);\n if (match) {\n publicKeys.push(match[3]);\n }\n } while (match);\n\n if (publicKeys.length === 0) {\n throw new Error(\"The file at the specified path does not contain a PEM-encoded certificate.\");\n }\n\n const thumbprint = createHash(\"sha1\")\n .update(Buffer.from(publicKeys[0], \"base64\"))\n .digest(\"hex\")\n .toUpperCase();\n\n const thumbprintSha256 = createHash(\"sha256\")\n .update(Buffer.from(publicKeys[0], \"base64\"))\n .digest(\"hex\")\n .toUpperCase();\n\n return {\n certificateContents,\n thumbprintSha256,\n thumbprint,\n x5c,\n };\n}\n"]}
|
@@ -7,7 +7,7 @@ import type { ManagedIdentityCredentialClientIdOptions, ManagedIdentityCredentia
|
|
7
7
|
* Azure Kubernetes Services, Azure Service Fabric instances and inside of the Azure Cloud Shell.
|
8
8
|
*
|
9
9
|
* More information about configuring managed identities can be found here:
|
10
|
-
* https://learn.microsoft.com/
|
10
|
+
* https://learn.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview
|
11
11
|
*/
|
12
12
|
export declare class ManagedIdentityCredential implements TokenCredential {
|
13
13
|
private managedIdentityApp;
|
@@ -21,7 +21,7 @@ const logger = (0, logging_js_1.credentialLogger)("ManagedIdentityCredential");
|
|
21
21
|
* Azure Kubernetes Services, Azure Service Fabric instances and inside of the Azure Cloud Shell.
|
22
22
|
*
|
23
23
|
* More information about configuring managed identities can be found here:
|
24
|
-
* https://learn.microsoft.com/
|
24
|
+
* https://learn.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview
|
25
25
|
*/
|
26
26
|
class ManagedIdentityCredential {
|
27
27
|
/**
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/index.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAKlC,0CAA4C;AAC5C,gDAA8D;AAC9D,sEAAgE;AAChE,+CAA0F;AAC1F,kDAA6E;AAC7E,6DAAuD;AAEvD,sDAAqF;AACrF,sDAAsD;AACtD,6CAAuC;AACvC,+DAAyD;AACzD,yCAA4E;AAQ5E,MAAM,MAAM,GAAG,IAAA,6BAAgB,EAAC,2BAA2B,CAAC,CAAC;AAE7D;;;;;;;GAOG;AACH,MAAa,yBAAyB;IAuCpC;;;OAGG;IACH,YACE,iBAI4C,EAC5C,OAAgC;;QA3C1B,mBAAc,GAAoC;YACxD,UAAU,EAAE,CAAC;YACb,cAAc,EAAE,GAAG;YACnB,iBAAiB,EAAE,CAAC;SACrB,CAAC;QAyCA,IAAI,QAAgC,CAAC;QACrC,IAAI,OAAO,iBAAiB,KAAK,QAAQ,EAAE,CAAC;YAC1C,IAAI,CAAC,QAAQ,GAAG,iBAAiB,CAAC;YAClC,QAAQ,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;QAC3B,CAAC;aA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,4CAA4C;IAC5C,IAAI,GAAG,CAAC,UAAU,KAAK,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,GAAG,EAAE,CAAC;QAC/C,IAAI,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,CAAC;YACxC,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\n\nimport type { TokenCredentialOptions } from \"../../tokenCredentialOptions.js\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { ManagedIdentityApplication } from \"@azure/msal-node\";\nimport { IdentityClient } from \"../../client/identityClient.js\";\nimport { AuthenticationRequiredError, CredentialUnavailableError } from \"../../errors.js\";\nimport { getMSALLogLevel, defaultLoggerCallback } from \"../../msal/utils.js\";\nimport { imdsRetryPolicy } from \"./imdsRetryPolicy.js\";\nimport type { MSIConfiguration } from \"./models.js\";\nimport { formatSuccess, formatError, credentialLogger } from \"../../util/logging.js\";\nimport { tracingClient } from \"../../util/tracing.js\";\nimport { imdsMsi } from \"./imdsMsi.js\";\nimport { tokenExchangeMsi } from \"./tokenExchangeMsi.js\";\nimport { mapScopesToResource, serviceFabricErrorMessage } from \"./utils.js\";\nimport type { MsalToken, ValidMsalToken } from \"../../msal/types.js\";\nimport type {\n ManagedIdentityCredentialClientIdOptions,\n ManagedIdentityCredentialObjectIdOptions,\n ManagedIdentityCredentialResourceIdOptions,\n} from \"./options.js\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential\");\n\n/**\n * Attempts authentication using a managed identity available at the deployment environment.\n * This authentication type works in Azure VMs, App Service instances, Azure Functions applications,\n * Azure Kubernetes Services, Azure Service Fabric instances and inside of the Azure Cloud Shell.\n *\n * More information about configuring managed identities can be found here:\n * https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview\n */\nexport class ManagedIdentityCredential implements TokenCredential {\n private managedIdentityApp: ManagedIdentityApplication;\n private identityClient: IdentityClient;\n private clientId?: string;\n private resourceId?: string;\n private objectId?: string;\n private msiRetryConfig: MSIConfiguration[\"retryConfig\"] = {\n maxRetries: 5,\n startDelayInMs: 800,\n intervalIncrement: 2,\n };\n private isAvailableIdentityClient: IdentityClient;\n\n /**\n * Creates an instance of ManagedIdentityCredential with the client ID of a\n * user-assigned identity, or app registration (when working with AKS pod-identity).\n *\n * @param clientId - The client ID of the user-assigned identity, or app registration (when working with AKS pod-identity).\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(clientId: string, options?: TokenCredentialOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with a client ID\n *\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialClientIdOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with a resource ID\n *\n * @param options - Options for configuring the resource which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialResourceIdOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with an object ID\n *\n * @param options - Options for configuring the resource which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialObjectIdOptions);\n /**\n * @internal\n * @hidden\n */\n constructor(\n clientIdOrOptions?:\n | string\n | ManagedIdentityCredentialClientIdOptions\n | ManagedIdentityCredentialResourceIdOptions\n | ManagedIdentityCredentialObjectIdOptions,\n options?: TokenCredentialOptions,\n ) {\n let _options: TokenCredentialOptions;\n if (typeof clientIdOrOptions === \"string\") {\n this.clientId = clientIdOrOptions;\n _options = options ?? {};\n } else {\n this.clientId = (clientIdOrOptions as ManagedIdentityCredentialClientIdOptions)?.clientId;\n _options = clientIdOrOptions ?? {};\n }\n this.resourceId = (_options as ManagedIdentityCredentialResourceIdOptions)?.resourceId;\n this.objectId = (_options as ManagedIdentityCredentialObjectIdOptions)?.objectId;\n\n // For JavaScript users.\n const providedIds = [\n { key: \"clientId\", value: this.clientId },\n { key: \"resourceId\", value: this.resourceId },\n { key: \"objectId\", value: this.objectId },\n ].filter((id) => id.value);\n if (providedIds.length > 1) {\n throw new Error(\n `ManagedIdentityCredential: only one of 'clientId', 'resourceId', or 'objectId' can be provided. Received values: ${JSON.stringify(\n { clientId: this.clientId, resourceId: this.resourceId, objectId: this.objectId },\n )}`,\n );\n }\n\n // ManagedIdentity uses http for local requests\n _options.allowInsecureConnection = true;\n\n if (_options.retryOptions?.maxRetries !== undefined) {\n this.msiRetryConfig.maxRetries = _options.retryOptions.maxRetries;\n }\n\n this.identityClient = new IdentityClient({\n ..._options,\n additionalPolicies: [{ policy: imdsRetryPolicy(this.msiRetryConfig), position: \"perCall\" }],\n });\n\n this.managedIdentityApp = new ManagedIdentityApplication({\n managedIdentityIdParams: {\n userAssignedClientId: this.clientId,\n userAssignedResourceId: this.resourceId,\n userAssignedObjectId: this.objectId,\n },\n system: {\n disableInternalRetries: true,\n networkClient: this.identityClient,\n loggerOptions: {\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: _options.loggingOptions?.enableUnsafeSupportLogging,\n loggerCallback: defaultLoggerCallback(logger),\n },\n },\n });\n\n this.isAvailableIdentityClient = new IdentityClient({\n ..._options,\n retryOptions: {\n maxRetries: 0,\n },\n });\n\n const managedIdentitySource = this.managedIdentityApp.getManagedIdentitySource();\n // CloudShell MSI will ignore any user-assigned identity passed as parameters. To avoid confusion, we prevent this from happening as early as possible.\n if (managedIdentitySource === \"CloudShell\") {\n if (this.clientId || this.resourceId || this.objectId) {\n logger.warning(\n `CloudShell MSI detected with user-provided IDs - throwing. Received values: ${JSON.stringify(\n {\n clientId: this.clientId,\n resourceId: this.resourceId,\n objectId: this.objectId,\n },\n )}.`,\n );\n throw new CredentialUnavailableError(\n \"ManagedIdentityCredential: Specifying a user-assigned managed identity is not supported for CloudShell at runtime. When using Managed Identity in CloudShell, omit the clientId, resourceId, and objectId parameters.\",\n );\n }\n }\n\n // ServiceFabric does not support specifying user-assigned managed identity by client ID or resource ID. The managed identity selected is based on the resource configuration.\n if (managedIdentitySource === \"ServiceFabric\") {\n if (this.clientId || this.resourceId || this.objectId) {\n logger.warning(\n `Service Fabric detected with user-provided IDs - throwing. Received values: ${JSON.stringify(\n {\n clientId: this.clientId,\n resourceId: this.resourceId,\n objectId: this.objectId,\n },\n )}.`,\n );\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: ${serviceFabricErrorMessage}`,\n );\n }\n }\n\n logger.info(`Using ${managedIdentitySource} managed identity.`);\n\n // Check if either clientId, resourceId or objectId was provided and log the value used\n if (providedIds.length === 1) {\n const { key, value } = providedIds[0];\n logger.info(`${managedIdentitySource} with ${key}: ${value}`);\n }\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@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 logger.getToken.info(\"Using the MSAL provider for Managed Identity.\");\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Multiple scopes are not supported. Scopes: ${JSON.stringify(\n scopes,\n )}`,\n );\n }\n\n return tracingClient.withSpan(\"ManagedIdentityCredential.getToken\", options, async () => {\n try {\n const isTokenExchangeMsi = await tokenExchangeMsi.isAvailable(this.clientId);\n\n // Most scenarios are handled by MSAL except for two:\n // AKS pod identity - MSAL does not implement the token exchange flow.\n // IMDS Endpoint probing - MSAL does not do any probing before trying to get a token.\n // As a DefaultAzureCredential optimization we probe the IMDS endpoint with a short timeout and no retries before actually trying to get a token\n // We will continue to implement these features in the Identity library.\n\n const identitySource = this.managedIdentityApp.getManagedIdentitySource();\n const isImdsMsi = identitySource === \"DefaultToImds\" || identitySource === \"Imds\"; // Neither actually checks that IMDS endpoint is available, just that it's the source the MSAL _would_ try to use.\n\n logger.getToken.info(`MSAL Identity source: ${identitySource}`);\n\n if (isTokenExchangeMsi) {\n // In the AKS scenario we will use the existing tokenExchangeMsi indefinitely.\n logger.getToken.info(\"Using the token exchange managed identity.\");\n const result = await tokenExchangeMsi.getToken({\n scopes,\n clientId: this.clientId,\n identityClient: this.identityClient,\n retryConfig: this.msiRetryConfig,\n resourceId: this.resourceId,\n });\n\n if (result === null) {\n throw new CredentialUnavailableError(\n \"Attempted to use the token exchange managed identity, but received a null response.\",\n );\n }\n\n return result;\n } else if (isImdsMsi) {\n // In the IMDS scenario we will probe the IMDS endpoint to ensure it's available before trying to get a token.\n // If the IMDS endpoint is not available and this is the source that MSAL will use, we will fail-fast with an error that tells DAC to move to the next credential.\n logger.getToken.info(\"Using the IMDS endpoint to probe for availability.\");\n const isAvailable = await imdsMsi.isAvailable({\n scopes,\n clientId: this.clientId,\n getTokenOptions: options,\n identityClient: this.isAvailableIdentityClient,\n resourceId: this.resourceId,\n });\n\n if (!isAvailable) {\n throw new CredentialUnavailableError(\n `Attempted to use the IMDS endpoint, but it is not available.`,\n );\n }\n }\n\n // If we got this far, it means:\n // - This is not a tokenExchangeMsi,\n // - We already probed for IMDS endpoint availability and failed-fast if it's unreachable.\n // We can proceed normally by calling MSAL for a token.\n logger.getToken.info(\"Calling into MSAL for managed identity token.\");\n const token = await this.managedIdentityApp.acquireToken({\n resource,\n });\n\n this.ensureValidMsalToken(scopes, token, options);\n logger.getToken.info(formatSuccess(scopes));\n\n return {\n expiresOnTimestamp: token.expiresOn.getTime(),\n token: token.accessToken,\n refreshAfterTimestamp: token.refreshOn?.getTime(),\n tokenType: \"Bearer\",\n } as AccessToken;\n } catch (err: any) {\n logger.getToken.error(formatError(scopes, err));\n\n // AuthenticationRequiredError described as Error to enforce authentication after trying to retrieve a token silently.\n // TODO: why would this _ever_ happen considering we're not trying the silent request in this flow?\n if (err.name === \"AuthenticationRequiredError\") {\n throw err;\n }\n\n if (isNetworkError(err)) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Network unreachable. Message: ${err.message}`,\n { cause: err },\n );\n }\n\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Authentication failed. Message ${err.message}`,\n { cause: err },\n );\n }\n });\n }\n\n /**\n * Ensures the validity of the MSAL token\n */\n private ensureValidMsalToken(\n scopes: string | string[],\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions,\n ): asserts msalToken is ValidMsalToken {\n const createError = (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 createError(\"No response.\");\n }\n if (!msalToken.expiresOn) {\n throw createError(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw createError(`Response had no \"accessToken\" property.`);\n }\n }\n}\n\nfunction isNetworkError(err: any): boolean {\n // MSAL error\n if (err.errorCode === \"network_error\") {\n return true;\n }\n\n // Probe errors\n if (err.code === \"ENETUNREACH\" || err.code === \"EHOSTUNREACH\") {\n return true;\n }\n\n // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\" or \"A socket operation was attempted to an unreachable host\"\n // rather than just timing out, as expected.\n if (err.statusCode === 403 || err.code === 403) {\n if (err.message.includes(\"unreachable\")) {\n return true;\n }\n }\n\n return false;\n}\n"]}
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/index.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAKlC,0CAA4C;AAC5C,gDAA8D;AAC9D,sEAAgE;AAChE,+CAA0F;AAC1F,kDAA6E;AAC7E,6DAAuD;AAEvD,sDAAqF;AACrF,sDAAsD;AACtD,6CAAuC;AACvC,+DAAyD;AACzD,yCAA4E;AAQ5E,MAAM,MAAM,GAAG,IAAA,6BAAgB,E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D,CAAC;QACD,IAAI,CAAC,SAAS,CAAC,WAAW,EAAE,CAAC;YAC3B,MAAM,WAAW,CAAC,yCAAyC,CAAC,CAAC;QAC/D,CAAC;IACH,CAAC;CACF;AA7SD,8DA6SC;AAED,SAAS,cAAc,CAAC,GAAQ;IAC9B,aAAa;IACb,IAAI,GAAG,CAAC,SAAS,KAAK,eAAe,EAAE,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,eAAe;IACf,IAAI,GAAG,CAAC,IAAI,KAAK,aAAa,IAAI,GAAG,CAAC,IAAI,KAAK,cAAc,EAAE,CAAC;QAC9D,OAAO,IAAI,CAAC;IACd,CAAC;IAED,6NAA6N;IAC7N,4CAA4C;IAC5C,IAAI,GAAG,CAAC,UAAU,KAAK,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,GAAG,EAAE,CAAC;QAC/C,IAAI,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,CAAC;YACxC,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\n\nimport type { TokenCredentialOptions } from \"../../tokenCredentialOptions.js\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { ManagedIdentityApplication } from \"@azure/msal-node\";\nimport { IdentityClient } from \"../../client/identityClient.js\";\nimport { AuthenticationRequiredError, CredentialUnavailableError } from \"../../errors.js\";\nimport { getMSALLogLevel, defaultLoggerCallback } from \"../../msal/utils.js\";\nimport { imdsRetryPolicy } from \"./imdsRetryPolicy.js\";\nimport type { MSIConfiguration } from \"./models.js\";\nimport { formatSuccess, formatError, credentialLogger } from \"../../util/logging.js\";\nimport { tracingClient } from \"../../util/tracing.js\";\nimport { imdsMsi } from \"./imdsMsi.js\";\nimport { tokenExchangeMsi } from \"./tokenExchangeMsi.js\";\nimport { mapScopesToResource, serviceFabricErrorMessage } from \"./utils.js\";\nimport type { MsalToken, ValidMsalToken } from \"../../msal/types.js\";\nimport type {\n ManagedIdentityCredentialClientIdOptions,\n ManagedIdentityCredentialObjectIdOptions,\n ManagedIdentityCredentialResourceIdOptions,\n} from \"./options.js\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential\");\n\n/**\n * Attempts authentication using a managed identity available at the deployment environment.\n * This authentication type works in Azure VMs, App Service instances, Azure Functions applications,\n * Azure Kubernetes Services, Azure Service Fabric instances and inside of the Azure Cloud Shell.\n *\n * More information about configuring managed identities can be found here:\n * https://learn.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview\n */\nexport class ManagedIdentityCredential implements TokenCredential {\n private managedIdentityApp: ManagedIdentityApplication;\n private identityClient: IdentityClient;\n private clientId?: string;\n private resourceId?: string;\n private objectId?: string;\n private msiRetryConfig: MSIConfiguration[\"retryConfig\"] = {\n maxRetries: 5,\n startDelayInMs: 800,\n intervalIncrement: 2,\n };\n private isAvailableIdentityClient: IdentityClient;\n\n /**\n * Creates an instance of ManagedIdentityCredential with the client ID of a\n * user-assigned identity, or app registration (when working with AKS pod-identity).\n *\n * @param clientId - The client ID of the user-assigned identity, or app registration (when working with AKS pod-identity).\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(clientId: string, options?: TokenCredentialOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with a client ID\n *\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialClientIdOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with a resource ID\n *\n * @param options - Options for configuring the resource which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialResourceIdOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with an object ID\n *\n * @param options - Options for configuring the resource which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialObjectIdOptions);\n /**\n * @internal\n * @hidden\n */\n constructor(\n clientIdOrOptions?:\n | string\n | ManagedIdentityCredentialClientIdOptions\n | ManagedIdentityCredentialResourceIdOptions\n | ManagedIdentityCredentialObjectIdOptions,\n options?: TokenCredentialOptions,\n ) {\n let _options: TokenCredentialOptions;\n if (typeof clientIdOrOptions === \"string\") {\n this.clientId = clientIdOrOptions;\n _options = options ?? {};\n } else {\n this.clientId = (clientIdOrOptions as ManagedIdentityCredentialClientIdOptions)?.clientId;\n _options = clientIdOrOptions ?? {};\n }\n this.resourceId = (_options as ManagedIdentityCredentialResourceIdOptions)?.resourceId;\n this.objectId = (_options as ManagedIdentityCredentialObjectIdOptions)?.objectId;\n\n // For JavaScript users.\n const providedIds = [\n { key: \"clientId\", value: this.clientId },\n { key: \"resourceId\", value: this.resourceId },\n { key: \"objectId\", value: this.objectId },\n ].filter((id) => id.value);\n if (providedIds.length > 1) {\n throw new Error(\n `ManagedIdentityCredential: only one of 'clientId', 'resourceId', or 'objectId' can be provided. Received values: ${JSON.stringify(\n { clientId: this.clientId, resourceId: this.resourceId, objectId: this.objectId },\n )}`,\n );\n }\n\n // ManagedIdentity uses http for local requests\n _options.allowInsecureConnection = true;\n\n if (_options.retryOptions?.maxRetries !== undefined) {\n this.msiRetryConfig.maxRetries = _options.retryOptions.maxRetries;\n }\n\n this.identityClient = new IdentityClient({\n ..._options,\n additionalPolicies: [{ policy: imdsRetryPolicy(this.msiRetryConfig), position: \"perCall\" }],\n });\n\n this.managedIdentityApp = new ManagedIdentityApplication({\n managedIdentityIdParams: {\n userAssignedClientId: this.clientId,\n userAssignedResourceId: this.resourceId,\n userAssignedObjectId: this.objectId,\n },\n system: {\n disableInternalRetries: true,\n networkClient: this.identityClient,\n loggerOptions: {\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: _options.loggingOptions?.enableUnsafeSupportLogging,\n loggerCallback: defaultLoggerCallback(logger),\n },\n },\n });\n\n this.isAvailableIdentityClient = new IdentityClient({\n ..._options,\n retryOptions: {\n maxRetries: 0,\n },\n });\n\n const managedIdentitySource = this.managedIdentityApp.getManagedIdentitySource();\n // CloudShell MSI will ignore any user-assigned identity passed as parameters. To avoid confusion, we prevent this from happening as early as possible.\n if (managedIdentitySource === \"CloudShell\") {\n if (this.clientId || this.resourceId || this.objectId) {\n logger.warning(\n `CloudShell MSI detected with user-provided IDs - throwing. Received values: ${JSON.stringify(\n {\n clientId: this.clientId,\n resourceId: this.resourceId,\n objectId: this.objectId,\n },\n )}.`,\n );\n throw new CredentialUnavailableError(\n \"ManagedIdentityCredential: Specifying a user-assigned managed identity is not supported for CloudShell at runtime. When using Managed Identity in CloudShell, omit the clientId, resourceId, and objectId parameters.\",\n );\n }\n }\n\n // ServiceFabric does not support specifying user-assigned managed identity by client ID or resource ID. The managed identity selected is based on the resource configuration.\n if (managedIdentitySource === \"ServiceFabric\") {\n if (this.clientId || this.resourceId || this.objectId) {\n logger.warning(\n `Service Fabric detected with user-provided IDs - throwing. Received values: ${JSON.stringify(\n {\n clientId: this.clientId,\n resourceId: this.resourceId,\n objectId: this.objectId,\n },\n )}.`,\n );\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: ${serviceFabricErrorMessage}`,\n );\n }\n }\n\n logger.info(`Using ${managedIdentitySource} managed identity.`);\n\n // Check if either clientId, resourceId or objectId was provided and log the value used\n if (providedIds.length === 1) {\n const { key, value } = providedIds[0];\n logger.info(`${managedIdentitySource} with ${key}: ${value}`);\n }\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@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 logger.getToken.info(\"Using the MSAL provider for Managed Identity.\");\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Multiple scopes are not supported. Scopes: ${JSON.stringify(\n scopes,\n )}`,\n );\n }\n\n return tracingClient.withSpan(\"ManagedIdentityCredential.getToken\", options, async () => {\n try {\n const isTokenExchangeMsi = await tokenExchangeMsi.isAvailable(this.clientId);\n\n // Most scenarios are handled by MSAL except for two:\n // AKS pod identity - MSAL does not implement the token exchange flow.\n // IMDS Endpoint probing - MSAL does not do any probing before trying to get a token.\n // As a DefaultAzureCredential optimization we probe the IMDS endpoint with a short timeout and no retries before actually trying to get a token\n // We will continue to implement these features in the Identity library.\n\n const identitySource = this.managedIdentityApp.getManagedIdentitySource();\n const isImdsMsi = identitySource === \"DefaultToImds\" || identitySource === \"Imds\"; // Neither actually checks that IMDS endpoint is available, just that it's the source the MSAL _would_ try to use.\n\n logger.getToken.info(`MSAL Identity source: ${identitySource}`);\n\n if (isTokenExchangeMsi) {\n // In the AKS scenario we will use the existing tokenExchangeMsi indefinitely.\n logger.getToken.info(\"Using the token exchange managed identity.\");\n const result = await tokenExchangeMsi.getToken({\n scopes,\n clientId: this.clientId,\n identityClient: this.identityClient,\n retryConfig: this.msiRetryConfig,\n resourceId: this.resourceId,\n });\n\n if (result === null) {\n throw new CredentialUnavailableError(\n \"Attempted to use the token exchange managed identity, but received a null response.\",\n );\n }\n\n return result;\n } else if (isImdsMsi) {\n // In the IMDS scenario we will probe the IMDS endpoint to ensure it's available before trying to get a token.\n // If the IMDS endpoint is not available and this is the source that MSAL will use, we will fail-fast with an error that tells DAC to move to the next credential.\n logger.getToken.info(\"Using the IMDS endpoint to probe for availability.\");\n const isAvailable = await imdsMsi.isAvailable({\n scopes,\n clientId: this.clientId,\n getTokenOptions: options,\n identityClient: this.isAvailableIdentityClient,\n resourceId: this.resourceId,\n });\n\n if (!isAvailable) {\n throw new CredentialUnavailableError(\n `Attempted to use the IMDS endpoint, but it is not available.`,\n );\n }\n }\n\n // If we got this far, it means:\n // - This is not a tokenExchangeMsi,\n // - We already probed for IMDS endpoint availability and failed-fast if it's unreachable.\n // We can proceed normally by calling MSAL for a token.\n logger.getToken.info(\"Calling into MSAL for managed identity token.\");\n const token = await this.managedIdentityApp.acquireToken({\n resource,\n });\n\n this.ensureValidMsalToken(scopes, token, options);\n logger.getToken.info(formatSuccess(scopes));\n\n return {\n expiresOnTimestamp: token.expiresOn.getTime(),\n token: token.accessToken,\n refreshAfterTimestamp: token.refreshOn?.getTime(),\n tokenType: \"Bearer\",\n } as AccessToken;\n } catch (err: any) {\n logger.getToken.error(formatError(scopes, err));\n\n // AuthenticationRequiredError described as Error to enforce authentication after trying to retrieve a token silently.\n // TODO: why would this _ever_ happen considering we're not trying the silent request in this flow?\n if (err.name === \"AuthenticationRequiredError\") {\n throw err;\n }\n\n if (isNetworkError(err)) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Network unreachable. Message: ${err.message}`,\n { cause: err },\n );\n }\n\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Authentication failed. Message ${err.message}`,\n { cause: err },\n );\n }\n });\n }\n\n /**\n * Ensures the validity of the MSAL token\n */\n private ensureValidMsalToken(\n scopes: string | string[],\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions,\n ): asserts msalToken is ValidMsalToken {\n const createError = (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 createError(\"No response.\");\n }\n if (!msalToken.expiresOn) {\n throw createError(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw createError(`Response had no \"accessToken\" property.`);\n }\n }\n}\n\nfunction isNetworkError(err: any): boolean {\n // MSAL error\n if (err.errorCode === \"network_error\") {\n return true;\n }\n\n // Probe errors\n if (err.code === \"ENETUNREACH\" || err.code === \"EHOSTUNREACH\") {\n return true;\n }\n\n // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\" or \"A socket operation was attempted to an unreachable host\"\n // rather than just timing out, as expected.\n if (err.statusCode === 403 || err.code === 403) {\n if (err.message.includes(\"unreachable\")) {\n return true;\n }\n }\n\n return false;\n}\n"]}
|
@@ -2,7 +2,7 @@ import type { GetTokenOptions } from "@azure/core-auth";
|
|
2
2
|
/**
|
3
3
|
* See the official documentation for more details:
|
4
4
|
*
|
5
|
-
* https://learn.microsoft.com/
|
5
|
+
* https://learn.microsoft.com/azure/active-directory/develop/v1-protocols-oauth-code#error-response-1
|
6
6
|
*
|
7
7
|
* NOTE: This documentation is for v1 OAuth support but the same error
|
8
8
|
* response details still apply to v2.
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAyDlC,SAAS,eAAe,CAAC,aAAkB;IACzC,OAAO,CACL,aAAa;QACb,OAAO,aAAa,CAAC,KAAK,KAAK,QAAQ;QACvC,OAAO,aAAa,CAAC,iBAAiB,KAAK,QAAQ,CACpD,CAAC;AACJ,CAAC;AAED;;GAEG;AACU,QAAA,8BAA8B,GAAG,4BAA4B,CAAC;AAE3E;;;;GAIG;AACH,MAAa,0BAA2B,SAAQ,KAAK;IACnD,YAAY,OAAgB,EAAE,OAA6B;QACzD,2JAA2J;QAC3J,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,sCAA8B,CAAC;IAC7C,CAAC;CACF;AAND,gEAMC;AAED;;GAEG;AACU,QAAA,uBAAuB,GAAG,qBAAqB,CAAC;AAE7D;;;;GAIG;AACH,MAAa,mBAAoB,SAAQ,KAAK;IAW5C,YACE,UAAkB,EAClB,SAA6C,EAC7C,OAA6B;QAE7B,IAAI,aAAa,GAAkB;YACjC,KAAK,EAAE,SAAS;YAChB,gBAAgB,EAAE,oEAAoE;SACvF,CAAC;QAEF,IAAI,eAAe,CAAC,SAAS,CAAC,EAAE,CAAC;YAC/B,aAAa,GAAG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KAAK,CAAC,GAAG,YAAY,KAAK,WAAW,EAAE,CAAC,CAAC;QACzC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QAErB,iDAAiD;QACjD,IAAI,CAAC,IAAI,GAAG,wCAAgC,CAAC;IAC/C,CAAC;CACF;AAfD,oEAeC;AAED,SAAS,wCAAwC,CAAC,SAA6B;IAC7E,OAAO;QACL,KAAK,EAAE,SAAS,CAAC,KAAK;QACtB,gBAAgB,EAAE,SAAS,CAAC,iBAAiB;QAC7C,aAAa,EAAE,SAAS,CAAC,cAAc;QACvC,UAAU,EAAE,SAAS,CAAC,WAAW;QACjC,SAAS,EAAE,SAAS,CAAC,SAAS;QAC9B,OAAO,EAAE,SAAS,CAAC,QAAQ;KAC5B,CAAC;AACJ,CAAC;AAwBD;;GAEG;AACH,MAAa,2BAA4B,SAAQ,KAAK;IAUpD;IACE;;OAEG;IACH,OAA2C;QAE3C,KAAK,CACH,OAAO,CAAC,OAAO;QACf,2JAA2J;QAC3J,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CACrD,CAAC;QACF,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC7B,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC;QAC/C,IAAI,CAAC,IAAI,GAAG,6BAA6B,CAAC;IAC5C,CAAC;CACF;AAzBD,kEAyBC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { GetTokenOptions } from \"@azure/core-auth\";\n\n/**\n * See the official documentation for more details:\n *\n * https://learn.microsoft.com/en-us/azure/active-directory/develop/v1-protocols-oauth-code#error-response-1\n *\n * NOTE: This documentation is for v1 OAuth support but the same error\n * response details still apply to v2.\n */\nexport interface ErrorResponse {\n /**\n * The string identifier for the error.\n */\n error: string;\n\n /**\n * The error's description.\n */\n errorDescription: string;\n\n /**\n * An array of codes pertaining to the error(s) that occurred.\n */\n errorCodes?: number[];\n\n /**\n * The timestamp at which the error occurred.\n */\n timestamp?: string;\n\n /**\n * The trace identifier for this error occurrence.\n */\n traceId?: string;\n\n /**\n * The correlation ID to be used for tracking the source of the error.\n */\n correlationId?: string;\n}\n\n/**\n * Used for internal deserialization of OAuth responses. Public model is ErrorResponse\n * @internal\n */\nexport interface OAuthErrorResponse {\n error: string;\n error_description: string;\n error_codes?: number[];\n timestamp?: string;\n trace_id?: string;\n correlation_id?: string;\n}\n\nfunction isErrorResponse(errorResponse: any): errorResponse is OAuthErrorResponse {\n return (\n errorResponse &&\n typeof errorResponse.error === \"string\" &&\n typeof errorResponse.error_description === \"string\"\n );\n}\n\n/**\n * The Error.name value of an CredentialUnavailable\n */\nexport const CredentialUnavailableErrorName = \"CredentialUnavailableError\";\n\n/**\n * This signifies that the credential that was tried in a chained credential\n * was not available to be used as the credential. Rather than treating this as\n * an error that should halt the chain, it's caught and the chain continues\n */\nexport class CredentialUnavailableError extends Error {\n constructor(message?: string, options?: { cause?: unknown }) {\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n super(message, options);\n this.name = CredentialUnavailableErrorName;\n }\n}\n\n/**\n * The Error.name value of an AuthenticationError\n */\nexport const AuthenticationErrorName = \"AuthenticationError\";\n\n/**\n * Provides details about a failure to authenticate with Azure Active\n * Directory. The `errorResponse` field contains more details about\n * the specific failure.\n */\nexport class AuthenticationError extends Error {\n /**\n * The HTTP status code returned from the authentication request.\n */\n public readonly statusCode: number;\n\n /**\n * The error response details.\n */\n public readonly errorResponse: ErrorResponse;\n\n constructor(\n statusCode: number,\n errorBody: object | string | undefined | null,\n options?: { cause?: unknown },\n ) {\n let errorResponse: ErrorResponse = {\n error: \"unknown\",\n errorDescription: \"An unknown error occurred and no additional details are available.\",\n };\n\n if (isErrorResponse(errorBody)) {\n errorResponse = convertOAuthErrorResponseToErrorResponse(errorBody);\n } else if (typeof errorBody === \"string\") {\n try {\n // Most error responses will contain JSON-formatted error details\n // in the response body\n const oauthErrorResponse: OAuthErrorResponse = JSON.parse(errorBody);\n errorResponse = convertOAuthErrorResponseToErrorResponse(oauthErrorResponse);\n } catch (e: any) {\n if (statusCode === 400) {\n errorResponse = {\n error: \"invalid_request\",\n errorDescription: `The service indicated that the request was invalid.\\n\\n${errorBody}`,\n };\n } else {\n errorResponse = {\n error: \"unknown_error\",\n errorDescription: `An unknown error has occurred. Response body:\\n\\n${errorBody}`,\n };\n }\n }\n } else {\n errorResponse = {\n error: \"unknown_error\",\n errorDescription: \"An unknown error occurred and no additional details are available.\",\n };\n }\n\n super(\n `${errorResponse.error} Status code: ${statusCode}\\nMore details:\\n${errorResponse.errorDescription},`,\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n options,\n );\n this.statusCode = statusCode;\n this.errorResponse = errorResponse;\n\n // Ensure that this type reports the correct name\n this.name = AuthenticationErrorName;\n }\n}\n\n/**\n * The Error.name value of an AggregateAuthenticationError\n */\nexport const AggregateAuthenticationErrorName = \"AggregateAuthenticationError\";\n\n/**\n * Provides an `errors` array containing {@link AuthenticationError} instance\n * for authentication failures from credentials in a {@link ChainedTokenCredential}.\n */\nexport class AggregateAuthenticationError extends Error {\n /**\n * The array of error objects that were thrown while trying to authenticate\n * with the credentials in a {@link ChainedTokenCredential}.\n */\n public errors: any[];\n\n constructor(errors: any[], errorMessage?: string) {\n const errorDetail = errors.join(\"\\n\");\n super(`${errorMessage}\\n${errorDetail}`);\n this.errors = errors;\n\n // Ensure that this type reports the correct name\n this.name = AggregateAuthenticationErrorName;\n }\n}\n\nfunction convertOAuthErrorResponseToErrorResponse(errorBody: OAuthErrorResponse): ErrorResponse {\n return {\n error: errorBody.error,\n errorDescription: errorBody.error_description,\n correlationId: errorBody.correlation_id,\n errorCodes: errorBody.error_codes,\n timestamp: errorBody.timestamp,\n traceId: errorBody.trace_id,\n };\n}\n\n/**\n * Optional parameters to the {@link AuthenticationRequiredError}\n */\nexport interface AuthenticationRequiredErrorOptions {\n /**\n * The list of scopes for which the token will have access.\n */\n scopes: string[];\n /**\n * The options passed to the getToken request.\n */\n getTokenOptions?: GetTokenOptions;\n /**\n * The message of the error.\n */\n message?: string;\n /**\n * The underlying cause, if any, that caused the authentication to fail.\n */\n cause?: unknown;\n}\n\n/**\n * Error used to enforce authentication after trying to retrieve a token silently.\n */\nexport class AuthenticationRequiredError extends Error {\n /**\n * The list of scopes for which the token will have access.\n */\n public scopes: string[];\n /**\n * The options passed to the getToken request.\n */\n public getTokenOptions?: GetTokenOptions;\n\n constructor(\n /**\n * Optional parameters. A message can be specified. The {@link GetTokenOptions} of the request can also be specified to more easily associate the error with the received parameters.\n */\n options: AuthenticationRequiredErrorOptions,\n ) {\n super(\n options.message,\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n options.cause ? { cause: options.cause } : undefined,\n );\n this.scopes = options.scopes;\n this.getTokenOptions = options.getTokenOptions;\n this.name = \"AuthenticationRequiredError\";\n }\n}\n"]}
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAyDlC,SAAS,eAAe,CAAC,aAAkB;IACzC,OAAO,CACL,aAAa;QACb,OAAO,aAAa,CAAC,KAAK,KAAK,QAAQ;QACvC,OAAO,aAAa,CAAC,iBAAiB,KAAK,QAAQ,CACpD,CAAC;AACJ,CAAC;AAED;;GAEG;AACU,QAAA,8BAA8B,GAAG,4BAA4B,CAAC;AAE3E;;;;GAIG;AACH,MAAa,0BAA2B,SAAQ,KAAK;IACnD,YAAY,OAAgB,EAAE,OAA6B;QACzD,2JAA2J;QAC3J,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,sCAA8B,CAAC;IAC7C,CAAC;CACF;AAND,gEAMC;AAED;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yright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { GetTokenOptions } from \"@azure/core-auth\";\n\n/**\n * See the official documentation for more details:\n *\n * https://learn.microsoft.com/azure/active-directory/develop/v1-protocols-oauth-code#error-response-1\n *\n * NOTE: This documentation is for v1 OAuth support but the same error\n * response details still apply to v2.\n */\nexport interface ErrorResponse {\n /**\n * The string identifier for the error.\n */\n error: string;\n\n /**\n * The error's description.\n */\n errorDescription: string;\n\n /**\n * An array of codes pertaining to the error(s) that occurred.\n */\n errorCodes?: number[];\n\n /**\n * The timestamp at which the error occurred.\n */\n timestamp?: string;\n\n /**\n * The trace identifier for this error occurrence.\n */\n traceId?: string;\n\n /**\n * The correlation ID to be used for tracking the source of the error.\n */\n correlationId?: string;\n}\n\n/**\n * Used for internal deserialization of OAuth responses. Public model is ErrorResponse\n * @internal\n */\nexport interface OAuthErrorResponse {\n error: string;\n error_description: string;\n error_codes?: number[];\n timestamp?: string;\n trace_id?: string;\n correlation_id?: string;\n}\n\nfunction isErrorResponse(errorResponse: any): errorResponse is OAuthErrorResponse {\n return (\n errorResponse &&\n typeof errorResponse.error === \"string\" &&\n typeof errorResponse.error_description === \"string\"\n );\n}\n\n/**\n * The Error.name value of an CredentialUnavailable\n */\nexport const CredentialUnavailableErrorName = \"CredentialUnavailableError\";\n\n/**\n * This signifies that the credential that was tried in a chained credential\n * was not available to be used as the credential. Rather than treating this as\n * an error that should halt the chain, it's caught and the chain continues\n */\nexport class CredentialUnavailableError extends Error {\n constructor(message?: string, options?: { cause?: unknown }) {\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n super(message, options);\n this.name = CredentialUnavailableErrorName;\n }\n}\n\n/**\n * The Error.name value of an AuthenticationError\n */\nexport const AuthenticationErrorName = \"AuthenticationError\";\n\n/**\n * Provides details about a failure to authenticate with Azure Active\n * Directory. The `errorResponse` field contains more details about\n * the specific failure.\n */\nexport class AuthenticationError extends Error {\n /**\n * The HTTP status code returned from the authentication request.\n */\n public readonly statusCode: number;\n\n /**\n * The error response details.\n */\n public readonly errorResponse: ErrorResponse;\n\n constructor(\n statusCode: number,\n errorBody: object | string | undefined | null,\n options?: { cause?: unknown },\n ) {\n let errorResponse: ErrorResponse = {\n error: \"unknown\",\n errorDescription: \"An unknown error occurred and no additional details are available.\",\n };\n\n if (isErrorResponse(errorBody)) {\n errorResponse = convertOAuthErrorResponseToErrorResponse(errorBody);\n } else if (typeof errorBody === \"string\") {\n try {\n // Most error responses will contain JSON-formatted error details\n // in the response body\n const oauthErrorResponse: OAuthErrorResponse = JSON.parse(errorBody);\n errorResponse = convertOAuthErrorResponseToErrorResponse(oauthErrorResponse);\n } catch (e: any) {\n if (statusCode === 400) {\n errorResponse = {\n error: \"invalid_request\",\n errorDescription: `The service indicated that the request was invalid.\\n\\n${errorBody}`,\n };\n } else {\n errorResponse = {\n error: \"unknown_error\",\n errorDescription: `An unknown error has occurred. Response body:\\n\\n${errorBody}`,\n };\n }\n }\n } else {\n errorResponse = {\n error: \"unknown_error\",\n errorDescription: \"An unknown error occurred and no additional details are available.\",\n };\n }\n\n super(\n `${errorResponse.error} Status code: ${statusCode}\\nMore details:\\n${errorResponse.errorDescription},`,\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n options,\n );\n this.statusCode = statusCode;\n this.errorResponse = errorResponse;\n\n // Ensure that this type reports the correct name\n this.name = AuthenticationErrorName;\n }\n}\n\n/**\n * The Error.name value of an AggregateAuthenticationError\n */\nexport const AggregateAuthenticationErrorName = \"AggregateAuthenticationError\";\n\n/**\n * Provides an `errors` array containing {@link AuthenticationError} instance\n * for authentication failures from credentials in a {@link ChainedTokenCredential}.\n */\nexport class AggregateAuthenticationError extends Error {\n /**\n * The array of error objects that were thrown while trying to authenticate\n * with the credentials in a {@link ChainedTokenCredential}.\n */\n public errors: any[];\n\n constructor(errors: any[], errorMessage?: string) {\n const errorDetail = errors.join(\"\\n\");\n super(`${errorMessage}\\n${errorDetail}`);\n this.errors = errors;\n\n // Ensure that this type reports the correct name\n this.name = AggregateAuthenticationErrorName;\n }\n}\n\nfunction convertOAuthErrorResponseToErrorResponse(errorBody: OAuthErrorResponse): ErrorResponse {\n return {\n error: errorBody.error,\n errorDescription: errorBody.error_description,\n correlationId: errorBody.correlation_id,\n errorCodes: errorBody.error_codes,\n timestamp: errorBody.timestamp,\n traceId: errorBody.trace_id,\n };\n}\n\n/**\n * Optional parameters to the {@link AuthenticationRequiredError}\n */\nexport interface AuthenticationRequiredErrorOptions {\n /**\n * The list of scopes for which the token will have access.\n */\n scopes: string[];\n /**\n * The options passed to the getToken request.\n */\n getTokenOptions?: GetTokenOptions;\n /**\n * The message of the error.\n */\n message?: string;\n /**\n * The underlying cause, if any, that caused the authentication to fail.\n */\n cause?: unknown;\n}\n\n/**\n * Error used to enforce authentication after trying to retrieve a token silently.\n */\nexport class AuthenticationRequiredError extends Error {\n /**\n * The list of scopes for which the token will have access.\n */\n public scopes: string[];\n /**\n * The options passed to the getToken request.\n */\n public getTokenOptions?: GetTokenOptions;\n\n constructor(\n /**\n * Optional parameters. A message can be specified. The {@link GetTokenOptions} of the request can also be specified to more easily associate the error with the received parameters.\n */\n options: AuthenticationRequiredErrorOptions,\n ) {\n super(\n options.message,\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n options.cause ? { cause: options.cause } : undefined,\n );\n this.scopes = options.scopes;\n this.getTokenOptions = options.getTokenOptions;\n this.name = \"AuthenticationRequiredError\";\n }\n}\n"]}
|
@@ -12,7 +12,7 @@ export interface MsalBrowserClient {
|
|
12
12
|
}
|
13
13
|
/**
|
14
14
|
* Uses MSAL Browser 2.X for browser authentication,
|
15
|
-
* which uses the [Auth Code Flow](https://learn.microsoft.com/
|
15
|
+
* which uses the [Auth Code Flow](https://learn.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow).
|
16
16
|
* @internal
|
17
17
|
*/
|
18
18
|
export declare function createMsalBrowserClient(options: MsalBrowserFlowOptions): MsalBrowserClient;
|
@@ -49,7 +49,7 @@ function generateMsalBrowserConfiguration(options) {
|
|
49
49
|
const redirectHash = isLocationDefined ? self.location.hash : undefined;
|
50
50
|
/**
|
51
51
|
* Uses MSAL Browser 2.X for browser authentication,
|
52
|
-
* which uses the [Auth Code Flow](https://learn.microsoft.com/
|
52
|
+
* which uses the [Auth Code Flow](https://learn.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow).
|
53
53
|
* @internal
|
54
54
|
*/
|
55
55
|
function createMsalBrowserClient(options) {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"msalBrowserCommon.js","sourceRoot":"","sources":["../../../../src/msal/browserFlows/msalBrowserCommon.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;AAmFlC,0DAyPC;;AA1UD,yEAAmD;AAGnD,0CASqB;AAIrB,+CAA0F;AAE1F,0CAA4C;AAC5C,sDAAsD;AACtD,kEAIqC;AACrC,qDAAqD;AAErD,uCAAuC;AACvC,gDAAgD;AAChD,MAAM,iBAAiB,GAAG,OAAO,IAAI,KAAK,WAAW,IAAI,IAAI,CAAC,QAAQ,KAAK,SAAS,CAAC;AAErF;;;GAGG;AACH,SAAS,gCAAgC,CACvC,OAA+B;;IAE/B,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,8BAAe,CAAC;IACrD,MAAM,SAAS,GAAG,IAAA,uBAAY,EAAC,QAAQ,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC;IAChE,OAAO;QACL,IAAI,EAAE;YACJ,QAAQ,EAAE,OAAO,CAAC,QAAS;YAC3B,SAAS;YACT,gBAAgB,EAAE,IAAA,8BAAmB,EAAC,QAAQ,EAAE,SAAS,EAAE,OAAO,CAAC,wBAAwB,CAAC;YAC5F,qDAAqD;YACrD,yCAAyC;YACzC,kEAAkE;YAClE,WAAW,EAAE,OAAO,CAAC,WAAW,IAAI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IACH,KAAK,UAAU,QAAQ,CACrB,MAAgB,EAChB,kBAAiD,EAAE;QAEnD,MAAM,gBAAgB,GACpB,IAAA,4CAAyB,EAAC,QAAQ,EAAE,eAAe,EAAE,4BAA4B,CAAC;YAClF,QAAQ,CAAC;QAEX,IAAI,CAAC,eAAe,CAAC,SAAS,EAAE,CAAC;YAC/B,eAAe,CAAC,SAAS,GAAG,IAAA,uBAAY,EAAC,gBAAgB,EAAE,aAAa,CAAC,CAAC;QAC5E,CAAC;QAED,uDAAuD;QACvD,MAAM,cAAc,EAAE,CAAC;QAEvB,IAAI,CAAC,CAAC,MAAM,gBAAgB,EAAE,CAAC,IAAI,CAAC,8BAA8B,EAAE,CAAC;YACnE,MAAM,KAAK,CAAC,MAAM,CAAC,CAAC;QACtB,CAAC;QAED,8EAA8E;QAC9E,IAAI,CAAC;YACH,OAAO,MAAM,cAAc,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;QACvD,CAAC;QAAC,OAAO,GAAQ,EAAE,CAAC;YAClB,IAAI,GAAG,CAAC,IAAI,KAAK,6BAA6B,EAAE,CAAC;gBAC/C,MAAM,GAAG,CAAC;YACZ,CAAC;YACD,IAAI,eAAe,aAAf,eAAe,uBAAf,eAAe,CAAE,8BAA8B,EAAE,CAAC;gBACpD,MAAM,IAAI,uCAA2B,CAAC;oBACpC,MAAM;oBACN,eAAe;oBACf,OAAO,EACL,qFAAqF;iBACxF,CAAC,CAAC;YACL,CAAC;YACD,MAAM,CAAC,IAAI,CAAC,oEAAoE,UAAU,EAAE,CAAC,CAAC;YAC9F,OAAO,mBAAmB,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;QACtD,CAAC;IACH,CAAC;IACD,OAAO;QACL,gBAAgB;QAChB,QAAQ;KACT,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport * as msalBrowser from \"@azure/msal-browser\";\n\nimport type { MsalBrowserFlowOptions } from \"./msalBrowserOptions.js\";\nimport {\n defaultLoggerCallback,\n ensureValidMsalToken,\n getAuthority,\n getKnownAuthorities,\n getMSALLogLevel,\n handleMsalError,\n msalToPublic,\n publicToMsal,\n} from \"../utils.js\";\n\nimport type { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport type { AuthenticationRecord, MsalResult } from \"../types.js\";\nimport { AuthenticationRequiredError, CredentialUnavailableError } from \"../../errors.js\";\nimport type { CredentialFlowGetTokenOptions } from \"../credentials.js\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { formatSuccess } from \"../../util/logging.js\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n resolveTenantId,\n} from \"../../util/tenantIdUtils.js\";\nimport { DefaultTenantId } from \"../../constants.js\";\n\n// We keep a copy of the redirect hash.\n// Check if self and location object is defined.\nconst isLocationDefined = typeof self !== \"undefined\" && self.location !== undefined;\n\n/**\n * Generates a MSAL configuration that generally works for browsers\n * @internal\n */\nfunction generateMsalBrowserConfiguration(\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(tenantId, authority, options.disableInstanceDiscovery),\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 || (isLocationDefined ? self.location.origin : undefined),\n },\n cache: {\n cacheLocation: \"sessionStorage\",\n storeAuthStateInCookie: true, // Set to true to improve the experience on IE11 and Edge.\n },\n system: {\n loggerOptions: {\n loggerCallback: defaultLoggerCallback(options.logger, \"Browser\"),\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: options.loggingOptions?.enableUnsafeSupportLogging,\n },\n },\n };\n}\n\n/**\n * Methods that are used by InteractiveBrowserCredential\n * @internal\n */\nexport interface MsalBrowserClient {\n getActiveAccount(): Promise<AuthenticationRecord | undefined>;\n getToken(scopes: string[], options: CredentialFlowGetTokenOptions): Promise<AccessToken>;\n}\n\n// We keep a copy of the redirect hash.\nconst redirectHash = isLocationDefined ? self.location.hash : undefined;\n\n/**\n * Uses MSAL Browser 2.X for browser authentication,\n * which uses the [Auth Code Flow](https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow).\n * @internal\n */\nexport function createMsalBrowserClient(options: MsalBrowserFlowOptions): MsalBrowserClient {\n const loginStyle = options.loginStyle;\n if (!options.clientId) {\n throw new CredentialUnavailableError(\"A client ID is required in browsers\");\n }\n const clientId = options.clientId;\n const logger = options.logger;\n const tenantId = resolveTenantId(logger, options.tenantId, options.clientId);\n const additionallyAllowedTenantIds: string[] = resolveAdditionallyAllowedTenantIds(\n options?.tokenCredentialOptions?.additionallyAllowedTenants,\n );\n const authorityHost = options.authorityHost;\n const msalConfig = generateMsalBrowserConfiguration(options);\n const disableAutomaticAuthentication = options.disableAutomaticAuthentication;\n const loginHint = options.loginHint;\n\n let account: AuthenticationRecord | undefined;\n if (options.authenticationRecord) {\n account = {\n ...options.authenticationRecord,\n tenantId,\n };\n }\n\n // This variable should only be used through calling `getApp` function\n let app: msalBrowser.IPublicClientApplication;\n /**\n * Return the MSAL account if not set yet\n * @returns MSAL application\n */\n async function getApp(): Promise<msalBrowser.IPublicClientApplication> {\n if (!app) {\n // Prepare the MSAL application\n app = await msalBrowser.PublicClientApplication.createPublicClientApplication(msalConfig);\n\n // setting the account right after the app is created.\n if (account) {\n app.setActiveAccount(publicToMsal(account));\n }\n }\n\n return app;\n }\n\n /**\n * Loads the account based on the result of the authentication.\n * If no result was received, tries to load the account from the cache.\n * @param result - Result object received from MSAL.\n */\n async function handleBrowserResult(\n result?: msalBrowser.AuthenticationResult,\n ): Promise<AuthenticationRecord | undefined> {\n try {\n const msalApp = await getApp();\n if (result && result.account) {\n logger.info(`MSAL Browser V2 authentication successful.`);\n msalApp.setActiveAccount(result.account);\n return msalToPublic(clientId, result.account);\n }\n } catch (e: any) {\n logger.info(`Failed to acquire token through MSAL. ${e.message}`);\n }\n return;\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 function handleResult(\n scopes: string | string[],\n result?: MsalResult,\n getTokenOptions?: GetTokenOptions,\n ): AccessToken {\n if (result?.account) {\n account = msalToPublic(clientId, result.account);\n }\n ensureValidMsalToken(scopes, result, getTokenOptions);\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: result.accessToken,\n expiresOnTimestamp: result.expiresOn.getTime(),\n refreshAfterTimestamp: result.refreshOn?.getTime(),\n tokenType: \"Bearer\",\n };\n }\n\n /**\n * Uses MSAL to handle the redirect.\n */\n async function handleRedirect(): Promise<AuthenticationRecord | undefined> {\n const msalApp = await getApp();\n return handleBrowserResult((await msalApp.handleRedirectPromise(redirectHash)) || undefined);\n }\n\n /**\n * Uses MSAL to retrieve the active account.\n */\n async function getActiveAccount(): Promise<AuthenticationRecord | undefined> {\n const msalApp = await getApp();\n const activeAccount = msalApp.getActiveAccount();\n if (!activeAccount) {\n return;\n }\n return msalToPublic(clientId, activeAccount);\n }\n\n /**\n * Uses MSAL to trigger a redirect or a popup login.\n */\n async function login(scopes: string | string[] = []): Promise<AuthenticationRecord | undefined> {\n const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];\n const loginRequest: msalBrowser.RedirectRequest = {\n scopes: arrayScopes,\n loginHint: loginHint,\n };\n const msalApp = await getApp();\n switch (loginStyle) {\n case \"redirect\": {\n await app.loginRedirect(loginRequest);\n return;\n }\n case \"popup\":\n return handleBrowserResult(await msalApp.loginPopup(loginRequest));\n }\n }\n\n /**\n * Tries to retrieve the token silently using MSAL.\n */\n async function getTokenSilent(\n scopes: string[],\n getTokenOptions?: CredentialFlowGetTokenOptions,\n ): Promise<AccessToken> {\n const activeAccount = await getActiveAccount();\n if (!activeAccount) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions,\n message:\n \"Silent authentication failed. We couldn't retrieve an active account from the cache.\",\n });\n }\n\n const parameters: msalBrowser.SilentRequest = {\n authority: getTokenOptions?.authority || msalConfig.auth.authority!,\n correlationId: getTokenOptions?.correlationId,\n claims: getTokenOptions?.claims,\n account: publicToMsal(activeAccount),\n forceRefresh: false,\n scopes,\n };\n\n try {\n logger.info(\"Attempting to acquire token silently\");\n const msalApp = await getApp();\n const response = await msalApp.acquireTokenSilent(parameters);\n return handleResult(scopes, response);\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n /**\n * Attempts to retrieve the token in the browser through interactive methods.\n */\n async function getTokenInteractive(\n scopes: string[],\n getTokenOptions?: CredentialFlowGetTokenOptions,\n ): Promise<AccessToken> {\n const activeAccount = await getActiveAccount();\n if (!activeAccount) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions,\n message:\n \"Silent authentication failed. We couldn't retrieve an active account from the cache.\",\n });\n }\n\n const parameters: msalBrowser.RedirectRequest = {\n authority: getTokenOptions?.authority || msalConfig.auth.authority!,\n correlationId: getTokenOptions?.correlationId,\n claims: getTokenOptions?.claims,\n account: publicToMsal(activeAccount),\n loginHint: loginHint,\n scopes,\n };\n const msalApp = await getApp();\n switch (loginStyle) {\n case \"redirect\":\n // This will go out of the page.\n // Once the InteractiveBrowserCredential is initialized again,\n // we'll load the MSAL account in the constructor.\n\n await msalApp.acquireTokenRedirect(parameters);\n return { token: \"\", expiresOnTimestamp: 0, tokenType: \"Bearer\" };\n case \"popup\":\n return handleResult(scopes, await app.acquireTokenPopup(parameters));\n }\n }\n\n /**\n * Attempts to get token through the silent flow.\n * If failed, get token through interactive method with `doGetToken` method.\n */\n async function getToken(\n scopes: string[],\n getTokenOptions: CredentialFlowGetTokenOptions = {},\n ): Promise<AccessToken> {\n const getTokenTenantId =\n processMultiTenantRequest(tenantId, getTokenOptions, additionallyAllowedTenantIds) ||\n tenantId;\n\n if (!getTokenOptions.authority) {\n getTokenOptions.authority = getAuthority(getTokenTenantId, authorityHost);\n }\n\n // We ensure that redirection is handled at this point.\n await handleRedirect();\n\n if (!(await getActiveAccount()) && !disableAutomaticAuthentication) {\n await login(scopes);\n }\n\n // Attempts to get the token silently; else, falls back to interactive method.\n try {\n return await getTokenSilent(scopes, getTokenOptions);\n } catch (err: any) {\n if (err.name !== \"AuthenticationRequiredError\") {\n throw err;\n }\n if (getTokenOptions?.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions,\n message:\n \"Automatic authentication has been disabled. You may call the authenticate() method.\",\n });\n }\n logger.info(`Silent authentication failed, falling back to interactive method ${loginStyle}`);\n return getTokenInteractive(scopes, getTokenOptions);\n }\n }\n return {\n getActiveAccount,\n getToken,\n };\n}\n"]}
|
1
|
+
{"version":3,"file":"msalBrowserCommon.js","sourceRoot":"","sources":["../../../../src/msal/browserFlows/msalBrowserCommon.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;AAmFlC,0DAyPC;;AA1UD,yEAAmD;AAGnD,0CASqB;AAIrB,+CAA0F;AAE1F,0CAA4C;AAC5C,sDAAsD;AACtD,kEAIqC;AACrC,qDAAqD;AAErD,uCAAuC;AACvC,gDAAgD;AAChD,MAAM,iBAAiB,GAAG,OAAO,IAAI,KAAK,WAAW,IAAI,IAAI,CAAC,QAAQ,KAAK,SAAS,CAAC;AAErF;;;GAGG;AACH,SAAS,gCAAgC,CACvC,OAA+B;;IAE/B,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,8BAAe,CAAC;IACrD,MAAM,SAAS,GAAG,IAAA,uBAAY,EAAC,QAAQ,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC;IAChE,OAAO;QACL,IAAI,EAAE;YACJ,QAAQ,EAAE,OAAO,CAAC,QAAS;YAC3B,SAAS;YACT,gBAAgB,EAAE,IAAA,8BAAmB,EAAC,QAAQ,EAAE,SAAS,EAAE,OAAO,CAAC,wBAAwB,CAAC;YAC5F,qDAAqD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* as msalBrowser from \"@azure/msal-browser\";\n\nimport type { MsalBrowserFlowOptions } from \"./msalBrowserOptions.js\";\nimport {\n defaultLoggerCallback,\n ensureValidMsalToken,\n getAuthority,\n getKnownAuthorities,\n getMSALLogLevel,\n handleMsalError,\n msalToPublic,\n publicToMsal,\n} from \"../utils.js\";\n\nimport type { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport type { AuthenticationRecord, MsalResult } from \"../types.js\";\nimport { AuthenticationRequiredError, CredentialUnavailableError } from \"../../errors.js\";\nimport type { CredentialFlowGetTokenOptions } from \"../credentials.js\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { formatSuccess } from \"../../util/logging.js\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n resolveTenantId,\n} from \"../../util/tenantIdUtils.js\";\nimport { DefaultTenantId } from \"../../constants.js\";\n\n// We keep a copy of the redirect hash.\n// Check if self and location object is defined.\nconst isLocationDefined = typeof self !== \"undefined\" && self.location !== undefined;\n\n/**\n * Generates a MSAL configuration that generally works for browsers\n * @internal\n */\nfunction generateMsalBrowserConfiguration(\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(tenantId, authority, options.disableInstanceDiscovery),\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 || (isLocationDefined ? self.location.origin : undefined),\n },\n cache: {\n cacheLocation: \"sessionStorage\",\n storeAuthStateInCookie: true, // Set to true to improve the experience on IE11 and Edge.\n },\n system: {\n loggerOptions: {\n loggerCallback: defaultLoggerCallback(options.logger, \"Browser\"),\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: options.loggingOptions?.enableUnsafeSupportLogging,\n },\n },\n };\n}\n\n/**\n * Methods that are used by InteractiveBrowserCredential\n * @internal\n */\nexport interface MsalBrowserClient {\n getActiveAccount(): Promise<AuthenticationRecord | undefined>;\n getToken(scopes: string[], options: CredentialFlowGetTokenOptions): Promise<AccessToken>;\n}\n\n// We keep a copy of the redirect hash.\nconst redirectHash = isLocationDefined ? self.location.hash : undefined;\n\n/**\n * Uses MSAL Browser 2.X for browser authentication,\n * which uses the [Auth Code Flow](https://learn.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow).\n * @internal\n */\nexport function createMsalBrowserClient(options: MsalBrowserFlowOptions): MsalBrowserClient {\n const loginStyle = options.loginStyle;\n if (!options.clientId) {\n throw new CredentialUnavailableError(\"A client ID is required in browsers\");\n }\n const clientId = options.clientId;\n const logger = options.logger;\n const tenantId = resolveTenantId(logger, options.tenantId, options.clientId);\n const additionallyAllowedTenantIds: string[] = resolveAdditionallyAllowedTenantIds(\n options?.tokenCredentialOptions?.additionallyAllowedTenants,\n );\n const authorityHost = options.authorityHost;\n const msalConfig = generateMsalBrowserConfiguration(options);\n const disableAutomaticAuthentication = options.disableAutomaticAuthentication;\n const loginHint = options.loginHint;\n\n let account: AuthenticationRecord | undefined;\n if (options.authenticationRecord) {\n account = {\n ...options.authenticationRecord,\n tenantId,\n };\n }\n\n // This variable should only be used through calling `getApp` function\n let app: msalBrowser.IPublicClientApplication;\n /**\n * Return the MSAL account if not set yet\n * @returns MSAL application\n */\n async function getApp(): Promise<msalBrowser.IPublicClientApplication> {\n if (!app) {\n // Prepare the MSAL application\n app = await msalBrowser.PublicClientApplication.createPublicClientApplication(msalConfig);\n\n // setting the account right after the app is created.\n if (account) {\n app.setActiveAccount(publicToMsal(account));\n }\n }\n\n return app;\n }\n\n /**\n * Loads the account based on the result of the authentication.\n * If no result was received, tries to load the account from the cache.\n * @param result - Result object received from MSAL.\n */\n async function handleBrowserResult(\n result?: msalBrowser.AuthenticationResult,\n ): Promise<AuthenticationRecord | undefined> {\n try {\n const msalApp = await getApp();\n if (result && result.account) {\n logger.info(`MSAL Browser V2 authentication successful.`);\n msalApp.setActiveAccount(result.account);\n return msalToPublic(clientId, result.account);\n }\n } catch (e: any) {\n logger.info(`Failed to acquire token through MSAL. ${e.message}`);\n }\n return;\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 function handleResult(\n scopes: string | string[],\n result?: MsalResult,\n getTokenOptions?: GetTokenOptions,\n ): AccessToken {\n if (result?.account) {\n account = msalToPublic(clientId, result.account);\n }\n ensureValidMsalToken(scopes, result, getTokenOptions);\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: result.accessToken,\n expiresOnTimestamp: result.expiresOn.getTime(),\n refreshAfterTimestamp: result.refreshOn?.getTime(),\n tokenType: \"Bearer\",\n };\n }\n\n /**\n * Uses MSAL to handle the redirect.\n */\n async function handleRedirect(): Promise<AuthenticationRecord | undefined> {\n const msalApp = await getApp();\n return handleBrowserResult((await msalApp.handleRedirectPromise(redirectHash)) || undefined);\n }\n\n /**\n * Uses MSAL to retrieve the active account.\n */\n async function getActiveAccount(): Promise<AuthenticationRecord | undefined> {\n const msalApp = await getApp();\n const activeAccount = msalApp.getActiveAccount();\n if (!activeAccount) {\n return;\n }\n return msalToPublic(clientId, activeAccount);\n }\n\n /**\n * Uses MSAL to trigger a redirect or a popup login.\n */\n async function login(scopes: string | string[] = []): Promise<AuthenticationRecord | undefined> {\n const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];\n const loginRequest: msalBrowser.RedirectRequest = {\n scopes: arrayScopes,\n loginHint: loginHint,\n };\n const msalApp = await getApp();\n switch (loginStyle) {\n case \"redirect\": {\n await app.loginRedirect(loginRequest);\n return;\n }\n case \"popup\":\n return handleBrowserResult(await msalApp.loginPopup(loginRequest));\n }\n }\n\n /**\n * Tries to retrieve the token silently using MSAL.\n */\n async function getTokenSilent(\n scopes: string[],\n getTokenOptions?: CredentialFlowGetTokenOptions,\n ): Promise<AccessToken> {\n const activeAccount = await getActiveAccount();\n if (!activeAccount) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions,\n message:\n \"Silent authentication failed. We couldn't retrieve an active account from the cache.\",\n });\n }\n\n const parameters: msalBrowser.SilentRequest = {\n authority: getTokenOptions?.authority || msalConfig.auth.authority!,\n correlationId: getTokenOptions?.correlationId,\n claims: getTokenOptions?.claims,\n account: publicToMsal(activeAccount),\n forceRefresh: false,\n scopes,\n };\n\n try {\n logger.info(\"Attempting to acquire token silently\");\n const msalApp = await getApp();\n const response = await msalApp.acquireTokenSilent(parameters);\n return handleResult(scopes, response);\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n /**\n * Attempts to retrieve the token in the browser through interactive methods.\n */\n async function getTokenInteractive(\n scopes: string[],\n getTokenOptions?: CredentialFlowGetTokenOptions,\n ): Promise<AccessToken> {\n const activeAccount = await getActiveAccount();\n if (!activeAccount) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions,\n message:\n \"Silent authentication failed. We couldn't retrieve an active account from the cache.\",\n });\n }\n\n const parameters: msalBrowser.RedirectRequest = {\n authority: getTokenOptions?.authority || msalConfig.auth.authority!,\n correlationId: getTokenOptions?.correlationId,\n claims: getTokenOptions?.claims,\n account: publicToMsal(activeAccount),\n loginHint: loginHint,\n scopes,\n };\n const msalApp = await getApp();\n switch (loginStyle) {\n case \"redirect\":\n // This will go out of the page.\n // Once the InteractiveBrowserCredential is initialized again,\n // we'll load the MSAL account in the constructor.\n\n await msalApp.acquireTokenRedirect(parameters);\n return { token: \"\", expiresOnTimestamp: 0, tokenType: \"Bearer\" };\n case \"popup\":\n return handleResult(scopes, await app.acquireTokenPopup(parameters));\n }\n }\n\n /**\n * Attempts to get token through the silent flow.\n * If failed, get token through interactive method with `doGetToken` method.\n */\n async function getToken(\n scopes: string[],\n getTokenOptions: CredentialFlowGetTokenOptions = {},\n ): Promise<AccessToken> {\n const getTokenTenantId =\n processMultiTenantRequest(tenantId, getTokenOptions, additionallyAllowedTenantIds) ||\n tenantId;\n\n if (!getTokenOptions.authority) {\n getTokenOptions.authority = getAuthority(getTokenTenantId, authorityHost);\n }\n\n // We ensure that redirection is handled at this point.\n await handleRedirect();\n\n if (!(await getActiveAccount()) && !disableAutomaticAuthentication) {\n await login(scopes);\n }\n\n // Attempts to get the token silently; else, falls back to interactive method.\n try {\n return await getTokenSilent(scopes, getTokenOptions);\n } catch (err: any) {\n if (err.name !== \"AuthenticationRequiredError\") {\n throw err;\n }\n if (getTokenOptions?.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions,\n message:\n \"Automatic authentication has been disabled. You may call the authenticate() method.\",\n });\n }\n logger.info(`Silent authentication failed, falling back to interactive method ${loginStyle}`);\n return getTokenInteractive(scopes, getTokenOptions);\n }\n }\n return {\n getActiveAccount,\n getToken,\n };\n}\n"]}
|
@@ -7,7 +7,7 @@ import type { ClientCertificateCredentialPEMConfiguration, ClientCertificatePEMC
|
|
7
7
|
* certificate that is assigned to an App Registration. More information
|
8
8
|
* on how to configure certificate authentication can be found here:
|
9
9
|
*
|
10
|
-
* https://learn.microsoft.com/
|
10
|
+
* https://learn.microsoft.com/azure/active-directory/develop/active-directory-certificate-credentials#register-your-certificate-with-azure-ad
|
11
11
|
*
|
12
12
|
*/
|
13
13
|
export declare class ClientCertificateCredential implements TokenCredential {
|