@azure/identity 2.1.0-alpha.20220321.2 → 2.1.0-alpha.20220404.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of @azure/identity might be problematic. Click here for more details.
- package/CHANGELOG.md +4 -6
- package/README.md +1 -1
- package/dist/index.js +236 -187
- package/dist/index.js.map +1 -1
- package/dist-esm/src/credentials/clientCertificateCredential.js +5 -2
- package/dist-esm/src/credentials/clientCertificateCredential.js.map +1 -1
- package/dist-esm/src/credentials/defaultAzureCredential.js +13 -26
- package/dist-esm/src/credentials/defaultAzureCredential.js.map +1 -1
- package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2019.js +77 -0
- package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2019.js.map +1 -0
- package/dist-esm/src/credentials/managedIdentityCredential/index.js +10 -1
- package/dist-esm/src/credentials/managedIdentityCredential/index.js.map +1 -1
- package/dist-esm/src/credentials/onBehalfOfCredential.js +0 -21
- package/dist-esm/src/credentials/onBehalfOfCredential.js.map +1 -1
- package/dist-esm/src/credentials/onBehalfOfCredentialOptions.js.map +1 -1
- package/dist-esm/src/index.js.map +1 -1
- package/dist-esm/src/msal/browserFlows/msalBrowserCommon.js +1 -1
- package/dist-esm/src/msal/browserFlows/msalBrowserCommon.js.map +1 -1
- package/dist-esm/src/msal/flows.js.map +1 -1
- package/dist-esm/src/msal/nodeFlows/msalClientCertificate.js +5 -1
- package/dist-esm/src/msal/nodeFlows/msalClientCertificate.js.map +1 -1
- package/dist-esm/src/msal/nodeFlows/msalNodeCommon.js +2 -3
- package/dist-esm/src/msal/nodeFlows/msalNodeCommon.js.map +1 -1
- package/dist-esm/src/msal/utils.js +1 -5
- package/dist-esm/src/msal/utils.js.map +1 -1
- package/dist-esm/src/tokenCredentialOptions.js.map +1 -1
- package/package.json +2 -2
- package/types/identity.d.ts +123 -59
|
@@ -69,12 +69,12 @@ export class MsalNode extends MsalBaseUtilities {
|
|
|
69
69
|
if (process.env.AZURE_IDENTITY_DISABLE_CP1) {
|
|
70
70
|
clientCapabilities = [];
|
|
71
71
|
}
|
|
72
|
-
|
|
72
|
+
return {
|
|
73
73
|
auth: {
|
|
74
74
|
clientId,
|
|
75
75
|
authority,
|
|
76
|
+
knownAuthorities: getKnownAuthorities(tenantId, authority),
|
|
76
77
|
clientCapabilities,
|
|
77
|
-
knownAuthorities: getKnownAuthorities(tenantId, authority, options.disableAuthorityValidation),
|
|
78
78
|
},
|
|
79
79
|
// Cache is defined in this.prepare();
|
|
80
80
|
system: {
|
|
@@ -84,7 +84,6 @@ export class MsalNode extends MsalBaseUtilities {
|
|
|
84
84
|
},
|
|
85
85
|
},
|
|
86
86
|
};
|
|
87
|
-
return configuration;
|
|
88
87
|
}
|
|
89
88
|
/**
|
|
90
89
|
* Prepares the MSAL applications.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"msalNodeCommon.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalNodeCommon.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,QAAQ,MAAM,kBAAkB,CAAC;AAM7C,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAE7D,OAAO,EAAE,uBAAuB,EAAE,MAAM,iBAAiB,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAI3D,OAAO,EACL,qBAAqB,EACrB,YAAY,EACZ,mBAAmB,EACnB,iBAAiB,EACjB,YAAY,EACZ,YAAY,GACb,MAAM,UAAU,CAAC;AAElB,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAuB5D;;;GAGG;AACH,IAAI,mBAAmB,GAEP,SAAS,CAAC;AAE1B;;;GAGG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D,IAAI,IAAI,CAAC,YAAY,IAAI,CAAC,aAAa,EAAE;gBACtC,OAAe,CAAC,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC;aAC7C;YACD,wEAAwE;YACxE,OAAO,MAAM,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;SACnD;QAAC,OAAO,GAAG,EAAE;YACZ,IAAI,GAAG,CAAC,IAAI,KAAK,6BAA6B,EAAE;gBAC9C,MAAM,GAAG,CAAC;aACX;YACD,IAAI,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,8BAA8B,EAAE;gBAC3C,MAAM,IAAI,2BAA2B,CAAC;oBACpC,MAAM;oBACN,eAAe,EAAE,OAAO;oBACxB,OAAO,EACL,uFAAuF;iBAC1F,CAAC,CAAC;aACJ;YACD,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,mEAAmE,CAAC,CAAC;YACtF,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;SACzC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalNode from \"@azure/msal-node\";\nimport * as msalCommon from \"@azure/msal-common\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { LogPolicyOptions } from \"@azure/core-rest-pipeline\";\n\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { DeveloperSignOnClientId } from \"../../constants\";\nimport { resolveTenantId } from \"../../util/resolveTenantId\";\nimport { AuthenticationRequiredError } from \"../../errors\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { MsalFlow, MsalFlowOptions } from \"../flows\";\nimport { AuthenticationRecord } from \"../types\";\nimport {\n defaultLoggerCallback,\n getAuthority,\n getKnownAuthorities,\n MsalBaseUtilities,\n msalToPublic,\n publicToMsal,\n} from \"../utils\";\nimport { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions\";\nimport { processMultiTenantRequest } from \"../../util/validateMultiTenant\";\nimport { RegionalAuthority } from \"../../regionalAuthority\";\n\n/**\n * Union of the constructor parameters that all MSAL flow types for Node.\n * @internal\n */\nexport interface MsalNodeOptions extends MsalFlowOptions {\n tokenCachePersistenceOptions?: TokenCachePersistenceOptions;\n tokenCredentialOptions: TokenCredentialOptions;\n /**\n * Specifies a regional authority. Please refer to the {@link RegionalAuthority} type for the accepted values.\n * If {@link RegionalAuthority.AutoDiscoverRegion} is specified, we will try to discover the regional authority endpoint.\n * If the property is not specified, uses a non-regional authority endpoint.\n */\n regionalAuthority?: string;\n /**\n * Allows logging account information once the authentication flow succeeds.\n */\n loggingOptions?: LogPolicyOptions & {\n allowLoggingAccountIdentifiers?: boolean;\n };\n}\n\n/**\n * The current persistence provider, undefined by default.\n * @internal\n */\nlet persistenceProvider:\n | ((options?: TokenCachePersistenceOptions) => Promise<msalCommon.ICachePlugin>)\n | undefined = undefined;\n\n/**\n * An object that allows setting the persistence provider.\n * @internal\n */\nexport const msalNodeFlowCacheControl = {\n setPersistence(pluginProvider: Exclude<typeof persistenceProvider, undefined>): void {\n persistenceProvider = pluginProvider;\n },\n};\n\n/**\n * MSAL partial base client for Node.js.\n *\n * It completes the input configuration with some default values.\n * It also provides with utility protected methods that can be used from any of the clients,\n * which includes handlers for successful responses and errors.\n *\n * @internal\n */\nexport abstract class MsalNode extends MsalBaseUtilities implements MsalFlow {\n protected publicApp: msalNode.PublicClientApplication | undefined;\n protected confidentialApp: msalNode.ConfidentialClientApplication | undefined;\n protected msalConfig: msalNode.Configuration;\n protected clientId: string;\n protected tenantId: string;\n protected authorityHost?: string;\n protected identityClient?: IdentityClient;\n protected requiresConfidential: boolean = false;\n protected azureRegion?: string;\n protected createCachePlugin: (() => Promise<msalCommon.ICachePlugin>) | undefined;\n\n /**\n * MSAL currently caches the tokens depending on the claims used to retrieve them.\n * In cases like CAE, in which we use claims to update the tokens, trying to retrieve the token without the claims will yield the original token.\n * To ensure we always get the latest token, we have to keep track of the claims.\n */\n private cachedClaims: string | undefined;\n\n constructor(options: MsalNodeOptions) {\n super(options);\n this.msalConfig = this.defaultNodeMsalConfig(options);\n this.tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);\n this.clientId = this.msalConfig.auth.clientId;\n\n // If persistence has been configured\n if (persistenceProvider !== undefined && options.tokenCachePersistenceOptions?.enabled) {\n this.createCachePlugin = () => persistenceProvider!(options.tokenCachePersistenceOptions);\n } else if (options.tokenCachePersistenceOptions?.enabled) {\n throw new Error(\n [\n \"Persistent token caching was requested, but no persistence provider was configured.\",\n \"You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)\",\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n \"`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`.\",\n ].join(\" \")\n );\n }\n\n this.azureRegion = options.regionalAuthority ?? process.env.AZURE_REGIONAL_AUTHORITY_NAME;\n if (this.azureRegion === RegionalAuthority.AutoDiscoverRegion) {\n this.azureRegion = \"AUTO_DISCOVER\";\n }\n }\n\n /**\n * Generates a MSAL configuration that generally works for Node.js\n */\n protected defaultNodeMsalConfig(options: MsalNodeOptions): msalNode.Configuration {\n const clientId = options.clientId || DeveloperSignOnClientId;\n const tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);\n\n this.authorityHost = options.authorityHost || process.env.AZURE_AUTHORITY_HOST;\n const authority = getAuthority(tenantId, this.authorityHost);\n\n this.identityClient = new IdentityClient({\n ...options.tokenCredentialOptions,\n authorityHost: authority,\n loggingOptions: options.loggingOptions,\n });\n\n let clientCapabilities: string[] = [\"cp1\"];\n if (process.env.AZURE_IDENTITY_DISABLE_CP1) {\n clientCapabilities = [];\n }\n\n const configuration: msalNode.Configuration = {\n auth: {\n clientId,\n authority,\n clientCapabilities,\n knownAuthorities: getKnownAuthorities(\n tenantId,\n authority,\n options.disableAuthorityValidation\n ),\n },\n // Cache is defined in this.prepare();\n system: {\n networkClient: this.identityClient,\n loggerOptions: {\n loggerCallback: defaultLoggerCallback(options.logger),\n },\n },\n };\n\n return configuration;\n }\n\n /**\n * Prepares the MSAL applications.\n */\n async init(options?: CredentialFlowGetTokenOptions): Promise<void> {\n if (options?.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", () => {\n // This will abort any pending request in the IdentityClient,\n // based on the received or generated correlationId\n this.identityClient!.abortRequests(options.correlationId);\n });\n }\n\n if (this.publicApp || this.confidentialApp) {\n return;\n }\n\n if (this.createCachePlugin !== undefined) {\n this.msalConfig.cache = {\n cachePlugin: await this.createCachePlugin(),\n };\n }\n\n this.publicApp = new msalNode.PublicClientApplication(this.msalConfig);\n // The confidential client requires either a secret, assertion or certificate.\n if (\n this.msalConfig.auth.clientSecret ||\n this.msalConfig.auth.clientAssertion ||\n this.msalConfig.auth.clientCertificate\n ) {\n this.confidentialApp = new msalNode.ConfidentialClientApplication(this.msalConfig);\n } else {\n if (this.requiresConfidential) {\n throw new Error(\n \"Unable to generate the MSAL confidential client. Missing either the client's secret, certificate or assertion.\"\n );\n }\n }\n }\n\n /**\n * Allows the cancellation of a MSAL request.\n */\n protected withCancellation(\n promise: Promise<msalCommon.AuthenticationResult | null>,\n abortSignal?: AbortSignalLike,\n onCancel?: () => void\n ): Promise<msalCommon.AuthenticationResult | null> {\n return new Promise((resolve, reject) => {\n promise\n .then((msalToken) => {\n return resolve(msalToken!);\n })\n .catch(reject);\n if (abortSignal) {\n abortSignal.addEventListener(\"abort\", () => {\n onCancel?.();\n });\n }\n });\n }\n\n /**\n * Returns the existing account, attempts to load the account from MSAL.\n */\n async getActiveAccount(): Promise<AuthenticationRecord | undefined> {\n if (this.account) {\n return this.account;\n }\n const cache = this.confidentialApp?.getTokenCache() ?? this.publicApp?.getTokenCache();\n const accountsByTenant = await cache?.getAllAccounts();\n\n if (!accountsByTenant) {\n return;\n }\n\n if (accountsByTenant.length === 1) {\n this.account = msalToPublic(this.clientId, accountsByTenant[0]);\n } else {\n this.logger\n .info(`More than one account was found authenticated for this Client ID and Tenant ID.\nHowever, no \"authenticationRecord\" has been provided for this credential,\ntherefore we're unable to pick between these accounts.\nA new login attempt will be requested, to ensure the correct account is picked.\nTo work with multiple accounts for the same Client ID and Tenant ID, please provide an \"authenticationRecord\" when initializing a credential to prevent this from happening.`);\n return;\n }\n\n return this.account;\n }\n\n /**\n * Attempts to retrieve a token from cache.\n */\n async getTokenSilent(\n scopes: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<AccessToken> {\n await this.getActiveAccount();\n if (!this.account) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Silent authentication failed. We couldn't retrieve an active account from the cache.\",\n });\n }\n\n const silentRequest: msalNode.SilentFlowRequest = {\n // To be able to re-use the account, the Token Cache must also have been provided.\n account: publicToMsal(this.account),\n correlationId: options?.correlationId,\n scopes,\n authority: options?.authority,\n claims: options?.claims,\n };\n\n try {\n this.logger.info(\"Attempting to acquire token silently\");\n const response =\n (await this.confidentialApp?.acquireTokenSilent(silentRequest)) ??\n (await this.publicApp!.acquireTokenSilent(silentRequest));\n return this.handleResult(scopes, this.clientId, response || undefined);\n } catch (err) {\n throw this.handleError(scopes, err, options);\n }\n }\n\n /**\n * Attempts to retrieve an authenticated token from MSAL.\n */\n protected abstract doGetToken(scopes: string[], options?: GetTokenOptions): Promise<AccessToken>;\n\n /**\n * Wrapper around each MSAL flow get token operation: doGetToken.\n * If disableAutomaticAuthentication is sent through the constructor, it will prevent MSAL from requesting the user input.\n */\n public async getToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {}\n ): Promise<AccessToken> {\n const tenantId = processMultiTenantRequest(this.tenantId, options) || this.tenantId;\n\n options.authority = getAuthority(tenantId, this.authorityHost);\n\n options.correlationId = options?.correlationId || this.generateUuid();\n await this.init(options);\n\n try {\n // MSAL now caches tokens based on their claims,\n // so now one has to keep track fo claims in order to retrieve the newer tokens from acquireTokenSilent\n // This update happened on PR: https://github.com/AzureAD/microsoft-authentication-library-for-js/pull/4533\n const optionsClaims = (options as any).claims;\n if (optionsClaims) {\n this.cachedClaims = optionsClaims;\n }\n if (this.cachedClaims && !optionsClaims) {\n (options as any).claims = this.cachedClaims;\n }\n // We don't return the promise since we want to catch errors right here.\n return await this.getTokenSilent(scopes, options);\n } catch (err) {\n if (err.name !== \"AuthenticationRequiredError\") {\n throw err;\n }\n if (options?.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Automatic authentication has been disabled. You may call the authentication() method.\",\n });\n }\n this.logger.info(`Silent authentication failed, falling back to interactive method.`);\n return this.doGetToken(scopes, options);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"msalNodeCommon.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalNodeCommon.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,QAAQ,MAAM,kBAAkB,CAAC;AAM7C,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAE7D,OAAO,EAAE,uBAAuB,EAAE,MAAM,iBAAiB,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAI3D,OAAO,EACL,qBAAqB,EACrB,YAAY,EACZ,mBAAmB,EACnB,iBAAiB,EACjB,YAAY,EACZ,YAAY,GACb,MAAM,UAAU,CAAC;AAElB,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAuB5D;;;GAGG;AACH,IAAI,mBAAmB,GAEP,SAAS,CAAC;AAE1B;;;GAGG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG;IACtC,cAAc,CAAC,cAA8D;QAC3E,mBA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O,MAAM,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;SACnD;QAAC,OAAO,GAAG,EAAE;YACZ,IAAI,GAAG,CAAC,IAAI,KAAK,6BAA6B,EAAE;gBAC9C,MAAM,GAAG,CAAC;aACX;YACD,IAAI,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,8BAA8B,EAAE;gBAC3C,MAAM,IAAI,2BAA2B,CAAC;oBACpC,MAAM;oBACN,eAAe,EAAE,OAAO;oBACxB,OAAO,EACL,uFAAuF;iBAC1F,CAAC,CAAC;aACJ;YACD,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,mEAAmE,CAAC,CAAC;YACtF,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;SACzC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalNode from \"@azure/msal-node\";\nimport * as msalCommon from \"@azure/msal-common\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { LogPolicyOptions } from \"@azure/core-rest-pipeline\";\n\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { DeveloperSignOnClientId } from \"../../constants\";\nimport { resolveTenantId } from \"../../util/resolveTenantId\";\nimport { AuthenticationRequiredError } from \"../../errors\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { MsalFlow, MsalFlowOptions } from \"../flows\";\nimport { AuthenticationRecord } from \"../types\";\nimport {\n defaultLoggerCallback,\n getAuthority,\n getKnownAuthorities,\n MsalBaseUtilities,\n msalToPublic,\n publicToMsal,\n} from \"../utils\";\nimport { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions\";\nimport { processMultiTenantRequest } from \"../../util/validateMultiTenant\";\nimport { RegionalAuthority } from \"../../regionalAuthority\";\n\n/**\n * Union of the constructor parameters that all MSAL flow types for Node.\n * @internal\n */\nexport interface MsalNodeOptions extends MsalFlowOptions {\n tokenCachePersistenceOptions?: TokenCachePersistenceOptions;\n tokenCredentialOptions: TokenCredentialOptions;\n /**\n * Specifies a regional authority. Please refer to the {@link RegionalAuthority} type for the accepted values.\n * If {@link RegionalAuthority.AutoDiscoverRegion} is specified, we will try to discover the regional authority endpoint.\n * If the property is not specified, uses a non-regional authority endpoint.\n */\n regionalAuthority?: string;\n /**\n * Allows logging account information once the authentication flow succeeds.\n */\n loggingOptions?: LogPolicyOptions & {\n allowLoggingAccountIdentifiers?: boolean;\n };\n}\n\n/**\n * The current persistence provider, undefined by default.\n * @internal\n */\nlet persistenceProvider:\n | ((options?: TokenCachePersistenceOptions) => Promise<msalCommon.ICachePlugin>)\n | undefined = undefined;\n\n/**\n * An object that allows setting the persistence provider.\n * @internal\n */\nexport const msalNodeFlowCacheControl = {\n setPersistence(pluginProvider: Exclude<typeof persistenceProvider, undefined>): void {\n persistenceProvider = pluginProvider;\n },\n};\n\n/**\n * MSAL partial base client for Node.js.\n *\n * It completes the input configuration with some default values.\n * It also provides with utility protected methods that can be used from any of the clients,\n * which includes handlers for successful responses and errors.\n *\n * @internal\n */\nexport abstract class MsalNode extends MsalBaseUtilities implements MsalFlow {\n protected publicApp: msalNode.PublicClientApplication | undefined;\n protected confidentialApp: msalNode.ConfidentialClientApplication | undefined;\n protected msalConfig: msalNode.Configuration;\n protected clientId: string;\n protected tenantId: string;\n protected authorityHost?: string;\n protected identityClient?: IdentityClient;\n protected requiresConfidential: boolean = false;\n protected azureRegion?: string;\n protected createCachePlugin: (() => Promise<msalCommon.ICachePlugin>) | undefined;\n\n /**\n * MSAL currently caches the tokens depending on the claims used to retrieve them.\n * In cases like CAE, in which we use claims to update the tokens, trying to retrieve the token without the claims will yield the original token.\n * To ensure we always get the latest token, we have to keep track of the claims.\n */\n private cachedClaims: string | undefined;\n\n constructor(options: MsalNodeOptions) {\n super(options);\n this.msalConfig = this.defaultNodeMsalConfig(options);\n this.tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);\n this.clientId = this.msalConfig.auth.clientId;\n\n // If persistence has been configured\n if (persistenceProvider !== undefined && options.tokenCachePersistenceOptions?.enabled) {\n this.createCachePlugin = () => persistenceProvider!(options.tokenCachePersistenceOptions);\n } else if (options.tokenCachePersistenceOptions?.enabled) {\n throw new Error(\n [\n \"Persistent token caching was requested, but no persistence provider was configured.\",\n \"You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)\",\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n \"`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`.\",\n ].join(\" \")\n );\n }\n\n this.azureRegion = options.regionalAuthority ?? process.env.AZURE_REGIONAL_AUTHORITY_NAME;\n if (this.azureRegion === RegionalAuthority.AutoDiscoverRegion) {\n this.azureRegion = \"AUTO_DISCOVER\";\n }\n }\n\n /**\n * Generates a MSAL configuration that generally works for Node.js\n */\n protected defaultNodeMsalConfig(options: MsalNodeOptions): msalNode.Configuration {\n const clientId = options.clientId || DeveloperSignOnClientId;\n const tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);\n\n this.authorityHost = options.authorityHost || process.env.AZURE_AUTHORITY_HOST;\n const authority = getAuthority(tenantId, this.authorityHost);\n\n this.identityClient = new IdentityClient({\n ...options.tokenCredentialOptions,\n authorityHost: authority,\n loggingOptions: options.loggingOptions,\n });\n\n let clientCapabilities: string[] = [\"cp1\"];\n if (process.env.AZURE_IDENTITY_DISABLE_CP1) {\n clientCapabilities = [];\n }\n\n return {\n auth: {\n clientId,\n authority,\n knownAuthorities: getKnownAuthorities(tenantId, authority),\n clientCapabilities,\n },\n // Cache is defined in this.prepare();\n system: {\n networkClient: this.identityClient,\n loggerOptions: {\n loggerCallback: defaultLoggerCallback(options.logger),\n },\n },\n };\n }\n\n /**\n * Prepares the MSAL applications.\n */\n async init(options?: CredentialFlowGetTokenOptions): Promise<void> {\n if (options?.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", () => {\n // This will abort any pending request in the IdentityClient,\n // based on the received or generated correlationId\n this.identityClient!.abortRequests(options.correlationId);\n });\n }\n\n if (this.publicApp || this.confidentialApp) {\n return;\n }\n\n if (this.createCachePlugin !== undefined) {\n this.msalConfig.cache = {\n cachePlugin: await this.createCachePlugin(),\n };\n }\n\n this.publicApp = new msalNode.PublicClientApplication(this.msalConfig);\n // The confidential client requires either a secret, assertion or certificate.\n if (\n this.msalConfig.auth.clientSecret ||\n this.msalConfig.auth.clientAssertion ||\n this.msalConfig.auth.clientCertificate\n ) {\n this.confidentialApp = new msalNode.ConfidentialClientApplication(this.msalConfig);\n } else {\n if (this.requiresConfidential) {\n throw new Error(\n \"Unable to generate the MSAL confidential client. Missing either the client's secret, certificate or assertion.\"\n );\n }\n }\n }\n\n /**\n * Allows the cancellation of a MSAL request.\n */\n protected withCancellation(\n promise: Promise<msalCommon.AuthenticationResult | null>,\n abortSignal?: AbortSignalLike,\n onCancel?: () => void\n ): Promise<msalCommon.AuthenticationResult | null> {\n return new Promise((resolve, reject) => {\n promise\n .then((msalToken) => {\n return resolve(msalToken!);\n })\n .catch(reject);\n if (abortSignal) {\n abortSignal.addEventListener(\"abort\", () => {\n onCancel?.();\n });\n }\n });\n }\n\n /**\n * Returns the existing account, attempts to load the account from MSAL.\n */\n async getActiveAccount(): Promise<AuthenticationRecord | undefined> {\n if (this.account) {\n return this.account;\n }\n const cache = this.confidentialApp?.getTokenCache() ?? this.publicApp?.getTokenCache();\n const accountsByTenant = await cache?.getAllAccounts();\n\n if (!accountsByTenant) {\n return;\n }\n\n if (accountsByTenant.length === 1) {\n this.account = msalToPublic(this.clientId, accountsByTenant[0]);\n } else {\n this.logger\n .info(`More than one account was found authenticated for this Client ID and Tenant ID.\nHowever, no \"authenticationRecord\" has been provided for this credential,\ntherefore we're unable to pick between these accounts.\nA new login attempt will be requested, to ensure the correct account is picked.\nTo work with multiple accounts for the same Client ID and Tenant ID, please provide an \"authenticationRecord\" when initializing a credential to prevent this from happening.`);\n return;\n }\n\n return this.account;\n }\n\n /**\n * Attempts to retrieve a token from cache.\n */\n async getTokenSilent(\n scopes: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<AccessToken> {\n await this.getActiveAccount();\n if (!this.account) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Silent authentication failed. We couldn't retrieve an active account from the cache.\",\n });\n }\n\n const silentRequest: msalNode.SilentFlowRequest = {\n // To be able to re-use the account, the Token Cache must also have been provided.\n account: publicToMsal(this.account),\n correlationId: options?.correlationId,\n scopes,\n authority: options?.authority,\n claims: options?.claims,\n };\n\n try {\n this.logger.info(\"Attempting to acquire token silently\");\n const response =\n (await this.confidentialApp?.acquireTokenSilent(silentRequest)) ??\n (await this.publicApp!.acquireTokenSilent(silentRequest));\n return this.handleResult(scopes, this.clientId, response || undefined);\n } catch (err) {\n throw this.handleError(scopes, err, options);\n }\n }\n\n /**\n * Attempts to retrieve an authenticated token from MSAL.\n */\n protected abstract doGetToken(scopes: string[], options?: GetTokenOptions): Promise<AccessToken>;\n\n /**\n * Wrapper around each MSAL flow get token operation: doGetToken.\n * If disableAutomaticAuthentication is sent through the constructor, it will prevent MSAL from requesting the user input.\n */\n public async getToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {}\n ): Promise<AccessToken> {\n const tenantId = processMultiTenantRequest(this.tenantId, options) || this.tenantId;\n\n options.authority = getAuthority(tenantId, this.authorityHost);\n\n options.correlationId = options?.correlationId || this.generateUuid();\n await this.init(options);\n\n try {\n // MSAL now caches tokens based on their claims,\n // so now one has to keep track fo claims in order to retrieve the newer tokens from acquireTokenSilent\n // This update happened on PR: https://github.com/AzureAD/microsoft-authentication-library-for-js/pull/4533\n const optionsClaims = (options as any).claims;\n if (optionsClaims) {\n this.cachedClaims = optionsClaims;\n }\n if (this.cachedClaims && !optionsClaims) {\n (options as any).claims = this.cachedClaims;\n }\n // We don't return the promise since we want to catch errors right here.\n return await this.getTokenSilent(scopes, options);\n } catch (err) {\n if (err.name !== \"AuthenticationRequiredError\") {\n throw err;\n }\n if (options?.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Automatic authentication has been disabled. You may call the authentication() method.\",\n });\n }\n this.logger.info(`Silent authentication failed, falling back to interactive method.`);\n return this.doGetToken(scopes, options);\n }\n }\n}\n"]}
|
|
@@ -55,16 +55,12 @@ export function getAuthority(tenantId, host) {
|
|
|
55
55
|
}
|
|
56
56
|
/**
|
|
57
57
|
* Generates the known authorities.
|
|
58
|
-
* If `disableAuthorityValidation` is passed, it returns the authority host as a known host, thus disabling the authority validation.
|
|
59
58
|
* If the Tenant Id is `adfs`, the authority can't be validated since the format won't match the expected one.
|
|
60
59
|
* For that reason, we have to force MSAL to disable validating the authority
|
|
61
60
|
* by sending it within the known authorities in the MSAL configuration.
|
|
62
61
|
* @internal
|
|
63
62
|
*/
|
|
64
|
-
export function getKnownAuthorities(tenantId, authorityHost
|
|
65
|
-
if (disableAuthorityValidation) {
|
|
66
|
-
return [authorityHost];
|
|
67
|
-
}
|
|
63
|
+
export function getKnownAuthorities(tenantId, authorityHost) {
|
|
68
64
|
if (tenantId === "adfs" && authorityHost) {
|
|
69
65
|
return [authorityHost];
|
|
70
66
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/msal/utils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,UAAU,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAE1C,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAErD,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,EAAoB,WAAW,EAAE,aAAa,EAAE,MAAM,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AM,CAAC;AAChB,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,6BAA6B,CAAC,MAA4B;IACxE,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;AAChC,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,+BAA+B,CAAC,gBAAwB;IACtE,MAAM,MAAM,GAAgD,IAAI,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;IAEzF,IAAI,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,OAAO,KAAK,iCAAiC,EAAE;QAC1E,MAAM,KAAK,CAAC,0CAA0C,CAAC,CAAC;KACzD;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalCommon from \"@azure/msal-common\";\nimport { isNode } from \"@azure/core-util\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AbortError } from \"@azure/abort-controller\";\n\nimport { v4 as uuidv4 } from \"uuid\";\nimport { CredentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { CredentialUnavailableError, AuthenticationRequiredError } from \"../errors\";\nimport { DefaultAuthorityHost, DefaultTenantId } from \"../constants\";\nimport { AuthenticationRecord, MsalAccountInfo, MsalResult, MsalToken } from \"./types\";\nimport { MsalFlowOptions } from \"./flows\";\n\n/**\n * Latest AuthenticationRecord version\n * @internal\n */\nconst LatestAuthenticationRecordVersion = \"1.0\";\n\n/**\n * Ensures the validity of the MSAL token\n * @internal\n */\nexport function ensureValidMsalToken(\n scopes: string | string[],\n logger: CredentialLogger,\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions\n): void {\n const error = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message,\n });\n };\n if (!msalToken) {\n throw error(\"No response\");\n }\n if (!msalToken.expiresOn) {\n throw error(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw error(`Response had no \"accessToken\" property.`);\n }\n}\n\n/**\n * Generates a valid authority by combining a host with a tenantId.\n * @internal\n */\nexport function getAuthority(tenantId: string, host?: string): string {\n if (!host) {\n host = DefaultAuthorityHost;\n }\n if (new RegExp(`${tenantId}/?$`).test(host)) {\n return host;\n }\n if (host.endsWith(\"/\")) {\n return host + tenantId;\n } else {\n return `${host}/${tenantId}`;\n }\n}\n\n/**\n * Generates the known authorities.\n * If `disableAuthorityValidation` is passed, it returns the authority host as a known host, thus disabling the authority validation.\n * If the Tenant Id is `adfs`, the authority can't be validated since the format won't match the expected one.\n * For that reason, we have to force MSAL to disable validating the authority\n * by sending it within the known authorities in the MSAL configuration.\n * @internal\n */\nexport function getKnownAuthorities(\n tenantId: string,\n authorityHost: string,\n disableAuthorityValidation?: boolean\n): string[] {\n if (disableAuthorityValidation) {\n return [authorityHost];\n }\n if (tenantId === \"adfs\" && authorityHost) {\n return [authorityHost];\n }\n return [];\n}\n\n/**\n * Generates a logger that can be passed to the MSAL clients.\n * @param logger - The logger of the credential.\n * @internal\n */\nexport const defaultLoggerCallback: (\n logger: CredentialLogger,\n platform?: \"Node\" | \"Browser\"\n) => msalCommon.ILoggerCallback =\n (logger: CredentialLogger, platform: \"Node\" | \"Browser\" = isNode ? \"Node\" : \"Browser\") =>\n (level, message, containsPii): void => {\n if (containsPii) {\n return;\n }\n switch (level) {\n case msalCommon.LogLevel.Error:\n logger.info(`MSAL ${platform} V2 error: ${message}`);\n return;\n case msalCommon.LogLevel.Info:\n logger.info(`MSAL ${platform} V2 info message: ${message}`);\n return;\n case msalCommon.LogLevel.Verbose:\n logger.info(`MSAL ${platform} V2 verbose message: ${message}`);\n return;\n case msalCommon.LogLevel.Warning:\n logger.info(`MSAL ${platform} V2 warning: ${message}`);\n return;\n }\n };\n\n/**\n * The common utility functions for the MSAL clients.\n * Defined as a class so that the classes extending this one can have access to its methods and protected properties.\n *\n * It keeps track of a logger and an in-memory copy of the AuthenticationRecord.\n *\n * @internal\n */\nexport class MsalBaseUtilities {\n protected logger: CredentialLogger;\n protected account: AuthenticationRecord | undefined;\n\n constructor(options: MsalFlowOptions) {\n this.logger = options.logger;\n this.account = options.authenticationRecord;\n }\n\n /**\n * Generates a UUID\n */\n generateUuid(): string {\n return uuidv4();\n }\n\n /**\n * Handles the MSAL authentication result.\n * If the result has an account, we update the local account reference.\n * If the token received is invalid, an error will be thrown depending on what's missing.\n */\n protected handleResult(\n scopes: string | string[],\n clientId: string,\n result?: MsalResult,\n getTokenOptions?: GetTokenOptions\n ): AccessToken {\n if (result?.account) {\n this.account = msalToPublic(clientId, result.account);\n }\n ensureValidMsalToken(scopes, this.logger, result, getTokenOptions);\n this.logger.getToken.info(formatSuccess(scopes));\n return {\n token: result!.accessToken!,\n expiresOnTimestamp: result!.expiresOn!.getTime(),\n };\n }\n\n /**\n * Handles MSAL errors.\n */\n protected handleError(scopes: string[], error: Error, getTokenOptions?: GetTokenOptions): Error {\n if (\n error.name === \"AuthError\" ||\n error.name === \"ClientAuthError\" ||\n error.name === \"BrowserAuthError\"\n ) {\n const msalError = error as msalCommon.AuthError;\n switch (msalError.errorCode) {\n case \"endpoints_resolution_error\":\n this.logger.info(formatError(scopes, error.message));\n return new CredentialUnavailableError(error.message);\n case \"device_code_polling_cancelled\":\n return new AbortError(\"The authentication has been aborted by the caller.\");\n case \"consent_required\":\n case \"interaction_required\":\n case \"login_required\":\n this.logger.info(\n formatError(scopes, `Authentication returned errorCode ${msalError.errorCode}`)\n );\n break;\n default:\n this.logger.info(formatError(scopes, `Failed to acquire token: ${error.message}`));\n break;\n }\n }\n if (\n error.name === \"ClientConfigurationError\" ||\n error.name === \"BrowserConfigurationAuthError\" ||\n error.name === \"AbortError\"\n ) {\n return error;\n }\n return new AuthenticationRequiredError({ scopes, getTokenOptions, message: error.message });\n }\n}\n\n// transformations.ts\n\nexport function publicToMsal(account: AuthenticationRecord): msalCommon.AccountInfo {\n const [environment] = account.authority.match(/([a-z]*\\.[a-z]*\\.[a-z]*)/) || [];\n return {\n ...account,\n localAccountId: account.homeAccountId,\n environment,\n };\n}\n\nexport function msalToPublic(clientId: string, account: MsalAccountInfo): AuthenticationRecord {\n const record = {\n authority: getAuthority(account.tenantId, account.environment),\n homeAccountId: account.homeAccountId,\n tenantId: account.tenantId || DefaultTenantId,\n username: account.username,\n clientId,\n version: LatestAuthenticationRecordVersion,\n };\n return record;\n}\n\n/**\n * Serializes an `AuthenticationRecord` into a string.\n *\n * The output of a serialized authentication record will contain the following properties:\n *\n * - \"authority\"\n * - \"homeAccountId\"\n * - \"clientId\"\n * - \"tenantId\"\n * - \"username\"\n * - \"version\"\n *\n * To later convert this string to a serialized `AuthenticationRecord`, please use the exported function `deserializeAuthenticationRecord()`.\n */\nexport function serializeAuthenticationRecord(record: AuthenticationRecord): string {\n return JSON.stringify(record);\n}\n\n/**\n * Deserializes a previously serialized authentication record from a string into an object.\n *\n * The input string must contain the following properties:\n *\n * - \"authority\"\n * - \"homeAccountId\"\n * - \"clientId\"\n * - \"tenantId\"\n * - \"username\"\n * - \"version\"\n *\n * If the version we receive is unsupported, an error will be thrown.\n *\n * At the moment, the only available version is: \"1.0\", which is always set when the authentication record is serialized.\n *\n * @param serializedRecord - Authentication record previously serialized into string.\n * @returns AuthenticationRecord.\n */\nexport function deserializeAuthenticationRecord(serializedRecord: string): AuthenticationRecord {\n const parsed: AuthenticationRecord & { version?: string } = JSON.parse(serializedRecord);\n\n if (parsed.version && parsed.version !== LatestAuthenticationRecordVersion) {\n throw Error(\"Unsupported AuthenticationRecord version\");\n }\n\n return parsed;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/msal/utils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,UAAU,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CA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CAAC,QAAQ;QAC1B,QAAQ;QACR,OAAO,EAAE,iCAAiC;KAC3C,CAAC;IACF,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,6BAA6B,CAAC,MAA4B;IACxE,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;AAChC,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,+BAA+B,CAAC,gBAAwB;IACtE,MAAM,MAAM,GAAgD,IAAI,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;IAEzF,IAAI,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,OAAO,KAAK,iCAAiC,EAAE;QAC1E,MAAM,KAAK,CAAC,0CAA0C,CAAC,CAAC;KACzD;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalCommon from \"@azure/msal-common\";\nimport { isNode } from \"@azure/core-util\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AbortError } from \"@azure/abort-controller\";\n\nimport { v4 as uuidv4 } from \"uuid\";\nimport { CredentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { CredentialUnavailableError, AuthenticationRequiredError } from \"../errors\";\nimport { DefaultAuthorityHost, DefaultTenantId } from \"../constants\";\nimport { AuthenticationRecord, MsalAccountInfo, MsalResult, MsalToken } from \"./types\";\nimport { MsalFlowOptions } from \"./flows\";\n\n/**\n * Latest AuthenticationRecord version\n * @internal\n */\nconst LatestAuthenticationRecordVersion = \"1.0\";\n\n/**\n * Ensures the validity of the MSAL token\n * @internal\n */\nexport function ensureValidMsalToken(\n scopes: string | string[],\n logger: CredentialLogger,\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions\n): void {\n const error = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message,\n });\n };\n if (!msalToken) {\n throw error(\"No response\");\n }\n if (!msalToken.expiresOn) {\n throw error(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw error(`Response had no \"accessToken\" property.`);\n }\n}\n\n/**\n * Generates a valid authority by combining a host with a tenantId.\n * @internal\n */\nexport function getAuthority(tenantId: string, host?: string): string {\n if (!host) {\n host = DefaultAuthorityHost;\n }\n if (new RegExp(`${tenantId}/?$`).test(host)) {\n return host;\n }\n if (host.endsWith(\"/\")) {\n return host + tenantId;\n } else {\n return `${host}/${tenantId}`;\n }\n}\n\n/**\n * Generates the known authorities.\n * If the Tenant Id is `adfs`, the authority can't be validated since the format won't match the expected one.\n * For that reason, we have to force MSAL to disable validating the authority\n * by sending it within the known authorities in the MSAL configuration.\n * @internal\n */\nexport function getKnownAuthorities(tenantId: string, authorityHost: string): string[] {\n if (tenantId === \"adfs\" && authorityHost) {\n return [authorityHost];\n }\n return [];\n}\n\n/**\n * Generates a logger that can be passed to the MSAL clients.\n * @param logger - The logger of the credential.\n * @internal\n */\nexport const defaultLoggerCallback: (\n logger: CredentialLogger,\n platform?: \"Node\" | \"Browser\"\n) => msalCommon.ILoggerCallback =\n (logger: CredentialLogger, platform: \"Node\" | \"Browser\" = isNode ? \"Node\" : \"Browser\") =>\n (level, message, containsPii): void => {\n if (containsPii) {\n return;\n }\n switch (level) {\n case msalCommon.LogLevel.Error:\n logger.info(`MSAL ${platform} V2 error: ${message}`);\n return;\n case msalCommon.LogLevel.Info:\n logger.info(`MSAL ${platform} V2 info message: ${message}`);\n return;\n case msalCommon.LogLevel.Verbose:\n logger.info(`MSAL ${platform} V2 verbose message: ${message}`);\n return;\n case msalCommon.LogLevel.Warning:\n logger.info(`MSAL ${platform} V2 warning: ${message}`);\n return;\n }\n };\n\n/**\n * The common utility functions for the MSAL clients.\n * Defined as a class so that the classes extending this one can have access to its methods and protected properties.\n *\n * It keeps track of a logger and an in-memory copy of the AuthenticationRecord.\n *\n * @internal\n */\nexport class MsalBaseUtilities {\n protected logger: CredentialLogger;\n protected account: AuthenticationRecord | undefined;\n\n constructor(options: MsalFlowOptions) {\n this.logger = options.logger;\n this.account = options.authenticationRecord;\n }\n\n /**\n * Generates a UUID\n */\n generateUuid(): string {\n return uuidv4();\n }\n\n /**\n * Handles the MSAL authentication result.\n * If the result has an account, we update the local account reference.\n * If the token received is invalid, an error will be thrown depending on what's missing.\n */\n protected handleResult(\n scopes: string | string[],\n clientId: string,\n result?: MsalResult,\n getTokenOptions?: GetTokenOptions\n ): AccessToken {\n if (result?.account) {\n this.account = msalToPublic(clientId, result.account);\n }\n ensureValidMsalToken(scopes, this.logger, result, getTokenOptions);\n this.logger.getToken.info(formatSuccess(scopes));\n return {\n token: result!.accessToken!,\n expiresOnTimestamp: result!.expiresOn!.getTime(),\n };\n }\n\n /**\n * Handles MSAL errors.\n */\n protected handleError(scopes: string[], error: Error, getTokenOptions?: GetTokenOptions): Error {\n if (\n error.name === \"AuthError\" ||\n error.name === \"ClientAuthError\" ||\n error.name === \"BrowserAuthError\"\n ) {\n const msalError = error as msalCommon.AuthError;\n switch (msalError.errorCode) {\n case \"endpoints_resolution_error\":\n this.logger.info(formatError(scopes, error.message));\n return new CredentialUnavailableError(error.message);\n case \"device_code_polling_cancelled\":\n return new AbortError(\"The authentication has been aborted by the caller.\");\n case \"consent_required\":\n case \"interaction_required\":\n case \"login_required\":\n this.logger.info(\n formatError(scopes, `Authentication returned errorCode ${msalError.errorCode}`)\n );\n break;\n default:\n this.logger.info(formatError(scopes, `Failed to acquire token: ${error.message}`));\n break;\n }\n }\n if (\n error.name === \"ClientConfigurationError\" ||\n error.name === \"BrowserConfigurationAuthError\" ||\n error.name === \"AbortError\"\n ) {\n return error;\n }\n return new AuthenticationRequiredError({ scopes, getTokenOptions, message: error.message });\n }\n}\n\n// transformations.ts\n\nexport function publicToMsal(account: AuthenticationRecord): msalCommon.AccountInfo {\n const [environment] = account.authority.match(/([a-z]*\\.[a-z]*\\.[a-z]*)/) || [];\n return {\n ...account,\n localAccountId: account.homeAccountId,\n environment,\n };\n}\n\nexport function msalToPublic(clientId: string, account: MsalAccountInfo): AuthenticationRecord {\n const record = {\n authority: getAuthority(account.tenantId, account.environment),\n homeAccountId: account.homeAccountId,\n tenantId: account.tenantId || DefaultTenantId,\n username: account.username,\n clientId,\n version: LatestAuthenticationRecordVersion,\n };\n return record;\n}\n\n/**\n * Serializes an `AuthenticationRecord` into a string.\n *\n * The output of a serialized authentication record will contain the following properties:\n *\n * - \"authority\"\n * - \"homeAccountId\"\n * - \"clientId\"\n * - \"tenantId\"\n * - \"username\"\n * - \"version\"\n *\n * To later convert this string to a serialized `AuthenticationRecord`, please use the exported function `deserializeAuthenticationRecord()`.\n */\nexport function serializeAuthenticationRecord(record: AuthenticationRecord): string {\n return JSON.stringify(record);\n}\n\n/**\n * Deserializes a previously serialized authentication record from a string into an object.\n *\n * The input string must contain the following properties:\n *\n * - \"authority\"\n * - \"homeAccountId\"\n * - \"clientId\"\n * - \"tenantId\"\n * - \"username\"\n * - \"version\"\n *\n * If the version we receive is unsupported, an error will be thrown.\n *\n * At the moment, the only available version is: \"1.0\", which is always set when the authentication record is serialized.\n *\n * @param serializedRecord - Authentication record previously serialized into string.\n * @returns AuthenticationRecord.\n */\nexport function deserializeAuthenticationRecord(serializedRecord: string): AuthenticationRecord {\n const parsed: AuthenticationRecord & { version?: string } = JSON.parse(serializedRecord);\n\n if (parsed.version && parsed.version !== LatestAuthenticationRecordVersion) {\n throw Error(\"Unsupported AuthenticationRecord version\");\n }\n\n return parsed;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tokenCredentialOptions.js","sourceRoot":"","sources":["../../src/tokenCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { CommonClientOptions } from \"@azure/core-client\";\nimport { LogPolicyOptions } from \"@azure/core-rest-pipeline\";\n\n/**\n * Provides options to configure how the Identity library makes authentication\n * requests to Azure Active Directory.\n */\nexport interface TokenCredentialOptions extends CommonClientOptions {\n /**\n * The authority host to use for authentication requests.\n * Possible values are available through {@link AzureAuthorityHosts}.\n * The default is \"https://login.microsoftonline.com\".\n */\n authorityHost?: string;\n /**\n *
|
|
1
|
+
{"version":3,"file":"tokenCredentialOptions.js","sourceRoot":"","sources":["../../src/tokenCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { CommonClientOptions } from \"@azure/core-client\";\nimport { LogPolicyOptions } from \"@azure/core-rest-pipeline\";\n\n/**\n * Provides options to configure how the Identity library makes authentication\n * requests to Azure Active Directory.\n */\nexport interface TokenCredentialOptions extends CommonClientOptions {\n /**\n * The authority host to use for authentication requests.\n * Possible values are available through {@link AzureAuthorityHosts}.\n * The default is \"https://login.microsoftonline.com\".\n */\n authorityHost?: string;\n /**\n * Allows logging account information once the authentication flow succeeds.\n */\n loggingOptions?: LogPolicyOptions & {\n allowLoggingAccountIdentifiers?: boolean;\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@azure/identity",
|
|
3
3
|
"sdk-type": "client",
|
|
4
|
-
"version": "2.1.0-alpha.
|
|
4
|
+
"version": "2.1.0-alpha.20220404.1",
|
|
5
5
|
"description": "Provides credential implementations for Azure SDK libraries that can authenticate with Azure Active Directory",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"module": "dist-esm/src/index.js",
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
"format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
|
|
52
52
|
"check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
|
|
53
53
|
"integration-test:browser": "echo skipped",
|
|
54
|
-
"integration-test:node": "dev-tool run test:node-js-input -- --timeout 180000 'dist-esm/test/public/node/*.spec.js'",
|
|
54
|
+
"integration-test:node": "dev-tool run test:node-js-input -- --timeout 180000 'dist-esm/test/public/node/*.spec.js' 'dist-esm/test/internal/node/*.spec.js'",
|
|
55
55
|
"integration-test": "npm run integration-test:node && npm run integration-test:browser",
|
|
56
56
|
"lint:fix": "eslint package.json api-extractor.json src test --ext .ts --fix --fix-type [problem,suggestion]",
|
|
57
57
|
"lint": "eslint package.json api-extractor.json src test --ext .ts",
|
package/types/identity.d.ts
CHANGED
|
@@ -358,11 +358,22 @@ export declare class ClientCertificateCredential implements TokenCredential {
|
|
|
358
358
|
*
|
|
359
359
|
* @param tenantId - The Azure Active Directory tenant (directory) ID.
|
|
360
360
|
* @param clientId - The client (application) ID of an App Registration in the tenant.
|
|
361
|
-
* @param configuration - Other parameters required, including the
|
|
362
|
-
* If the type is ignored, we will throw
|
|
361
|
+
* @param configuration - Other parameters required, including the path of the certificate on the filesystem.
|
|
362
|
+
* If the type is ignored, we will throw the value of the path to a PEM certificate.
|
|
363
363
|
* @param options - Options for configuring the client which makes the authentication request.
|
|
364
364
|
*/
|
|
365
|
-
constructor(tenantId: string, clientId: string, configuration:
|
|
365
|
+
constructor(tenantId: string, clientId: string, configuration: ClientCertificatePEMCertificatePath, options?: ClientCertificateCredentialOptions);
|
|
366
|
+
/**
|
|
367
|
+
* Creates an instance of the ClientCertificateCredential with the details
|
|
368
|
+
* needed to authenticate against Azure Active Directory with a certificate.
|
|
369
|
+
*
|
|
370
|
+
* @param tenantId - The Azure Active Directory tenant (directory) ID.
|
|
371
|
+
* @param clientId - The client (application) ID of an App Registration in the tenant.
|
|
372
|
+
* @param configuration - Other parameters required, including the PEM-encoded certificate as a string.
|
|
373
|
+
* If the type is ignored, we will throw the value of the PEM-encoded certificate.
|
|
374
|
+
* @param options - Options for configuring the client which makes the authentication request.
|
|
375
|
+
*/
|
|
376
|
+
constructor(tenantId: string, clientId: string, configuration: ClientCertificatePEMCertificate, options?: ClientCertificateCredentialOptions);
|
|
366
377
|
/**
|
|
367
378
|
* Authenticates with Azure Active Directory and returns an access token if successful.
|
|
368
379
|
* If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
|
|
@@ -388,25 +399,27 @@ export declare interface ClientCertificateCredentialOptions extends TokenCredent
|
|
|
388
399
|
/**
|
|
389
400
|
* Required configuration options for the {@link ClientCertificateCredential}, with either the string contents of a PEM certificate, or the path to a PEM certificate.
|
|
390
401
|
*/
|
|
391
|
-
export declare type ClientCertificateCredentialPEMConfiguration =
|
|
402
|
+
export declare type ClientCertificateCredentialPEMConfiguration = ClientCertificatePEMCertificate | ClientCertificatePEMCertificatePath;
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Required configuration options for the {@link ClientCertificateCredential}, with the string contents of a PEM certificate
|
|
406
|
+
*/
|
|
407
|
+
export declare interface ClientCertificatePEMCertificate {
|
|
392
408
|
/**
|
|
393
409
|
* The PEM-encoded public/private key certificate on the filesystem.
|
|
394
410
|
*/
|
|
395
411
|
certificate: string;
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
* The PEM-encoded public/private key certificate on the filesystem should not be provided if `certificatePath` is provided.
|
|
403
|
-
*/
|
|
404
|
-
certificate?: never;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Required configuration options for the {@link ClientCertificateCredential}, with the path to a PEM certificate.
|
|
416
|
+
*/
|
|
417
|
+
export declare interface ClientCertificatePEMCertificatePath {
|
|
405
418
|
/**
|
|
406
419
|
* The path to the PEM-encoded public/private key certificate on the filesystem.
|
|
407
420
|
*/
|
|
408
421
|
certificatePath: string;
|
|
409
|
-
}
|
|
422
|
+
}
|
|
410
423
|
|
|
411
424
|
/**
|
|
412
425
|
* Enables authentication to Azure Active Directory using a client secret
|
|
@@ -503,7 +516,55 @@ export declare const CredentialUnavailableErrorName = "CredentialUnavailableErro
|
|
|
503
516
|
*/
|
|
504
517
|
export declare class DefaultAzureCredential extends ChainedTokenCredential {
|
|
505
518
|
/**
|
|
506
|
-
* Creates an instance of the DefaultAzureCredential class
|
|
519
|
+
* Creates an instance of the DefaultAzureCredential class with {@link DefaultAzureCredentialClientIdOptions}
|
|
520
|
+
*
|
|
521
|
+
* This credential provides a default {@link ChainedTokenCredential} configuration that should
|
|
522
|
+
* work for most applications that use the Azure SDK.
|
|
523
|
+
*
|
|
524
|
+
* The following credential types will be tried, in order:
|
|
525
|
+
*
|
|
526
|
+
* - {@link EnvironmentCredential}
|
|
527
|
+
* - {@link ManagedIdentityCredential}
|
|
528
|
+
* - {@link VisualStudioCodeCredential}
|
|
529
|
+
* - {@link AzureCliCredential}
|
|
530
|
+
* - {@link AzurePowerShellCredential}
|
|
531
|
+
*
|
|
532
|
+
* Consult the documentation of these credential types for more information
|
|
533
|
+
* on how they attempt authentication.
|
|
534
|
+
*
|
|
535
|
+
* **Note**: `VisualStudioCodeCredential` is provided by a plugin package:
|
|
536
|
+
* `@azure/identity-vscode`. If this package is not installed and registered
|
|
537
|
+
* using the plugin API (`useIdentityPlugin`), then authentication using
|
|
538
|
+
* `VisualStudioCodeCredential` will not be available.
|
|
539
|
+
* @param options - Optional parameters. See {@link DefaultAzureCredentialClientIdOptions}.
|
|
540
|
+
*/
|
|
541
|
+
constructor(options?: DefaultAzureCredentialClientIdOptions);
|
|
542
|
+
/**
|
|
543
|
+
* Creates an instance of the DefaultAzureCredential class with {@link DefaultAzureCredentialResourceIdOptions}
|
|
544
|
+
*
|
|
545
|
+
* This credential provides a default {@link ChainedTokenCredential} configuration that should
|
|
546
|
+
* work for most applications that use the Azure SDK.
|
|
547
|
+
*
|
|
548
|
+
* The following credential types will be tried, in order:
|
|
549
|
+
*
|
|
550
|
+
* - {@link EnvironmentCredential}
|
|
551
|
+
* - {@link ManagedIdentityCredential}
|
|
552
|
+
* - {@link VisualStudioCodeCredential}
|
|
553
|
+
* - {@link AzureCliCredential}
|
|
554
|
+
* - {@link AzurePowerShellCredential}
|
|
555
|
+
*
|
|
556
|
+
* Consult the documentation of these credential types for more information
|
|
557
|
+
* on how they attempt authentication.
|
|
558
|
+
*
|
|
559
|
+
* **Note**: `VisualStudioCodeCredential` is provided by a plugin package:
|
|
560
|
+
* `@azure/identity-vscode`. If this package is not installed and registered
|
|
561
|
+
* using the plugin API (`useIdentityPlugin`), then authentication using
|
|
562
|
+
* `VisualStudioCodeCredential` will not be available.
|
|
563
|
+
* @param options - Optional parameters. See {@link DefaultAzureCredentialResourceIdOptions}.
|
|
564
|
+
*/
|
|
565
|
+
constructor(options?: DefaultAzureCredentialResourceIdOptions);
|
|
566
|
+
/**
|
|
567
|
+
* Creates an instance of the DefaultAzureCredential class with {@link DefaultAzureCredentialOptions}
|
|
507
568
|
*
|
|
508
569
|
* This credential provides a default {@link ChainedTokenCredential} configuration that should
|
|
509
570
|
* work for most applications that use the Azure SDK.
|
|
@@ -533,12 +594,7 @@ export declare class DefaultAzureCredential extends ChainedTokenCredential {
|
|
|
533
594
|
* Provides options to configure the {@link DefaultAzureCredential} class.
|
|
534
595
|
* This variation supports `managedIdentityClientId` and not `managedIdentityResourceId`, since only one of both is supported.
|
|
535
596
|
*/
|
|
536
|
-
export declare interface DefaultAzureCredentialClientIdOptions extends
|
|
537
|
-
/**
|
|
538
|
-
* Optionally pass in a Tenant ID to be used as part of the credential.
|
|
539
|
-
* By default it may use a generic tenant ID depending on the underlying credential.
|
|
540
|
-
*/
|
|
541
|
-
tenantId?: string;
|
|
597
|
+
export declare interface DefaultAzureCredentialClientIdOptions extends DefaultAzureCredentialOptions {
|
|
542
598
|
/**
|
|
543
599
|
* Optionally pass in a user assigned client ID to be used by the {@link ManagedIdentityCredential}.
|
|
544
600
|
* This client ID can also be passed through to the {@link ManagedIdentityCredential} through the environment variable: AZURE_CLIENT_ID.
|
|
@@ -549,18 +605,19 @@ export declare interface DefaultAzureCredentialClientIdOptions extends TokenCred
|
|
|
549
605
|
/**
|
|
550
606
|
* Provides options to configure the {@link DefaultAzureCredential} class.
|
|
551
607
|
*/
|
|
552
|
-
export declare
|
|
553
|
-
|
|
554
|
-
/**
|
|
555
|
-
* Provides options to configure the {@link DefaultAzureCredential} class.
|
|
556
|
-
* This variation supports `managedIdentityResourceId` and not `managedIdentityClientId`, since only one of both is supported.
|
|
557
|
-
*/
|
|
558
|
-
export declare interface DefaultAzureCredentialResourceIdOptions extends TokenCredentialOptions {
|
|
608
|
+
export declare interface DefaultAzureCredentialOptions extends TokenCredentialOptions {
|
|
559
609
|
/**
|
|
560
610
|
* Optionally pass in a Tenant ID to be used as part of the credential.
|
|
561
611
|
* By default it may use a generic tenant ID depending on the underlying credential.
|
|
562
612
|
*/
|
|
563
613
|
tenantId?: string;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/**
|
|
617
|
+
* Provides options to configure the {@link DefaultAzureCredential} class.
|
|
618
|
+
* This variation supports `managedIdentityResourceId` and not `managedIdentityClientId`, since only one of both is supported.
|
|
619
|
+
*/
|
|
620
|
+
export declare interface DefaultAzureCredentialResourceIdOptions extends DefaultAzureCredentialOptions {
|
|
564
621
|
/**
|
|
565
622
|
* Optionally pass in a resource ID to be used by the {@link ManagedIdentityCredential}.
|
|
566
623
|
* In scenarios such as when user assigned identities are created using an ARM template,
|
|
@@ -568,7 +625,7 @@ export declare interface DefaultAzureCredentialResourceIdOptions extends TokenCr
|
|
|
568
625
|
* this parameter allows programs to use these user assigned identities
|
|
569
626
|
* without having to first determine the client Id of the created identity.
|
|
570
627
|
*/
|
|
571
|
-
managedIdentityResourceId
|
|
628
|
+
managedIdentityResourceId: string;
|
|
572
629
|
}
|
|
573
630
|
|
|
574
631
|
/**
|
|
@@ -941,11 +998,17 @@ export declare class ManagedIdentityCredential implements TokenCredential {
|
|
|
941
998
|
*/
|
|
942
999
|
constructor(clientId: string, options?: TokenCredentialOptions);
|
|
943
1000
|
/**
|
|
944
|
-
* Creates an instance of ManagedIdentityCredential
|
|
1001
|
+
* Creates an instance of ManagedIdentityCredential with clientId
|
|
945
1002
|
*
|
|
946
1003
|
* @param options - Options for configuring the client which makes the access token request.
|
|
947
1004
|
*/
|
|
948
|
-
constructor(options?:
|
|
1005
|
+
constructor(options?: ManagedIdentityCredentialClientIdOptions);
|
|
1006
|
+
/**
|
|
1007
|
+
* Creates an instance of ManagedIdentityCredential with Resource Id
|
|
1008
|
+
*
|
|
1009
|
+
* @param options - Options for configuring the resource which makes the access token request.
|
|
1010
|
+
*/
|
|
1011
|
+
constructor(options?: ManagedIdentityCredentialResourceIdOptions);
|
|
949
1012
|
private cachedMSI;
|
|
950
1013
|
private cachedAvailableMSI;
|
|
951
1014
|
private authenticateManagedIdentity;
|
|
@@ -972,11 +1035,6 @@ export declare interface ManagedIdentityCredentialClientIdOptions extends TokenC
|
|
|
972
1035
|
clientId?: string;
|
|
973
1036
|
}
|
|
974
1037
|
|
|
975
|
-
/**
|
|
976
|
-
* Options to send on the {@link ManagedIdentityCredential} constructor.
|
|
977
|
-
*/
|
|
978
|
-
export declare type ManagedIdentityCredentialOptions = ManagedIdentityCredentialClientIdOptions | ManagedIdentityCredentialResourceIdOptions;
|
|
979
|
-
|
|
980
1038
|
/**
|
|
981
1039
|
* Options to send on the {@link ManagedIdentityCredential} constructor.
|
|
982
1040
|
* This variation supports `resourceId` and not `clientId`, since only one of both is supported.
|
|
@@ -989,7 +1047,7 @@ export declare interface ManagedIdentityCredentialResourceIdOptions extends Toke
|
|
|
989
1047
|
* this parameter allows programs to use these user assigned identities
|
|
990
1048
|
* without having to first determine the client Id of the created identity.
|
|
991
1049
|
*/
|
|
992
|
-
resourceId
|
|
1050
|
+
resourceId: string;
|
|
993
1051
|
}
|
|
994
1052
|
|
|
995
1053
|
/**
|
|
@@ -998,10 +1056,32 @@ export declare interface ManagedIdentityCredentialResourceIdOptions extends Toke
|
|
|
998
1056
|
export declare class OnBehalfOfCredential implements TokenCredential {
|
|
999
1057
|
private options;
|
|
1000
1058
|
private msalFlow;
|
|
1059
|
+
/**
|
|
1060
|
+
* Creates an instance of the {@link OnBehalfOfCredential} with the details
|
|
1061
|
+
* needed to authenticate against Azure Active Directory with path to a PEM certificate,
|
|
1062
|
+
* and an user assertion.
|
|
1063
|
+
*
|
|
1064
|
+
* Example using the `KeyClient` from [\@azure/keyvault-keys](https://www.npmjs.com/package/\@azure/keyvault-keys):
|
|
1065
|
+
*
|
|
1066
|
+
* ```ts
|
|
1067
|
+
* const tokenCredential = new OnBehalfOfCredential({
|
|
1068
|
+
* tenantId,
|
|
1069
|
+
* clientId,
|
|
1070
|
+
* certificatePath: "/path/to/certificate.pem",
|
|
1071
|
+
* userAssertionToken: "access-token"
|
|
1072
|
+
* });
|
|
1073
|
+
* const client = new KeyClient("vault-url", tokenCredential);
|
|
1074
|
+
*
|
|
1075
|
+
* await client.getKey("key-name");
|
|
1076
|
+
* ```
|
|
1077
|
+
*
|
|
1078
|
+
* @param options - Optional parameters, generally common across credentials.
|
|
1079
|
+
*/
|
|
1080
|
+
constructor(options: OnBehalfOfCredentialCertificateOptions & TokenCredentialOptions & CredentialPersistenceOptions);
|
|
1001
1081
|
/**
|
|
1002
1082
|
* Creates an instance of the {@link OnBehalfOfCredential} with the details
|
|
1003
1083
|
* needed to authenticate against Azure Active Directory with a client
|
|
1004
|
-
* secret
|
|
1084
|
+
* secret and an user assertion.
|
|
1005
1085
|
*
|
|
1006
1086
|
* Example using the `KeyClient` from [\@azure/keyvault-keys](https://www.npmjs.com/package/\@azure/keyvault-keys):
|
|
1007
1087
|
*
|
|
@@ -1009,7 +1089,7 @@ export declare class OnBehalfOfCredential implements TokenCredential {
|
|
|
1009
1089
|
* const tokenCredential = new OnBehalfOfCredential({
|
|
1010
1090
|
* tenantId,
|
|
1011
1091
|
* clientId,
|
|
1012
|
-
* clientSecret,
|
|
1092
|
+
* clientSecret,
|
|
1013
1093
|
* userAssertionToken: "access-token"
|
|
1014
1094
|
* });
|
|
1015
1095
|
* const client = new KeyClient("vault-url", tokenCredential);
|
|
@@ -1019,7 +1099,7 @@ export declare class OnBehalfOfCredential implements TokenCredential {
|
|
|
1019
1099
|
*
|
|
1020
1100
|
* @param options - Optional parameters, generally common across credentials.
|
|
1021
1101
|
*/
|
|
1022
|
-
constructor(options:
|
|
1102
|
+
constructor(options: OnBehalfOfCredentialSecretOptions & TokenCredentialOptions & CredentialPersistenceOptions);
|
|
1023
1103
|
/**
|
|
1024
1104
|
* Authenticates with Azure Active Directory and returns an access token if successful.
|
|
1025
1105
|
* If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
|
|
@@ -1046,19 +1126,15 @@ export declare interface OnBehalfOfCredentialCertificateOptions {
|
|
|
1046
1126
|
* The path to a PEM-encoded public/private key certificate on the filesystem.
|
|
1047
1127
|
*/
|
|
1048
1128
|
certificatePath: string;
|
|
1049
|
-
/**
|
|
1050
|
-
* Option to include x5c header for SubjectName and Issuer name authorization.
|
|
1051
|
-
* Set this option to send base64 encoded public certificate in the client assertion header as an x5c claim
|
|
1052
|
-
*/
|
|
1053
|
-
sendCertificateChain?: boolean;
|
|
1054
1129
|
/**
|
|
1055
1130
|
* The user assertion for the On-Behalf-Of flow.
|
|
1056
1131
|
*/
|
|
1057
1132
|
userAssertionToken: string;
|
|
1058
1133
|
/**
|
|
1059
|
-
*
|
|
1134
|
+
* Option to include x5c header for SubjectName and Issuer name authorization.
|
|
1135
|
+
* Set this option to send base64 encoded public certificate in the client assertion header as an x5c claim
|
|
1060
1136
|
*/
|
|
1061
|
-
|
|
1137
|
+
sendCertificateChain?: boolean;
|
|
1062
1138
|
}
|
|
1063
1139
|
|
|
1064
1140
|
/**
|
|
@@ -1086,14 +1162,6 @@ export declare interface OnBehalfOfCredentialSecretOptions {
|
|
|
1086
1162
|
* The user assertion for the On-Behalf-Of flow.
|
|
1087
1163
|
*/
|
|
1088
1164
|
userAssertionToken: string;
|
|
1089
|
-
/**
|
|
1090
|
-
* The path to a PEM-encoded certificate should not be provided when the secret options are provided.
|
|
1091
|
-
*/
|
|
1092
|
-
certificatePath?: never;
|
|
1093
|
-
/**
|
|
1094
|
-
* Option to include x5c header should not be provided when the secret options are provided.
|
|
1095
|
-
*/
|
|
1096
|
-
sendCertificateChain?: never;
|
|
1097
1165
|
}
|
|
1098
1166
|
|
|
1099
1167
|
/**
|
|
@@ -1149,10 +1217,6 @@ export declare interface TokenCredentialOptions extends CommonClientOptions {
|
|
|
1149
1217
|
* The default is "https://login.microsoftonline.com".
|
|
1150
1218
|
*/
|
|
1151
1219
|
authorityHost?: string;
|
|
1152
|
-
/**
|
|
1153
|
-
* If set to true, disables the automatic validation of the authority host.
|
|
1154
|
-
*/
|
|
1155
|
-
disableAuthorityValidation?: boolean;
|
|
1156
1220
|
/**
|
|
1157
1221
|
* Allows logging account information once the authentication flow succeeds.
|
|
1158
1222
|
*/
|