@azure/identity 2.0.0-beta.3 → 2.0.0
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 +232 -6
- package/README.md +124 -39
- package/dist/index.js +2317 -1596
- package/dist/index.js.map +1 -1
- package/dist-esm/src/client/identityClient.js +147 -133
- package/dist-esm/src/client/identityClient.js.map +1 -1
- package/dist-esm/src/constants.js +1 -1
- package/dist-esm/src/constants.js.map +1 -1
- package/dist-esm/src/credentials/authorizationCodeCredential.browser.js +1 -1
- package/dist-esm/src/credentials/authorizationCodeCredential.browser.js.map +1 -1
- package/dist-esm/src/credentials/authorizationCodeCredential.js +13 -76
- package/dist-esm/src/credentials/authorizationCodeCredential.js.map +1 -1
- package/dist-esm/src/credentials/azureApplicationCredential.browser.js +34 -0
- package/dist-esm/src/credentials/azureApplicationCredential.browser.js.map +1 -0
- package/dist-esm/src/credentials/azureApplicationCredential.js +36 -0
- package/dist-esm/src/credentials/azureApplicationCredential.js.map +1 -0
- package/dist-esm/src/credentials/azureCliCredential.browser.js +7 -0
- package/dist-esm/src/credentials/azureCliCredential.browser.js.map +1 -1
- package/dist-esm/src/credentials/azureCliCredential.js +110 -83
- package/dist-esm/src/credentials/azureCliCredential.js.map +1 -1
- package/dist-esm/src/credentials/azureCliCredentialOptions.js +4 -0
- package/dist-esm/src/credentials/azureCliCredentialOptions.js.map +1 -0
- package/dist-esm/src/credentials/azurePowerShellCredential.browser.js +3 -1
- package/dist-esm/src/credentials/azurePowerShellCredential.browser.js.map +1 -1
- package/dist-esm/src/credentials/azurePowerShellCredential.js +93 -83
- package/dist-esm/src/credentials/azurePowerShellCredential.js.map +1 -1
- package/dist-esm/src/credentials/azurePowerShellCredentialOptions.js +4 -0
- package/dist-esm/src/credentials/azurePowerShellCredentialOptions.js.map +1 -0
- package/dist-esm/src/credentials/chainedTokenCredential.js +34 -37
- package/dist-esm/src/credentials/chainedTokenCredential.js.map +1 -1
- package/dist-esm/src/credentials/clientCertificateCredential.browser.js +7 -0
- package/dist-esm/src/credentials/clientCertificateCredential.browser.js.map +1 -1
- package/dist-esm/src/credentials/clientCertificateCredential.js +24 -23
- package/dist-esm/src/credentials/clientCertificateCredential.js.map +1 -1
- package/dist-esm/src/credentials/clientCertificateCredentialOptions.js.map +1 -1
- package/dist-esm/src/credentials/clientSecretCredential.browser.js +39 -44
- package/dist-esm/src/credentials/clientSecretCredential.browser.js.map +1 -1
- package/dist-esm/src/credentials/clientSecretCredential.js +9 -11
- package/dist-esm/src/credentials/clientSecretCredential.js.map +1 -1
- package/dist-esm/src/credentials/clientSecretCredentialOptions.js.map +1 -1
- package/dist-esm/src/credentials/credentialPersistenceOptions.js +4 -0
- package/dist-esm/src/credentials/credentialPersistenceOptions.js.map +1 -0
- package/dist-esm/src/credentials/defaultAzureCredential.browser.js +1 -1
- package/dist-esm/src/credentials/defaultAzureCredential.browser.js.map +1 -1
- package/dist-esm/src/credentials/defaultAzureCredential.js +50 -27
- package/dist-esm/src/credentials/defaultAzureCredential.js.map +1 -1
- package/dist-esm/src/credentials/deviceCodeCredential.browser.js +7 -0
- package/dist-esm/src/credentials/deviceCodeCredential.browser.js.map +1 -1
- package/dist-esm/src/credentials/deviceCodeCredential.js +27 -22
- package/dist-esm/src/credentials/deviceCodeCredential.js.map +1 -1
- package/dist-esm/src/credentials/deviceCodeCredentialOptions.js.map +1 -1
- package/dist-esm/src/credentials/environmentCredential.browser.js +7 -0
- package/dist-esm/src/credentials/environmentCredential.browser.js.map +1 -1
- package/dist-esm/src/credentials/environmentCredential.js +39 -38
- package/dist-esm/src/credentials/environmentCredential.js.map +1 -1
- package/dist-esm/src/credentials/interactiveBrowserCredential.browser.js +20 -29
- package/dist-esm/src/credentials/interactiveBrowserCredential.browser.js.map +1 -1
- package/dist-esm/src/credentials/interactiveBrowserCredential.js +23 -29
- package/dist-esm/src/credentials/interactiveBrowserCredential.js.map +1 -1
- package/dist-esm/src/credentials/interactiveBrowserCredentialOptions.js.map +1 -1
- package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2017.js +36 -22
- package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2017.js.map +1 -1
- package/dist-esm/src/credentials/managedIdentityCredential/arcMsi.js +62 -47
- package/dist-esm/src/credentials/managedIdentityCredential/arcMsi.js.map +1 -1
- package/dist-esm/src/credentials/managedIdentityCredential/cloudShellMsi.js +33 -22
- package/dist-esm/src/credentials/managedIdentityCredential/cloudShellMsi.js.map +1 -1
- package/dist-esm/src/credentials/managedIdentityCredential/constants.js +2 -1
- package/dist-esm/src/credentials/managedIdentityCredential/constants.js.map +1 -1
- package/dist-esm/src/credentials/managedIdentityCredential/fabricMsi.js +42 -27
- package/dist-esm/src/credentials/managedIdentityCredential/fabricMsi.js.map +1 -1
- package/dist-esm/src/credentials/managedIdentityCredential/imdsMsi.js +115 -91
- package/dist-esm/src/credentials/managedIdentityCredential/imdsMsi.js.map +1 -1
- package/dist-esm/src/credentials/managedIdentityCredential/index.browser.js +3 -6
- package/dist-esm/src/credentials/managedIdentityCredential/index.browser.js.map +1 -1
- package/dist-esm/src/credentials/managedIdentityCredential/index.js +120 -125
- package/dist-esm/src/credentials/managedIdentityCredential/index.js.map +1 -1
- package/dist-esm/src/credentials/managedIdentityCredential/models.js.map +1 -1
- package/dist-esm/src/credentials/managedIdentityCredential/tokenExchangeMsi.js +82 -0
- package/dist-esm/src/credentials/managedIdentityCredential/tokenExchangeMsi.js.map +1 -0
- package/dist-esm/src/credentials/managedIdentityCredential/utils.js +14 -8
- package/dist-esm/src/credentials/managedIdentityCredential/utils.js.map +1 -1
- package/dist-esm/src/credentials/onBehalfOfCredential.browser.js +23 -0
- package/dist-esm/src/credentials/onBehalfOfCredential.browser.js.map +1 -0
- package/dist-esm/src/credentials/onBehalfOfCredential.js +57 -0
- package/dist-esm/src/credentials/onBehalfOfCredential.js.map +1 -0
- package/dist-esm/src/credentials/onBehalfOfCredentialOptions.js +4 -0
- package/dist-esm/src/credentials/onBehalfOfCredentialOptions.js.map +1 -0
- package/dist-esm/src/credentials/usernamePasswordCredential.browser.js +41 -46
- package/dist-esm/src/credentials/usernamePasswordCredential.browser.js.map +1 -1
- package/dist-esm/src/credentials/usernamePasswordCredential.js +9 -13
- package/dist-esm/src/credentials/usernamePasswordCredential.js.map +1 -1
- package/dist-esm/src/credentials/usernamePasswordCredentialOptions.js.map +1 -1
- package/dist-esm/src/credentials/visualStudioCodeCredential.browser.js +27 -0
- package/dist-esm/src/credentials/visualStudioCodeCredential.browser.js.map +1 -0
- package/dist-esm/src/credentials/visualStudioCodeCredential.js +183 -0
- package/dist-esm/src/credentials/visualStudioCodeCredential.js.map +1 -0
- package/dist-esm/src/credentials/visualStudioCodeCredentialPlugin.js +4 -0
- package/dist-esm/src/credentials/visualStudioCodeCredentialPlugin.js.map +1 -0
- package/dist-esm/src/{client/errors.js → errors.js} +16 -1
- package/dist-esm/src/errors.js.map +1 -0
- package/dist-esm/src/index.js +4 -2
- package/dist-esm/src/index.js.map +1 -1
- package/dist-esm/src/msal/browserFlows/browserCommon.js +33 -31
- package/dist-esm/src/msal/browserFlows/browserCommon.js.map +1 -1
- package/dist-esm/src/msal/browserFlows/msalAuthCode.js +113 -115
- package/dist-esm/src/msal/browserFlows/msalAuthCode.js.map +1 -1
- package/dist-esm/src/msal/credentials.js.map +1 -1
- package/dist-esm/src/msal/flows.js.map +1 -1
- package/dist-esm/src/msal/nodeFlows/msalAuthorizationCode.js +41 -0
- package/dist-esm/src/msal/nodeFlows/msalAuthorizationCode.js.map +1 -0
- package/dist-esm/src/msal/nodeFlows/msalClientCertificate.js +65 -46
- package/dist-esm/src/msal/nodeFlows/msalClientCertificate.js.map +1 -1
- package/dist-esm/src/msal/nodeFlows/msalClientSecret.js +15 -16
- package/dist-esm/src/msal/nodeFlows/msalClientSecret.js.map +1 -1
- package/dist-esm/src/msal/nodeFlows/msalDeviceCode.js +20 -22
- package/dist-esm/src/msal/nodeFlows/msalDeviceCode.js.map +1 -1
- package/dist-esm/src/msal/nodeFlows/msalOnBehalfOf.js +56 -0
- package/dist-esm/src/msal/nodeFlows/msalOnBehalfOf.js.map +1 -0
- package/dist-esm/src/msal/nodeFlows/msalOpenBrowser.js +44 -33
- package/dist-esm/src/msal/nodeFlows/msalOpenBrowser.js.map +1 -1
- package/dist-esm/src/msal/nodeFlows/msalUsernamePassword.js +15 -17
- package/dist-esm/src/msal/nodeFlows/msalUsernamePassword.js.map +1 -1
- package/dist-esm/src/msal/nodeFlows/nodeCommon.js +141 -98
- package/dist-esm/src/msal/nodeFlows/nodeCommon.js.map +1 -1
- package/dist-esm/src/msal/nodeFlows/tokenCachePersistenceOptions.js +4 -0
- package/dist-esm/src/msal/nodeFlows/tokenCachePersistenceOptions.js.map +1 -0
- package/dist-esm/src/msal/utils.js +23 -15
- package/dist-esm/src/msal/utils.js.map +1 -1
- package/dist-esm/src/plugins/consumer.browser.js +7 -0
- package/dist-esm/src/plugins/consumer.browser.js.map +1 -0
- package/dist-esm/src/plugins/consumer.js +44 -0
- package/dist-esm/src/plugins/consumer.js.map +1 -0
- package/dist-esm/src/plugins/provider.js +4 -0
- package/dist-esm/src/plugins/provider.js.map +1 -0
- package/dist-esm/src/regionalAuthority.js +115 -0
- package/dist-esm/src/regionalAuthority.js.map +1 -0
- package/dist-esm/src/util/tracing.js +24 -27
- package/dist-esm/src/util/tracing.js.map +1 -1
- package/dist-esm/src/util/validateMultiTenant.browser.js +22 -0
- package/dist-esm/src/util/validateMultiTenant.browser.js.map +1 -0
- package/dist-esm/src/util/validateMultiTenant.js +29 -0
- package/dist-esm/src/util/validateMultiTenant.js.map +1 -0
- package/package.json +44 -28
- package/types/identity.d.ts +482 -126
- package/dist-esm/src/client/errors.js.map +0 -1
- package/dist-esm/src/msal/errors.js +0 -22
- package/dist-esm/src/msal/errors.js.map +0 -1
- package/dist-esm/src/util/authHostEnv.js +0 -13
- package/dist-esm/src/util/authHostEnv.js.map +0 -1
|
@@ -1,14 +1,29 @@
|
|
|
1
1
|
// Copyright (c) Microsoft Corporation.
|
|
2
2
|
// Licensed under the MIT license.
|
|
3
|
-
import { __awaiter } from "tslib";
|
|
4
3
|
import * as msalNode from "@azure/msal-node";
|
|
5
4
|
import { DeveloperSignOnClientId } from "../../constants";
|
|
6
5
|
import { IdentityClient } from "../../client/identityClient";
|
|
7
6
|
import { resolveTenantId } from "../../util/resolveTenantId";
|
|
8
|
-
import { AuthenticationRequiredError } from "
|
|
9
|
-
import { defaultLoggerCallback,
|
|
7
|
+
import { AuthenticationRequiredError } from "../../errors";
|
|
8
|
+
import { defaultLoggerCallback, getAuthority, getKnownAuthorities, MsalBaseUtilities, msalToPublic, publicToMsal } from "../utils";
|
|
9
|
+
import { processMultiTenantRequest } from "../../util/validateMultiTenant";
|
|
10
|
+
import { RegionalAuthority } from "../../regionalAuthority";
|
|
10
11
|
/**
|
|
11
|
-
*
|
|
12
|
+
* The current persistence provider, undefined by default.
|
|
13
|
+
* @internal
|
|
14
|
+
*/
|
|
15
|
+
let persistenceProvider = undefined;
|
|
16
|
+
/**
|
|
17
|
+
* An object that allows setting the persistence provider.
|
|
18
|
+
* @internal
|
|
19
|
+
*/
|
|
20
|
+
export const msalNodeFlowCacheControl = {
|
|
21
|
+
setPersistence(pluginProvider) {
|
|
22
|
+
persistenceProvider = pluginProvider;
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* MSAL partial base client for Node.js.
|
|
12
27
|
*
|
|
13
28
|
* It completes the input configuration with some default values.
|
|
14
29
|
* It also provides with utility protected methods that can be used from any of the clients,
|
|
@@ -18,24 +33,48 @@ import { defaultLoggerCallback, getAuthorityHost, getKnownAuthorities, MsalBaseU
|
|
|
18
33
|
*/
|
|
19
34
|
export class MsalNode extends MsalBaseUtilities {
|
|
20
35
|
constructor(options) {
|
|
36
|
+
var _a, _b, _c;
|
|
21
37
|
super(options);
|
|
22
38
|
this.requiresConfidential = false;
|
|
23
39
|
this.msalConfig = this.defaultNodeMsalConfig(options);
|
|
40
|
+
this.tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);
|
|
24
41
|
this.clientId = this.msalConfig.auth.clientId;
|
|
42
|
+
// If persistence has been configured
|
|
43
|
+
if (persistenceProvider !== undefined && ((_a = options.tokenCachePersistenceOptions) === null || _a === void 0 ? void 0 : _a.enabled)) {
|
|
44
|
+
this.createCachePlugin = () => persistenceProvider(options.tokenCachePersistenceOptions);
|
|
45
|
+
}
|
|
46
|
+
else if ((_b = options.tokenCachePersistenceOptions) === null || _b === void 0 ? void 0 : _b.enabled) {
|
|
47
|
+
throw new Error([
|
|
48
|
+
"Persistent token caching was requested, but no persistence provider was configured.",
|
|
49
|
+
"You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)",
|
|
50
|
+
"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling",
|
|
51
|
+
"`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`."
|
|
52
|
+
].join(" "));
|
|
53
|
+
}
|
|
54
|
+
this.azureRegion = (_c = options.regionalAuthority) !== null && _c !== void 0 ? _c : process.env.AZURE_REGIONAL_AUTHORITY_NAME;
|
|
55
|
+
if (this.azureRegion === RegionalAuthority.AutoDiscoverRegion) {
|
|
56
|
+
this.azureRegion = "AUTO_DISCOVER";
|
|
57
|
+
}
|
|
25
58
|
}
|
|
26
59
|
/**
|
|
27
|
-
* Generates a MSAL configuration that generally works for
|
|
60
|
+
* Generates a MSAL configuration that generally works for Node.js
|
|
28
61
|
*/
|
|
29
62
|
defaultNodeMsalConfig(options) {
|
|
30
63
|
const clientId = options.clientId || DeveloperSignOnClientId;
|
|
31
64
|
const tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);
|
|
32
|
-
|
|
33
|
-
|
|
65
|
+
this.authorityHost = options.authorityHost || process.env.AZURE_AUTHORITY_HOST;
|
|
66
|
+
const authority = getAuthority(tenantId, this.authorityHost);
|
|
67
|
+
this.identityClient = new IdentityClient(Object.assign(Object.assign({}, options.tokenCredentialOptions), { authorityHost: authority }));
|
|
68
|
+
let clientCapabilities = ["CP1"];
|
|
69
|
+
if (process.env.AZURE_IDENTITY_DISABLE_CP1) {
|
|
70
|
+
clientCapabilities = [];
|
|
71
|
+
}
|
|
34
72
|
return {
|
|
35
73
|
auth: {
|
|
36
74
|
clientId,
|
|
37
|
-
authority
|
|
38
|
-
knownAuthorities: getKnownAuthorities(tenantId,
|
|
75
|
+
authority,
|
|
76
|
+
knownAuthorities: getKnownAuthorities(tenantId, authority),
|
|
77
|
+
clientCapabilities
|
|
39
78
|
},
|
|
40
79
|
// Cache is defined in this.prepare();
|
|
41
80
|
system: {
|
|
@@ -49,31 +88,34 @@ export class MsalNode extends MsalBaseUtilities {
|
|
|
49
88
|
/**
|
|
50
89
|
* Prepares the MSAL applications.
|
|
51
90
|
*/
|
|
52
|
-
init(options) {
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
this.
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
91
|
+
async init(options) {
|
|
92
|
+
if (options === null || options === void 0 ? void 0 : options.abortSignal) {
|
|
93
|
+
options.abortSignal.addEventListener("abort", () => {
|
|
94
|
+
// This will abort any pending request in the IdentityClient,
|
|
95
|
+
// based on the received or generated correlationId
|
|
96
|
+
this.identityClient.abortRequests(options.correlationId);
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
if (this.publicApp || this.confidentialApp) {
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (this.createCachePlugin !== undefined) {
|
|
103
|
+
this.msalConfig.cache = {
|
|
104
|
+
cachePlugin: await this.createCachePlugin()
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
this.publicApp = new msalNode.PublicClientApplication(this.msalConfig);
|
|
108
|
+
// The confidential client requires either a secret, assertion or certificate.
|
|
109
|
+
if (this.msalConfig.auth.clientSecret ||
|
|
110
|
+
this.msalConfig.auth.clientAssertion ||
|
|
111
|
+
this.msalConfig.auth.clientCertificate) {
|
|
112
|
+
this.confidentialApp = new msalNode.ConfidentialClientApplication(this.msalConfig);
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
if (this.requiresConfidential) {
|
|
116
|
+
throw new Error("Unable to generate the MSAL confidential client. Missing either the client's secret, certificate or assertion.");
|
|
75
117
|
}
|
|
76
|
-
}
|
|
118
|
+
}
|
|
77
119
|
}
|
|
78
120
|
/**
|
|
79
121
|
* Allows the cancellation of a MSAL request.
|
|
@@ -95,84 +137,85 @@ export class MsalNode extends MsalBaseUtilities {
|
|
|
95
137
|
/**
|
|
96
138
|
* Returns the existing account, attempts to load the account from MSAL.
|
|
97
139
|
*/
|
|
98
|
-
getActiveAccount() {
|
|
99
|
-
var _a;
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
this.
|
|
114
|
-
.info(`More than one account was found authenticated for this Client ID and Tenant ID.
|
|
140
|
+
async getActiveAccount() {
|
|
141
|
+
var _a, _b, _c;
|
|
142
|
+
if (this.account) {
|
|
143
|
+
return this.account;
|
|
144
|
+
}
|
|
145
|
+
const cache = (_b = (_a = this.confidentialApp) === null || _a === void 0 ? void 0 : _a.getTokenCache()) !== null && _b !== void 0 ? _b : (_c = this.publicApp) === null || _c === void 0 ? void 0 : _c.getTokenCache();
|
|
146
|
+
const accountsByTenant = await (cache === null || cache === void 0 ? void 0 : cache.getAllAccounts());
|
|
147
|
+
if (!accountsByTenant) {
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (accountsByTenant.length === 1) {
|
|
151
|
+
this.account = msalToPublic(this.clientId, accountsByTenant[0]);
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
this.logger
|
|
155
|
+
.info(`More than one account was found authenticated for this Client ID and Tenant ID.
|
|
115
156
|
However, no "authenticationRecord" has been provided for this credential,
|
|
116
157
|
therefore we're unable to pick between these accounts.
|
|
117
158
|
A new login attempt will be requested, to ensure the correct account is picked.
|
|
118
159
|
To 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.`);
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
});
|
|
123
|
-
}
|
|
124
|
-
/**
|
|
125
|
-
* Clears MSAL's cache.
|
|
126
|
-
*/
|
|
127
|
-
logout() {
|
|
128
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
129
|
-
// Intentionally empty
|
|
130
|
-
});
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
return this.account;
|
|
131
163
|
}
|
|
132
164
|
/**
|
|
133
165
|
* Attempts to retrieve a token from cache.
|
|
134
166
|
*/
|
|
135
|
-
getTokenSilent(scopes, options) {
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
167
|
+
async getTokenSilent(scopes, options) {
|
|
168
|
+
var _a, _b;
|
|
169
|
+
await this.getActiveAccount();
|
|
170
|
+
if (!this.account) {
|
|
171
|
+
throw new AuthenticationRequiredError({
|
|
172
|
+
scopes,
|
|
173
|
+
getTokenOptions: options,
|
|
174
|
+
message: "Silent authentication failed. We couldn't retrieve an active account from the cache."
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
const silentRequest = {
|
|
178
|
+
// To be able to re-use the account, the Token Cache must also have been provided.
|
|
179
|
+
account: publicToMsal(this.account),
|
|
180
|
+
correlationId: options === null || options === void 0 ? void 0 : options.correlationId,
|
|
181
|
+
scopes,
|
|
182
|
+
authority: options === null || options === void 0 ? void 0 : options.authority
|
|
183
|
+
};
|
|
184
|
+
try {
|
|
185
|
+
this.logger.info("Attempting to acquire token silently");
|
|
186
|
+
const response = (_b = (await ((_a = this.confidentialApp) === null || _a === void 0 ? void 0 : _a.acquireTokenSilent(silentRequest)))) !== null && _b !== void 0 ? _b : (await this.publicApp.acquireTokenSilent(silentRequest));
|
|
187
|
+
return this.handleResult(scopes, this.clientId, response || undefined);
|
|
188
|
+
}
|
|
189
|
+
catch (err) {
|
|
190
|
+
throw this.handleError(scopes, err, options);
|
|
191
|
+
}
|
|
156
192
|
}
|
|
157
193
|
/**
|
|
158
194
|
* Wrapper around each MSAL flow get token operation: doGetToken.
|
|
159
195
|
* If disableAutomaticAuthentication is sent through the constructor, it will prevent MSAL from requesting the user input.
|
|
160
196
|
*/
|
|
161
|
-
getToken(scopes, options = {}) {
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
197
|
+
async getToken(scopes, options = {}) {
|
|
198
|
+
const tenantId = processMultiTenantRequest(this.tenantId, options) || this.tenantId;
|
|
199
|
+
options.authority = getAuthority(tenantId, this.authorityHost);
|
|
200
|
+
options.correlationId = (options === null || options === void 0 ? void 0 : options.correlationId) || this.generateUuid();
|
|
201
|
+
await this.init(options);
|
|
202
|
+
try {
|
|
203
|
+
return await this.getTokenSilent(scopes, options);
|
|
204
|
+
}
|
|
205
|
+
catch (err) {
|
|
206
|
+
if (err.name !== "AuthenticationRequiredError") {
|
|
207
|
+
throw err;
|
|
208
|
+
}
|
|
209
|
+
if (options === null || options === void 0 ? void 0 : options.disableAutomaticAuthentication) {
|
|
210
|
+
throw new AuthenticationRequiredError({
|
|
211
|
+
scopes,
|
|
212
|
+
getTokenOptions: options,
|
|
213
|
+
message: "Automatic authentication has been disabled. You may call the authentication() method."
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
this.logger.info(`Silent authentication failed, falling back to interactive method.`);
|
|
217
|
+
return this.doGetToken(scopes, options);
|
|
218
|
+
}
|
|
176
219
|
}
|
|
177
220
|
}
|
|
178
221
|
//# sourceMappingURL=nodeCommon.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nodeCommon.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/nodeCommon.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAElC,OAAO,KAAK,QAAQ,MAAM,kBAAkB,CAAC;AAI7C,OAAO,EAAE,uBAAuB,EAAE,MAAM,iBAAiB,CAAC;AAC1D,OAAO,EAAE,cAAc,EAA0B,MAAM,6BAA6B,CAAC;AACrF,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAG7D,OAAO,EAAE,2BAA2B,EAAE,MAAM,WAAW,CAAC;AAExD,OAAO,EACL,qBAAqB,EACrB,gBAAgB,EAChB,mBAAmB,EACnB,iBAAiB,EACjB,YAAY,EACZ,YAAY,EACb,MAAM,UAAU,CAAC;AAUlB;;;;;;;;GAQG;AACH,MAAM,OAAgB,QAAS,SAAQ,iBAAiB;IAQtD,YAAY,OAAwB;QAClC,KAAK,CAAC,OAAO,CAAC,CAAC;QAHP,yBAAoB,GAAY,KAAK,CAAC;QAI9C,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,qBAAqB,CAAC,OAAO,CAAC,CAAC;QACtD,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,UAAU,CA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AAP,OAAO,uBAAP,OAAO,CAAE,aAAa,KAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtE,MAAM,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACzB,OAAO,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;gBACxD,IAAI,GAAG,CAAC,IAAI,KAAK,6BAA6B,EAAE;oBAC9C,MAAM,GAAG,CAAC;iBACX;gBACD,IAAI,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,8BAA8B,EAAE;oBAC3C,MAAM,IAAI,2BAA2B,CACnC,MAAM,EACN,OAAO,EACP,uFAAuF,CACxF,CAAC;iBACH;gBACD,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,mEAAmE,CAAC,CAAC;gBACtF,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;YAC1C,CAAC,CAAC,CAAC;QACL,CAAC;KAAA;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-http\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { DeveloperSignOnClientId } from \"../../constants\";\nimport { IdentityClient, TokenCredentialOptions } from \"../../client/identityClient\";\nimport { resolveTenantId } from \"../../util/resolveTenantId\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { MsalFlow, MsalFlowOptions } from \"../flows\";\nimport { AuthenticationRequiredError } from \"../errors\";\nimport { AuthenticationRecord } from \"../types\";\nimport {\n defaultLoggerCallback,\n getAuthorityHost,\n getKnownAuthorities,\n MsalBaseUtilities,\n msalToPublic,\n publicToMsal\n} from \"../utils\";\n\n/**\n * Union of the constructor parameters that all MSAL flow types for Node.\n * @internal\n */\nexport interface MsalNodeOptions extends MsalFlowOptions {\n tokenCredentialOptions: TokenCredentialOptions;\n}\n\n/**\n * MSAL partial base client for NodeJS.\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 identityClient?: IdentityClient;\n protected requiresConfidential: boolean = false;\n\n constructor(options: MsalNodeOptions) {\n super(options);\n this.msalConfig = this.defaultNodeMsalConfig(options);\n this.clientId = this.msalConfig.auth.clientId;\n }\n\n /**\n * Generates a MSAL configuration that generally works for NodeJS\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 const authorityHost = getAuthorityHost(tenantId, options.authorityHost);\n this.identityClient = new IdentityClient({\n ...options.tokenCredentialOptions,\n authorityHost\n });\n return {\n auth: {\n clientId,\n authority: authorityHost,\n knownAuthorities: getKnownAuthorities(tenantId, authorityHost)\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 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.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 * Clears MSAL's cache.\n */\n async logout(): Promise<void> {\n // Intentionally empty\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(scopes, options);\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 };\n\n try {\n this.logger.info(\"Attempting to acquire token silently\");\n const response = 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 options.correlationId = options?.correlationId || this.generateUuid();\n await this.init(options);\n return this.getTokenSilent(scopes, options).catch((err) => {\n if (err.name !== \"AuthenticationRequiredError\") {\n throw err;\n }\n if (options?.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError(\n scopes,\n options,\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":"nodeCommon.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/nodeCommon.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,QAAQ,MAAM,kBAAkB,CAAC;AAM7C,OAAO,EAAE,uBAAuB,EAAE,MAAM,iBAAiB,CAAC;AAC1D,OAAO,EAAE,cAAc,EAA0B,MAAM,6BAA6B,CAAC;AACrF,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,EACb,MAAM,UAAU,CAAC;AAElB,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OA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P,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\";\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\n\nimport { DeveloperSignOnClientId } from \"../../constants\";\nimport { IdentityClient, TokenCredentialOptions } from \"../../client/identityClient\";\nimport { resolveTenantId } from \"../../util/resolveTenantId\";\nimport { AuthenticationRequiredError } from \"../../errors\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { MsalFlow, MsalFlowOptions } from \"../flows\";\nimport { AuthenticationRecord } from \"../types\";\nimport {\n defaultLoggerCallback,\n getAuthority,\n getKnownAuthorities,\n MsalBaseUtilities,\n msalToPublic,\n publicToMsal\n} from \"../utils\";\nimport { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions\";\nimport { processMultiTenantRequest } from \"../../util/validateMultiTenant\";\nimport { RegionalAuthority } from \"../../regionalAuthority\";\n\n/**\n * Union of the constructor parameters that all MSAL flow types for Node.\n * @internal\n */\nexport interface MsalNodeOptions extends MsalFlowOptions {\n tokenCachePersistenceOptions?: TokenCachePersistenceOptions;\n tokenCredentialOptions: TokenCredentialOptions;\n /**\n * Specifies a regional authority. Please refer to the {@link RegionalAuthority} type for the accepted values.\n * If {@link RegionalAuthority.AutoDiscoverRegion} is specified, we will try to discover the regional authority endpoint.\n * If the property is not specified, uses a non-regional authority endpoint.\n */\n regionalAuthority?: string;\n}\n\n/**\n * The current persistence provider, undefined by default.\n * @internal\n */\nlet persistenceProvider:\n | ((options?: TokenCachePersistenceOptions) => Promise<msalCommon.ICachePlugin>)\n | undefined = undefined;\n\n/**\n * An object that allows setting the persistence provider.\n * @internal\n */\nexport const msalNodeFlowCacheControl = {\n setPersistence(pluginProvider: Exclude<typeof persistenceProvider, undefined>): void {\n persistenceProvider = pluginProvider;\n }\n};\n\n/**\n * MSAL partial base client for Node.js.\n *\n * It completes the input configuration with some default values.\n * It also provides with utility protected methods that can be used from any of the clients,\n * which includes handlers for successful responses and errors.\n *\n * @internal\n */\nexport abstract class MsalNode extends MsalBaseUtilities implements MsalFlow {\n protected publicApp: msalNode.PublicClientApplication | undefined;\n protected confidentialApp: msalNode.ConfidentialClientApplication | undefined;\n protected msalConfig: msalNode.Configuration;\n protected clientId: string;\n protected tenantId: string;\n protected authorityHost?: string;\n protected identityClient?: IdentityClient;\n protected requiresConfidential: boolean = false;\n protected azureRegion?: string;\n protected createCachePlugin: (() => Promise<msalCommon.ICachePlugin>) | undefined;\n\n constructor(options: MsalNodeOptions) {\n super(options);\n this.msalConfig = this.defaultNodeMsalConfig(options);\n this.tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);\n this.clientId = this.msalConfig.auth.clientId;\n\n // If persistence has been configured\n if (persistenceProvider !== undefined && options.tokenCachePersistenceOptions?.enabled) {\n this.createCachePlugin = () => persistenceProvider!(options.tokenCachePersistenceOptions);\n } else if (options.tokenCachePersistenceOptions?.enabled) {\n throw new Error(\n [\n \"Persistent token caching was requested, but no persistence provider was configured.\",\n \"You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)\",\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n \"`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`.\"\n ].join(\" \")\n );\n }\n\n this.azureRegion = options.regionalAuthority ?? process.env.AZURE_REGIONAL_AUTHORITY_NAME;\n if (this.azureRegion === RegionalAuthority.AutoDiscoverRegion) {\n this.azureRegion = \"AUTO_DISCOVER\";\n }\n }\n\n /**\n * Generates a MSAL configuration that generally works for Node.js\n */\n protected defaultNodeMsalConfig(options: MsalNodeOptions): msalNode.Configuration {\n const clientId = options.clientId || DeveloperSignOnClientId;\n const tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);\n\n this.authorityHost = options.authorityHost || process.env.AZURE_AUTHORITY_HOST;\n const authority = getAuthority(tenantId, this.authorityHost);\n\n this.identityClient = new IdentityClient({\n ...options.tokenCredentialOptions,\n authorityHost: authority\n });\n\n let clientCapabilities: string[] = [\"CP1\"];\n if (process.env.AZURE_IDENTITY_DISABLE_CP1) {\n clientCapabilities = [];\n }\n\n return {\n auth: {\n clientId,\n authority,\n knownAuthorities: getKnownAuthorities(tenantId, authority),\n clientCapabilities\n },\n // Cache is defined in this.prepare();\n system: {\n networkClient: this.identityClient,\n loggerOptions: {\n loggerCallback: defaultLoggerCallback(options.logger)\n }\n }\n };\n }\n\n /**\n * Prepares the MSAL applications.\n */\n async init(options?: CredentialFlowGetTokenOptions): Promise<void> {\n if (options?.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", () => {\n // This will abort any pending request in the IdentityClient,\n // based on the received or generated correlationId\n this.identityClient!.abortRequests(options.correlationId);\n });\n }\n\n if (this.publicApp || this.confidentialApp) {\n return;\n }\n\n if (this.createCachePlugin !== undefined) {\n this.msalConfig.cache = {\n cachePlugin: await this.createCachePlugin()\n };\n }\n\n this.publicApp = new msalNode.PublicClientApplication(this.msalConfig);\n // The confidential client requires either a secret, assertion or certificate.\n if (\n this.msalConfig.auth.clientSecret ||\n this.msalConfig.auth.clientAssertion ||\n this.msalConfig.auth.clientCertificate\n ) {\n this.confidentialApp = new msalNode.ConfidentialClientApplication(this.msalConfig);\n } else {\n if (this.requiresConfidential) {\n throw new Error(\n \"Unable to generate the MSAL confidential client. Missing either the client's secret, certificate or assertion.\"\n );\n }\n }\n }\n\n /**\n * Allows the cancellation of a MSAL request.\n */\n protected withCancellation(\n promise: Promise<msalCommon.AuthenticationResult | null>,\n abortSignal?: AbortSignalLike,\n onCancel?: () => void\n ): Promise<msalCommon.AuthenticationResult | null> {\n return new Promise((resolve, reject) => {\n promise\n .then((msalToken) => {\n return resolve(msalToken!);\n })\n .catch(reject);\n if (abortSignal) {\n abortSignal.addEventListener(\"abort\", () => {\n onCancel?.();\n });\n }\n });\n }\n\n /**\n * Returns the existing account, attempts to load the account from MSAL.\n */\n async getActiveAccount(): Promise<AuthenticationRecord | undefined> {\n if (this.account) {\n return this.account;\n }\n const cache = this.confidentialApp?.getTokenCache() ?? this.publicApp?.getTokenCache();\n const accountsByTenant = await cache?.getAllAccounts();\n\n if (!accountsByTenant) {\n return;\n }\n\n if (accountsByTenant.length === 1) {\n this.account = msalToPublic(this.clientId, accountsByTenant[0]);\n } else {\n this.logger\n .info(`More than one account was found authenticated for this Client ID and Tenant ID.\nHowever, no \"authenticationRecord\" has been provided for this credential,\ntherefore we're unable to pick between these accounts.\nA new login attempt will be requested, to ensure the correct account is picked.\nTo work with multiple accounts for the same Client ID and Tenant ID, please provide an \"authenticationRecord\" when initializing a credential to prevent this from happening.`);\n return;\n }\n\n return this.account;\n }\n\n /**\n * Attempts to retrieve a token from cache.\n */\n async getTokenSilent(\n scopes: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<AccessToken> {\n await this.getActiveAccount();\n if (!this.account) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Silent authentication failed. We couldn't retrieve an active account from the cache.\"\n });\n }\n\n const silentRequest: msalNode.SilentFlowRequest = {\n // To be able to re-use the account, the Token Cache must also have been provided.\n account: publicToMsal(this.account),\n correlationId: options?.correlationId,\n scopes,\n authority: options?.authority\n };\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 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"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tokenCachePersistenceOptions.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/tokenCachePersistenceOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Parameters that enable token cache persistence in the Identity credentials.\n */\nexport interface TokenCachePersistenceOptions {\n /**\n * If set to true, persistent token caching will be enabled for this credential instance.\n */\n enabled: boolean;\n /**\n * Unique identifier for the persistent token cache.\n *\n * Based on this identifier, the persistence file will be located in any of the following places:\n * - Darwin: '/Users/user/.IdentityService/<name>'\n * - Windows 8+: 'C:\\\\Users\\\\user\\\\AppData\\\\Local\\\\.IdentityService\\\\<name>'\n * - Linux: '/home/user/.IdentityService/<name>'\n */\n name?: string;\n /**\n * If set to true, the cache will be stored without encryption if no OS level user encryption is available.\n * When set to false, the PersistentTokenCache will throw an error if no OS level user encryption is available.\n */\n unsafeAllowUnencryptedStorage?: boolean;\n}\n"]}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
// Copyright (c) Microsoft Corporation.
|
|
2
2
|
// Licensed under the MIT license.
|
|
3
3
|
import * as msalCommon from "@azure/msal-common";
|
|
4
|
+
import { isNode } from "@azure/core-util";
|
|
5
|
+
import { AbortError } from "@azure/abort-controller";
|
|
4
6
|
import { v4 as uuidv4 } from "uuid";
|
|
5
7
|
import { formatError, formatSuccess } from "../util/logging";
|
|
6
|
-
import { CredentialUnavailableError } from "../
|
|
8
|
+
import { CredentialUnavailableError, AuthenticationRequiredError } from "../errors";
|
|
7
9
|
import { DefaultAuthorityHost, DefaultTenantId } from "../constants";
|
|
8
|
-
import { AuthenticationRequiredError } from "./errors";
|
|
9
|
-
import { AbortError } from "@azure/abort-controller";
|
|
10
10
|
/**
|
|
11
11
|
* Latest AuthenticationRecord version
|
|
12
12
|
* @internal
|
|
@@ -19,7 +19,11 @@ const LatestAuthenticationRecordVersion = "1.0";
|
|
|
19
19
|
export function ensureValidMsalToken(scopes, logger, msalToken, getTokenOptions) {
|
|
20
20
|
const error = (message) => {
|
|
21
21
|
logger.getToken.info(message);
|
|
22
|
-
return new AuthenticationRequiredError(
|
|
22
|
+
return new AuthenticationRequiredError({
|
|
23
|
+
scopes: Array.isArray(scopes) ? scopes : [scopes],
|
|
24
|
+
getTokenOptions,
|
|
25
|
+
message
|
|
26
|
+
});
|
|
23
27
|
};
|
|
24
28
|
if (!msalToken) {
|
|
25
29
|
throw error("No response");
|
|
@@ -32,10 +36,13 @@ export function ensureValidMsalToken(scopes, logger, msalToken, getTokenOptions)
|
|
|
32
36
|
}
|
|
33
37
|
}
|
|
34
38
|
/**
|
|
35
|
-
* Generates a valid
|
|
39
|
+
* Generates a valid authority by combining a host with a tenantId.
|
|
36
40
|
* @internal
|
|
37
41
|
*/
|
|
38
|
-
export function
|
|
42
|
+
export function getAuthority(tenantId, host) {
|
|
43
|
+
if (!host) {
|
|
44
|
+
host = DefaultAuthorityHost;
|
|
45
|
+
}
|
|
39
46
|
if (host.endsWith("/")) {
|
|
40
47
|
return host + tenantId;
|
|
41
48
|
}
|
|
@@ -45,8 +52,9 @@ export function getAuthorityHost(tenantId, host = DefaultAuthorityHost) {
|
|
|
45
52
|
}
|
|
46
53
|
/**
|
|
47
54
|
* Generates the known authorities.
|
|
48
|
-
* If the
|
|
49
|
-
*
|
|
55
|
+
* If the Tenant Id is `adfs`, the authority can't be validated since the format won't match the expected one.
|
|
56
|
+
* For that reason, we have to force MSAL to disable validating the authority
|
|
57
|
+
* by sending it within the known authorities in the MSAL configuration.
|
|
50
58
|
* @internal
|
|
51
59
|
*/
|
|
52
60
|
export function getKnownAuthorities(tenantId, authorityHost) {
|
|
@@ -60,22 +68,22 @@ export function getKnownAuthorities(tenantId, authorityHost) {
|
|
|
60
68
|
* @param logger - The logger of the credential.
|
|
61
69
|
* @internal
|
|
62
70
|
*/
|
|
63
|
-
export const defaultLoggerCallback = (logger) => (level, message, containsPii) => {
|
|
71
|
+
export const defaultLoggerCallback = (logger, platform = isNode ? "Node" : "Browser") => (level, message, containsPii) => {
|
|
64
72
|
if (containsPii) {
|
|
65
73
|
return;
|
|
66
74
|
}
|
|
67
75
|
switch (level) {
|
|
68
76
|
case msalCommon.LogLevel.Error:
|
|
69
|
-
logger.info(`MSAL
|
|
77
|
+
logger.info(`MSAL ${platform} V2 error: ${message}`);
|
|
70
78
|
return;
|
|
71
79
|
case msalCommon.LogLevel.Info:
|
|
72
|
-
logger.info(`MSAL
|
|
80
|
+
logger.info(`MSAL ${platform} V2 info message: ${message}`);
|
|
73
81
|
return;
|
|
74
82
|
case msalCommon.LogLevel.Verbose:
|
|
75
|
-
logger.info(`MSAL
|
|
83
|
+
logger.info(`MSAL ${platform} V2 verbose message: ${message}`);
|
|
76
84
|
return;
|
|
77
85
|
case msalCommon.LogLevel.Warning:
|
|
78
|
-
logger.info(`MSAL
|
|
86
|
+
logger.info(`MSAL ${platform} V2 warning: ${message}`);
|
|
79
87
|
return;
|
|
80
88
|
}
|
|
81
89
|
};
|
|
@@ -143,7 +151,7 @@ export class MsalBaseUtilities {
|
|
|
143
151
|
error.name === "AbortError") {
|
|
144
152
|
return error;
|
|
145
153
|
}
|
|
146
|
-
return new AuthenticationRequiredError(scopes, getTokenOptions, error.message);
|
|
154
|
+
return new AuthenticationRequiredError({ scopes, getTokenOptions, message: error.message });
|
|
147
155
|
}
|
|
148
156
|
}
|
|
149
157
|
// transformations.ts
|
|
@@ -153,7 +161,7 @@ export function publicToMsal(account) {
|
|
|
153
161
|
}
|
|
154
162
|
export function msalToPublic(clientId, account) {
|
|
155
163
|
const record = {
|
|
156
|
-
authority:
|
|
164
|
+
authority: getAuthority(account.tenantId, account.environment),
|
|
157
165
|
homeAccountId: account.homeAccountId,
|
|
158
166
|
tenantId: account.tenantId || DefaultTenantId,
|
|
159
167
|
username: account.username,
|
|
@@ -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;AAEjD,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,EAAoB,WAAW,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,EAAE,0BAA0B,EAAE,MAAM,kBAAkB,CAAC;AAC9D,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAErE,OAAO,EAAE,2BAA2B,EAAE,MAAM,UAAU,CAAC;AAEvD,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAErD;;;GAGG;AACH,MAAM,iCAAiC,GAAG,KAAK,CA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AC;IACjF,CAAC;CACF;AAED,qBAAqB;AAErB,MAAM,UAAU,YAAY,CAAC,OAA6B;IACxD,MAAM,CAAC,WAAW,CAAC,GAAG,OAAO,CAAC,SAAS,CAAC,KAAK,CAAC,0BAA0B,CAAC,IAAI,EAAE,CAAC;IAChF,uCACK,OAAO,KACV,cAAc,EAAE,OAAO,CAAC,aAAa,EACrC,WAAW,IACX;AACJ,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,QAAgB,EAAE,OAAwB;IACrE,MAAM,MAAM,GAAG;QACb,SAAS,EAAE,gBAAgB,CAAC,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,WAAW,CAAC;QAClE,aAAa,EAAE,OAAO,CAAC,aAAa;QACpC,QAAQ,EAAE,OAAO,CAAC,QAAQ,IAAI,eAAe;QAC7C,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,QAAQ;QACR,OAAO,EAAE,iCAAiC;KAC3C,CAAC;IACF,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,6BAA6B,CAAC,MAA4B;IACxE,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;AAChC,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,+BAA+B,CAAC,gBAAwB;IACtE,MAAM,MAAM,GAAgD,IAAI,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;IAEzF,IAAI,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,OAAO,KAAK,iCAAiC,EAAE;QAC1E,MAAM,KAAK,CAAC,0CAA0C,CAAC,CAAC;KACzD;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalCommon from \"@azure/msal-common\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-http\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { CredentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { CredentialUnavailableError } from \"../client/errors\";\nimport { DefaultAuthorityHost, DefaultTenantId } from \"../constants\";\nimport { AuthenticationRecord, MsalAccountInfo, MsalResult, MsalToken } from \"./types\";\nimport { AuthenticationRequiredError } from \"./errors\";\nimport { MsalFlowOptions } from \"./flows\";\nimport { AbortError } from \"@azure/abort-controller\";\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 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 authorityHost by combining a host with a tenantId.\n * @internal\n */\nexport function getAuthorityHost(tenantId: string, host: string = DefaultAuthorityHost): string {\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 tenantId is \"adfs\", we will return an array with the authorityHost as the only known authority.\n * Otherwise, it is safe to return an empty array.\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: (logger: CredentialLogger) => msalCommon.ILoggerCallback = (\n logger: CredentialLogger\n) => (level, message, containsPii): void => {\n if (containsPii) {\n return;\n }\n switch (level) {\n case msalCommon.LogLevel.Error:\n logger.info(`MSAL Browser V2 error: ${message}`);\n return;\n case msalCommon.LogLevel.Info:\n logger.info(`MSAL Browser V2 info message: ${message}`);\n return;\n case msalCommon.LogLevel.Verbose:\n logger.info(`MSAL Browser V2 verbose message: ${message}`);\n return;\n case msalCommon.LogLevel.Warning:\n logger.info(`MSAL Browser 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, 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: getAuthorityHost(account.tenantId, account.environment),\n homeAccountId: account.homeAccountId,\n tenantId: account.tenantId || DefaultTenantId,\n username: account.username,\n clientId,\n version: LatestAuthenticationRecordVersion\n };\n return record;\n}\n\n/**\n * Serializes an `AuthenticationRecord` into a string.\n *\n * The output of a serialized authentication record will contain the following properties:\n *\n * - \"authority\"\n * - \"homeAccountId\"\n * - \"clientId\"\n * - \"tenantId\"\n * - \"username\"\n * - \"version\"\n *\n * To later convert this string to a serialized `AuthenticationRecord`, please use the exported function `deserializeAuthenticationRecord()`.\n */\nexport function serializeAuthenticationRecord(record: AuthenticationRecord): string {\n return JSON.stringify(record);\n}\n\n/**\n * Deserializes a previously serialized authentication record from a string into an object.\n *\n * The input string must contain the following properties:\n *\n * - \"authority\"\n * - \"homeAccountId\"\n * - \"clientId\"\n * - \"tenantId\"\n * - \"username\"\n * - \"version\"\n *\n * If the version we receive is unsupported, an error will be thrown.\n *\n * At the moment, the only available version is: \"1.0\", which is always set when the authentication record is serialized.\n *\n * @param serializedRecord - Authentication record previously serialized into string.\n * @returns AuthenticationRecord.\n */\nexport function deserializeAuthenticationRecord(serializedRecord: string): AuthenticationRecord {\n const parsed: AuthenticationRecord & { version?: string } = JSON.parse(serializedRecord);\n\n if (parsed.version && parsed.version !== LatestAuthenticationRecordVersion) {\n throw Error(\"Unsupported AuthenticationRecord version\");\n }\n\n return parsed;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/msal/utils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,UAAU,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAE1C,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAErD,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,EAAoB,WAAW,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,EAAE,0BAA0B,EAAE,2BAA2B,EAAE,MAAM,WAAW,CAAC;AACpF,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAIrE;;;GAGG;AACH,MAAM,iCAAiC,GAAG,KAAK,CAAC;AAEhD;;;GAGG;AACH,MAAM,UAAU,oBAAoB,CAClC,MAAyB,EACzB,MAAwB,EACxB,SAAqB,EACrB,eAAiC;IAEjC,MAAM,KAAK,GAAG,CAAC,OAAe,EAAS,EAAE;QACvC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC9B,OAAO,IAAI,2BAA2B,CAAC;YACrC,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;YACjD,eAAe;YACf,OAAO;SACR,CAAC,CAAC;IACL,CAAC,CAAC;IACF,IAAI,CAAC,SAAS,EAAE;QACd,MAAM,KAAK,CAAC,aAAa,CAAC,CAAC;KAC5B;IACD,IAAI,CAAC,SAAS,CAAC,SAAS,EAAE;QACxB,MAAM,KAAK,CAAC,uCAAuC,CAAC,CAAC;KACtD;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Y,CAAC,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,WAAW,CAAC;QAC9D,aAAa,EAAE,OAAO,CAAC,aAAa;QACpC,QAAQ,EAAE,OAAO,CAAC,QAAQ,IAAI,eAAe;QAC7C,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,QAAQ;QACR,OAAO,EAAE,iCAAiC;KAC3C,CAAC;IACF,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,6BAA6B,CAAC,MAA4B;IACxE,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;AAChC,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,+BAA+B,CAAC,gBAAwB;IACtE,MAAM,MAAM,GAAgD,IAAI,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;IAEzF,IAAI,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,OAAO,KAAK,iCAAiC,EAAE;QAC1E,MAAM,KAAK,CAAC,0CAA0C,CAAC,CAAC;KACzD;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalCommon from \"@azure/msal-common\";\nimport { isNode } from \"@azure/core-util\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AbortError } from \"@azure/abort-controller\";\n\nimport { v4 as uuidv4 } from \"uuid\";\nimport { CredentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { CredentialUnavailableError, AuthenticationRequiredError } from \"../errors\";\nimport { DefaultAuthorityHost, DefaultTenantId } from \"../constants\";\nimport { AuthenticationRecord, MsalAccountInfo, MsalResult, MsalToken } from \"./types\";\nimport { MsalFlowOptions } from \"./flows\";\n\n/**\n * Latest AuthenticationRecord version\n * @internal\n */\nconst LatestAuthenticationRecordVersion = \"1.0\";\n\n/**\n * Ensures the validity of the MSAL token\n * @internal\n */\nexport function ensureValidMsalToken(\n scopes: string | string[],\n logger: CredentialLogger,\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions\n): void {\n const error = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message\n });\n };\n if (!msalToken) {\n throw error(\"No response\");\n }\n if (!msalToken.expiresOn) {\n throw error(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw error(`Response had no \"accessToken\" property.`);\n }\n}\n\n/**\n * Generates a valid authority by combining a host with a tenantId.\n * @internal\n */\nexport function getAuthority(tenantId: string, host?: string): string {\n if (!host) {\n host = DefaultAuthorityHost;\n }\n if (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,\n 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"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Copyright (c) Microsoft Corporation.
|
|
2
|
+
// Licensed under the MIT license.
|
|
3
|
+
// This module is a shim for the plugin consumer in the browser
|
|
4
|
+
export function useIdentityPlugin(_plugin) {
|
|
5
|
+
throw new Error("Identity plugins are not supported in browser environments.");
|
|
6
|
+
}
|
|
7
|
+
//# sourceMappingURL=consumer.browser.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"consumer.browser.js","sourceRoot":"","sources":["../../../src/plugins/consumer.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,+DAA+D;AAE/D,MAAM,UAAU,iBAAiB,CAAC,OAAgB;IAChD,MAAM,IAAI,KAAK,CAAC,6DAA6D,CAAC,CAAC;AACjF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n// This module is a shim for the plugin consumer in the browser\n\nexport function useIdentityPlugin(_plugin: unknown): void {\n throw new Error(\"Identity plugins are not supported in browser environments.\");\n}\n"]}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Copyright (c) Microsoft Corporation.
|
|
2
|
+
// Licensed under the MIT license.
|
|
3
|
+
import { msalNodeFlowCacheControl } from "../msal/nodeFlows/nodeCommon";
|
|
4
|
+
import { vsCodeCredentialControl } from "../credentials/visualStudioCodeCredential";
|
|
5
|
+
/**
|
|
6
|
+
* The context passed to an Identity plugin. This contains objects that
|
|
7
|
+
* plugins can use to set backend implementations.
|
|
8
|
+
* @internal
|
|
9
|
+
*/
|
|
10
|
+
const pluginContext = {
|
|
11
|
+
cachePluginControl: msalNodeFlowCacheControl,
|
|
12
|
+
vsCodeCredentialControl: vsCodeCredentialControl
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Extend Azure Identity with additional functionality. Pass a plugin from
|
|
16
|
+
* a plugin package, such as:
|
|
17
|
+
*
|
|
18
|
+
* - `@azure/identity-cache-persistence`: provides persistent token caching
|
|
19
|
+
* - `@azure/identity-vscode`: provides the dependencies of
|
|
20
|
+
* `VisualStudioCodeCredential` and enables it
|
|
21
|
+
*
|
|
22
|
+
* Example:
|
|
23
|
+
*
|
|
24
|
+
* ```javascript
|
|
25
|
+
* import { cachePersistencePlugin } from "@azure/identity-cache-persistence";
|
|
26
|
+
*
|
|
27
|
+
* import { useIdentityPlugin, DefaultAzureCredential } from "@azure/identity";
|
|
28
|
+
* useIdentityPlugin(cachePersistencePlugin);
|
|
29
|
+
*
|
|
30
|
+
* // The plugin has the capability to extend `DefaultAzureCredential` and to
|
|
31
|
+
* // add middleware to the underlying credentials, such as persistence.
|
|
32
|
+
* const credential = new DefaultAzureCredential({
|
|
33
|
+
* tokenCachePersistenceOptions: {
|
|
34
|
+
* enabled: true
|
|
35
|
+
* }
|
|
36
|
+
* });
|
|
37
|
+
* ```
|
|
38
|
+
*
|
|
39
|
+
* @param plugin - the plugin to register
|
|
40
|
+
*/
|
|
41
|
+
export function useIdentityPlugin(plugin) {
|
|
42
|
+
plugin(pluginContext);
|
|
43
|
+
}
|
|
44
|
+
//# sourceMappingURL=consumer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"consumer.js","sourceRoot":"","sources":["../../../src/plugins/consumer.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,uBAAuB,EAAE,MAAM,2CAA2C,CAAC;AAEpF;;;;GAIG;AACH,MAAM,aAAa,GAAuB;IACxC,kBAAkB,EAAE,wBAAwB;IAC5C,uBAAuB,EAAE,uBAAuB;CACjD,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,UAAU,iBAAiB,CAAC,MAAsB;IACtD,MAAM,CAAC,aAAa,CAAC,CAAC;AACxB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AzurePluginContext, IdentityPlugin } from \"./provider\";\nimport { msalNodeFlowCacheControl } from \"../msal/nodeFlows/nodeCommon\";\nimport { vsCodeCredentialControl } from \"../credentials/visualStudioCodeCredential\";\n\n/**\n * The context passed to an Identity plugin. This contains objects that\n * plugins can use to set backend implementations.\n * @internal\n */\nconst pluginContext: AzurePluginContext = {\n cachePluginControl: msalNodeFlowCacheControl,\n vsCodeCredentialControl: vsCodeCredentialControl\n};\n\n/**\n * Extend Azure Identity with additional functionality. Pass a plugin from\n * a plugin package, such as:\n *\n * - `@azure/identity-cache-persistence`: provides persistent token caching\n * - `@azure/identity-vscode`: provides the dependencies of\n * `VisualStudioCodeCredential` and enables it\n *\n * Example:\n *\n * ```javascript\n * import { cachePersistencePlugin } from \"@azure/identity-cache-persistence\";\n *\n * import { useIdentityPlugin, DefaultAzureCredential } from \"@azure/identity\";\n * useIdentityPlugin(cachePersistencePlugin);\n *\n * // The plugin has the capability to extend `DefaultAzureCredential` and to\n * // add middleware to the underlying credentials, such as persistence.\n * const credential = new DefaultAzureCredential({\n * tokenCachePersistenceOptions: {\n * enabled: true\n * }\n * });\n * ```\n *\n * @param plugin - the plugin to register\n */\nexport function useIdentityPlugin(plugin: IdentityPlugin): void {\n plugin(pluginContext);\n}\n"]}
|