-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
MsalPublicClient.cs
433 lines (386 loc) · 17.8 KB
/
MsalPublicClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Microsoft.Identity.Client;
namespace Azure.Identity
{
internal class MsalPublicClient : MsalClientBase<IPublicClientApplication>
{
private Action<PublicClientApplicationBuilder> _beforeBuildClient;
internal string RedirectUrl { get; }
protected MsalPublicClient()
{ }
public MsalPublicClient(CredentialPipeline pipeline, string tenantId, string clientId, string redirectUrl, TokenCredentialOptions options)
: base(pipeline, tenantId, clientId, options)
{
RedirectUrl = redirectUrl;
if (options is IMsalPublicClientInitializerOptions initializerOptions)
{
_beforeBuildClient = initializerOptions.BeforeBuildClient;
};
}
protected override ValueTask<IPublicClientApplication> CreateClientAsync(bool enableCae, bool async, CancellationToken cancellationToken)
{
return CreateClientCoreAsync(enableCae, async, cancellationToken);
}
protected virtual ValueTask<IPublicClientApplication> CreateClientCoreAsync(bool enableCae, bool async, CancellationToken cancellationToken)
{
string[] clientCapabilities =
enableCae ? cp1Capabilities : Array.Empty<string>();
var authorityUri = new UriBuilder(AuthorityHost.Scheme, AuthorityHost.Host, AuthorityHost.Port, TenantId ?? Constants.OrganizationsTenantId).Uri;
PublicClientApplicationBuilder pubAppBuilder = PublicClientApplicationBuilder
.Create(ClientId)
.WithAuthority(authorityUri)
.WithHttpClientFactory(new HttpPipelineClientFactory(Pipeline.HttpPipeline))
.WithLogging(LogMsal, enablePiiLogging: IsSupportLoggingEnabled);
if (!string.IsNullOrEmpty(RedirectUrl))
{
pubAppBuilder = pubAppBuilder.WithRedirectUri(RedirectUrl);
}
if (clientCapabilities.Length > 0)
{
pubAppBuilder.WithClientCapabilities(clientCapabilities);
}
if (_beforeBuildClient != null)
{
_beforeBuildClient(pubAppBuilder);
}
if (DisableInstanceDiscovery)
{
pubAppBuilder.WithInstanceDiscovery(false);
}
return new ValueTask<IPublicClientApplication>(pubAppBuilder.Build());
}
public async ValueTask<List<IAccount>> GetAccountsAsync(bool async, bool enableCae, CancellationToken cancellationToken)
{
return await GetAccountsCoreAsync(async, enableCae, cancellationToken).ConfigureAwait(false);
}
protected virtual async ValueTask<List<IAccount>> GetAccountsCoreAsync(bool async, bool enableCae, CancellationToken cancellationToken)
{
IPublicClientApplication client = await GetClientAsync(enableCae, async, cancellationToken).ConfigureAwait(false);
return await GetAccountsAsync(client, async).ConfigureAwait(false);
}
public async ValueTask<AuthenticationResult> AcquireTokenSilentAsync(
string[] scopes,
string claims,
IAccount account,
string tenantId,
bool enableCae,
#if PREVIEW_FEATURE_FLAG
PopTokenRequestContext? popTokenRequestContext,
#endif
bool async,
CancellationToken cancellationToken)
{
var result = await AcquireTokenSilentCoreAsync(
scopes,
claims,
account,
tenantId,
enableCae,
#if PREVIEW_FEATURE_FLAG
popTokenRequestContext,
#endif
async,
cancellationToken).ConfigureAwait(false);
LogAccountDetails(result);
return result;
}
protected virtual async ValueTask<AuthenticationResult> AcquireTokenSilentCoreAsync(
string[] scopes,
string claims,
IAccount account,
string tenantId,
bool enableCae,
#if PREVIEW_FEATURE_FLAG
PopTokenRequestContext? popTokenRequestContext,
#endif
bool async,
CancellationToken cancellationToken)
{
IPublicClientApplication client = await GetClientAsync(enableCae, async, cancellationToken).ConfigureAwait(false);
var builder = client.AcquireTokenSilent(scopes, account);
if (!string.IsNullOrEmpty(claims))
{
builder.WithClaims(claims);
}
if (tenantId != null)
{
UriBuilder uriBuilder = new UriBuilder(AuthorityHost)
{
Path = TenantId ?? tenantId
};
builder.WithTenantIdFromAuthority(uriBuilder.Uri);
}
#if PREVIEW_FEATURE_FLAG
if (popTokenRequestContext.HasValue && popTokenRequestContext.Value.IsProofOfPossessionEnabled)
{
builder.WithProofOfPossession(popTokenRequestContext.Value.ProofOfPossessionNonce, popTokenRequestContext.Value.HttpMethod, popTokenRequestContext.Value.Uri);
}
#endif
return await builder
.ExecuteAsync(async, cancellationToken)
.ConfigureAwait(false);
}
public async ValueTask<AuthenticationResult> AcquireTokenSilentAsync(
string[] scopes,
string claims,
AuthenticationRecord record,
string tenantId,
bool enableCae,
#if PREVIEW_FEATURE_FLAG
PopTokenRequestContext? popTokenRequestContext,
#endif
bool async,
CancellationToken cancellationToken)
{
var result = await AcquireTokenSilentCoreAsync(
scopes,
claims,
record,
tenantId,
enableCae,
#if PREVIEW_FEATURE_FLAG
popTokenRequestContext,
#endif
async,
cancellationToken).ConfigureAwait(false);
LogAccountDetails(result);
return result;
}
protected virtual async ValueTask<AuthenticationResult> AcquireTokenSilentCoreAsync(
string[] scopes,
string claims,
AuthenticationRecord record,
string tenantId,
bool enableCae,
#if PREVIEW_FEATURE_FLAG
PopTokenRequestContext? popTokenRequestContext,
#endif
bool async,
CancellationToken cancellationToken)
{
IPublicClientApplication client = await GetClientAsync(enableCae, async, cancellationToken).ConfigureAwait(false);
// if the user specified a TenantId when they created the client we want to authenticate to that tenant.
// otherwise we should authenticate with the tenant specified by the authentication record since that's the tenant the
// user authenticated to originally.
var builder = client.AcquireTokenSilent(scopes, (AuthenticationAccount)record);
if (tenantId != null || record.TenantId != null)
{
UriBuilder uriBuilder = new UriBuilder(AuthorityHost)
{
Path = tenantId ?? record.TenantId
};
builder.WithTenantIdFromAuthority(uriBuilder.Uri);
}
if (!string.IsNullOrEmpty(claims))
{
builder.WithClaims(claims);
}
#if PREVIEW_FEATURE_FLAG
if (popTokenRequestContext.HasValue && popTokenRequestContext.Value.IsProofOfPossessionEnabled)
{
builder.WithProofOfPossession(popTokenRequestContext.Value.ProofOfPossessionNonce, popTokenRequestContext.Value.HttpMethod, popTokenRequestContext.Value.Uri);
}
#endif
return await builder.ExecuteAsync(async, cancellationToken)
.ConfigureAwait(false);
}
public async ValueTask<AuthenticationResult> AcquireTokenInteractiveAsync(
string[] scopes,
string claims,
Prompt prompt,
string loginHint,
string tenantId,
bool enableCae,
BrowserCustomizationOptions browserOptions,
#if PREVIEW_FEATURE_FLAG
PopTokenRequestContext? popTokenRequestContext,
#endif
bool async,
CancellationToken cancellationToken)
{
if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA && !IdentityCompatSwitches.DisableInteractiveBrowserThreadpoolExecution)
{
// In the case we are called in an STA apartment thread, we need to use Task.Run to execute on the call to MSAL on the threadpool.
// On certain platforms MSAL will use the embedded browser instead of launching the browser as a separate
// process. Executing with Task.Run prevents possibly deadlocking the UI thread in these cases.
// This workaround can be disabled by using the "Azure.Identity.DisableInteractiveBrowserThreadpoolExecution" app switch
// or setting the AZURE_IDENTITY_DISABLE_INTERACTIVEBROWSERTHREADPOOLEXECUTION environment variable to true
AzureIdentityEventSource.Singleton.InteractiveAuthenticationExecutingOnThreadPool();
#pragma warning disable AZC0102 // Do not use GetAwaiter().GetResult().
return Task.Run(async () =>
{
var result = await AcquireTokenInteractiveCoreAsync(
scopes,
claims,
prompt,
loginHint,
tenantId,
enableCae,
browserOptions,
#if PREVIEW_FEATURE_FLAG
popTokenRequestContext,
#endif
true,
cancellationToken).ConfigureAwait(false);
LogAccountDetails(result);
return result;
}).GetAwaiter().GetResult();
#pragma warning restore AZC0102 // Do not use GetAwaiter().GetResult().
}
AzureIdentityEventSource.Singleton.InteractiveAuthenticationExecutingInline();
var result = await AcquireTokenInteractiveCoreAsync(
scopes,
claims,
prompt,
loginHint,
tenantId,
enableCae,
browserOptions,
#if PREVIEW_FEATURE_FLAG
popTokenRequestContext,
#endif
async,
cancellationToken).ConfigureAwait(false);
LogAccountDetails(result);
return result;
}
protected virtual async ValueTask<AuthenticationResult> AcquireTokenInteractiveCoreAsync(
string[] scopes,
string claims,
Prompt prompt,
string loginHint,
string tenantId,
bool enableCae,
BrowserCustomizationOptions browserOptions,
#if PREVIEW_FEATURE_FLAG
PopTokenRequestContext? popTokenRequestContext,
#endif
bool async,
CancellationToken cancellationToken)
{
IPublicClientApplication client = await GetClientAsync(enableCae, async, cancellationToken).ConfigureAwait(false);
var builder = client.AcquireTokenInteractive(scopes)
.WithPrompt(prompt);
if (!string.IsNullOrEmpty(claims))
{
builder.WithClaims(claims);
}
if (loginHint != null)
{
builder.WithLoginHint(loginHint);
}
if (tenantId != null)
{
UriBuilder uriBuilder = new UriBuilder(AuthorityHost)
{
Path = tenantId
};
builder.WithTenantIdFromAuthority(uriBuilder.Uri);
}
if (browserOptions != null)
{
if (browserOptions.UseEmbeddedWebView.HasValue)
{
builder.WithUseEmbeddedWebView(browserOptions.UseEmbeddedWebView.Value);
}
if (browserOptions.SystemBrowserOptions != null)
{
builder.WithSystemWebViewOptions(browserOptions.SystemBrowserOptions);
}
}
#if PREVIEW_FEATURE_FLAG
if (popTokenRequestContext.HasValue && popTokenRequestContext.Value.IsProofOfPossessionEnabled)
{
builder.WithProofOfPossession(popTokenRequestContext.Value.ProofOfPossessionNonce, popTokenRequestContext.Value.HttpMethod, popTokenRequestContext.Value.Uri);
}
#endif
return await builder
.ExecuteAsync(async, cancellationToken)
.ConfigureAwait(false);
}
public async ValueTask<AuthenticationResult> AcquireTokenByUsernamePasswordAsync(string[] scopes, string claims, string username, string password, string tenantId, bool enableCae, bool async, CancellationToken cancellationToken)
{
var result = await AcquireTokenByUsernamePasswordCoreAsync(scopes, claims, username, password, tenantId, enableCae, async, cancellationToken).ConfigureAwait(false);
LogAccountDetails(result);
return result;
}
protected virtual async ValueTask<AuthenticationResult> AcquireTokenByUsernamePasswordCoreAsync(string[] scopes, string claims, string username, string password, string tenantId, bool enableCae, bool async, CancellationToken cancellationToken)
{
IPublicClientApplication client = await GetClientAsync(enableCae, async, cancellationToken).ConfigureAwait(false);
var builder = client
.AcquireTokenByUsernamePassword(scopes, username, password);
if (!string.IsNullOrEmpty(claims))
{
builder.WithClaims(claims);
}
if (!string.IsNullOrEmpty(tenantId))
{
UriBuilder uriBuilder = new UriBuilder(AuthorityHost)
{
Path = tenantId
};
builder.WithTenantIdFromAuthority(uriBuilder.Uri);
}
return await builder.ExecuteAsync(async, cancellationToken)
.ConfigureAwait(false);
}
public async ValueTask<AuthenticationResult> AcquireTokenWithDeviceCodeAsync(string[] scopes, string claims, Func<DeviceCodeResult, Task> deviceCodeCallback, bool enableCae, bool async, CancellationToken cancellationToken)
{
var result = await AcquireTokenWithDeviceCodeCoreAsync(scopes, claims, deviceCodeCallback, enableCae, async, cancellationToken).ConfigureAwait(false);
LogAccountDetails(result);
return result;
}
protected virtual async ValueTask<AuthenticationResult> AcquireTokenWithDeviceCodeCoreAsync(string[] scopes, string claims, Func<DeviceCodeResult, Task> deviceCodeCallback, bool enableCae, bool async, CancellationToken cancellationToken)
{
IPublicClientApplication client = await GetClientAsync(enableCae, async, cancellationToken).ConfigureAwait(false);
var builder = client.AcquireTokenWithDeviceCode(scopes, deviceCodeCallback);
if (!string.IsNullOrEmpty(claims))
{
builder.WithClaims(claims);
}
return await builder.ExecuteAsync(async, cancellationToken)
.ConfigureAwait(false);
}
public async ValueTask<AuthenticationResult> AcquireTokenByRefreshTokenAsync(string[] scopes, string claims, string refreshToken, AzureCloudInstance azureCloudInstance, string tenant, bool enableCae, bool async, CancellationToken cancellationToken)
{
var result = await AcquireTokenByRefreshTokenCoreAsync(scopes, claims, refreshToken, azureCloudInstance, tenant, enableCae, async, cancellationToken).ConfigureAwait(false);
LogAccountDetails(result);
return result;
}
protected virtual async ValueTask<AuthenticationResult> AcquireTokenByRefreshTokenCoreAsync(string[] scopes, string claims, string refreshToken, AzureCloudInstance azureCloudInstance, string tenant, bool enableCae, bool async, CancellationToken cancellationToken)
{
IPublicClientApplication client = await GetClientAsync(enableCae, async, cancellationToken).ConfigureAwait(false);
var builder = ((IByRefreshToken)client).AcquireTokenByRefreshToken(scopes, refreshToken);
if (!string.IsNullOrEmpty(claims))
{
builder.WithClaims(claims);
}
if (!string.IsNullOrEmpty(TenantId))
{
UriBuilder uriBuilder = new UriBuilder(AuthorityHost)
{
Path = tenant
};
builder.WithTenantIdFromAuthority(uriBuilder.Uri);
}
return await builder.ExecuteAsync(async, cancellationToken)
.ConfigureAwait(false);
}
private static async ValueTask<List<IAccount>> GetAccountsAsync(IPublicClientApplication client, bool async)
{
var result = async
? await client.GetAccountsAsync().ConfigureAwait(false)
#pragma warning disable AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead.
: client.GetAccountsAsync().GetAwaiter().GetResult();
#pragma warning restore AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead.
return result.ToList();
}
}
}