-
Notifications
You must be signed in to change notification settings - Fork 403
Expand file tree
/
Copy pathOnBehalfOfTests.cs
More file actions
539 lines (448 loc) · 27.1 KB
/
OnBehalfOfTests.cs
File metadata and controls
539 lines (448 loc) · 27.1 KB
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Internal;
using Microsoft.Identity.Test.Common;
using Microsoft.Identity.Test.Common.Core.Helpers;
using Microsoft.Identity.Test.Common.Core.Mocks;
using Microsoft.Identity.Test.Integration.Infrastructure;
using Microsoft.Identity.Test.Integration.NetFx.Infrastructure;
using Microsoft.Identity.Test.LabInfrastructure;
using Microsoft.Identity.Test.Unit;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Identity.Test.Integration.HeadlessTests
{
[TestClass]
public class OnBehalfOfTests
{
private static readonly string[] s_scopes = { "User.Read" };
private static InMemoryTokenCache s_inMemoryTokenCache = new InMemoryTokenCache();
private X509Certificate2 _labAuthCert;
private readonly KeyVaultSecretsProvider _keyVaultMsidLab = new KeyVaultSecretsProvider(KeyVaultInstance.MSIDLab);
#region Test Hooks
[TestInitialize]
public async Task TestInitializeAsync()
{
ApplicationBase.ResetStateForTest();
if (_labAuthCert is null)
{
_labAuthCert = await _keyVaultMsidLab.GetCertificateWithPrivateMaterialAsync("LabAuth").ConfigureAwait(false);
}
}
#endregion
/// <summary>
/// Tests the behavior when calling OBO and silent in different orders with multiple users.
/// OBO calls should return tokens for correct users, silent calls should throw.
/// </summary>
[TestMethod]
[DataRow(false, false)]
[DataRow(true, false)]
[DataRow(true, true)]
public async Task OboAndSilent_ReturnsCorrectTokens_TestAsync(bool serializeCache, bool usePartitionedSerializationCache)
{
// Setup: Get lab users, create PCA and get user tokens
var user1 = await LabResponseHelper.GetUserConfigAsync(KeyVaultSecrets.UserPublicCloud).ConfigureAwait(false);
var user2 = await LabResponseHelper.GetUserConfigAsync(KeyVaultSecrets.UserPublicCloud2).ConfigureAwait(false);
var app = await LabResponseHelper.GetAppConfigAsync(KeyVaultSecrets.AppS2S).ConfigureAwait(false);
var appApi = await LabResponseHelper.GetAppConfigAsync(KeyVaultSecrets.AppOBOService).ConfigureAwait(false);
var partitionedInMemoryTokenCache = new InMemoryPartitionedTokenCache();
var nonPartitionedInMemoryTokenCache = new InMemoryTokenCache();
var oboTokens = new HashSet<string>();
var pca = PublicClientApplicationBuilder
.Create(app.AppId)
.WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
.Build();
#pragma warning disable CS0618 // Type or member is obsolete
var user1AuthResult = await pca
.AcquireTokenByUsernamePassword([appApi.DefaultScopes], user1.Upn, user1.GetOrFetchPassword())
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);
#pragma warning restore CS0618
#pragma warning disable CS0618 // Type or member is obsolete
var user2AuthResult = await pca
.AcquireTokenByUsernamePassword([appApi.DefaultScopes], user2.Upn, user2.GetOrFetchPassword())
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);
#pragma warning restore CS0618
Assert.AreEqual(user1AuthResult.TenantId, user2AuthResult.TenantId);
var cca = CreateCCA();
// Asserts
// Silent calls should throw
await AssertException.TaskThrowsAsync<MsalUiRequiredException>(() =>
cca.AcquireTokenSilent(s_scopes, user1AuthResult.Account)
.ExecuteAsync(CancellationToken.None)
).ConfigureAwait(false);
await AssertException.TaskThrowsAsync<MsalUiRequiredException>(() =>
cca.AcquireTokenSilent(s_scopes, user2AuthResult.Account)
.ExecuteAsync(CancellationToken.None)
).ConfigureAwait(false);
// User1 - no AT, RT in cache - retrieves from IdP
var authResult = await cca.AcquireTokenOnBehalfOf(s_scopes, new UserAssertion(user1AuthResult.AccessToken))
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);
Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
Assert.AreEqual(CacheRefreshReason.NoCachedAccessToken, authResult.AuthenticationResultMetadata.CacheRefreshReason);
oboTokens.Add(authResult.AccessToken);
// User1 - finds AT in cache
authResult = await cca.AcquireTokenOnBehalfOf(s_scopes, new UserAssertion(user1AuthResult.AccessToken))
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);
Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource);
Assert.AreEqual(CacheRefreshReason.NotApplicable, authResult.AuthenticationResultMetadata.CacheRefreshReason);
oboTokens.Add(authResult.AccessToken);
// User2 - no AT, RT - retrieves from IdP
authResult = await cca.AcquireTokenOnBehalfOf(s_scopes, new UserAssertion(user2AuthResult.AccessToken))
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);
Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
Assert.AreEqual(CacheRefreshReason.NoCachedAccessToken, authResult.AuthenticationResultMetadata.CacheRefreshReason);
oboTokens.Add(authResult.AccessToken);
// User2 - finds AT in cache
authResult = await cca.AcquireTokenOnBehalfOf(s_scopes, new UserAssertion(user2AuthResult.AccessToken))
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);
Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource);
Assert.AreEqual(CacheRefreshReason.NotApplicable, authResult.AuthenticationResultMetadata.CacheRefreshReason);
oboTokens.Add(authResult.AccessToken);
Assert.HasCount(2, oboTokens);
// Silent calls should throw
await AssertException.TaskThrowsAsync<MsalUiRequiredException>(() =>
cca.AcquireTokenSilent(s_scopes, user1AuthResult.Account)
.ExecuteAsync(CancellationToken.None)
).ConfigureAwait(false);
await AssertException.TaskThrowsAsync<MsalUiRequiredException>(() =>
cca.AcquireTokenSilent(s_scopes, user2AuthResult.Account)
.ExecuteAsync(CancellationToken.None)
).ConfigureAwait(false);
IConfidentialClientApplication CreateCCA()
{
var app = ConfidentialClientApplicationBuilder
.Create(appApi.AppId)
.WithAuthority(new Uri($"https://login.microsoftonline.com/{user1AuthResult.TenantId}"), true)
.WithCertificate(_labAuthCert)
.WithLegacyCacheCompatibility(false)
.Build();
if (serializeCache)
{
if (usePartitionedSerializationCache)
{
partitionedInMemoryTokenCache.Bind(app.UserTokenCache);
}
else
{
nonPartitionedInMemoryTokenCache.Bind(app.UserTokenCache);
}
}
return app;
}
}
/// <summary>
/// Reuse the same CCA with regional for OBO and for client calls in different orders.
/// Client calls should go to regional, OBO calls should go to global
/// </summary>
[TestMethod]
public async Task OboAndClientCredentials_WithRegional_ReturnsCorrectTokens_TestAsync()
{
// Setup: Get lab user, create PCA and get user tokens
var user = await LabResponseHelper.GetUserConfigAsync(KeyVaultSecrets.UserPublicCloud).ConfigureAwait(false);
var app = await LabResponseHelper.GetAppConfigAsync(KeyVaultSecrets.AppS2S).ConfigureAwait(false);
var appApi = await LabResponseHelper.GetAppConfigAsync(KeyVaultSecrets.AppOBOService).ConfigureAwait(false);
// Use the correct public client ID from KeyVault for all tests
var publicClientId = app.AppId;
var pca = PublicClientApplicationBuilder
.Create(publicClientId)
.WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
.Build();
#pragma warning disable CS0618 // Type or member is obsolete
var userResult = await pca
.AcquireTokenByUsernamePassword([appApi.DefaultScopes], user.Upn, user.GetOrFetchPassword())
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);
#pragma warning restore CS0618
// Act and Assert different scenarios
var cca = await BuildCcaAsync(userResult.TenantId, true).ConfigureAwait(false);
// OBO uses global - IdP
var oboResult = await cca.AcquireTokenOnBehalfOf(s_scopes, new UserAssertion(userResult.AccessToken))
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);
Assert.AreEqual(TokenSource.IdentityProvider, oboResult.AuthenticationResultMetadata.TokenSource);
Assert.DoesNotContain(TestConstants.Region, oboResult.AuthenticationResultMetadata.TokenEndpoint);
// Client uses regional - IdP
var clientResult = await cca.AcquireTokenForClient(new string[] { "https://graph.microsoft.com/.default" })
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);
Assert.AreEqual(TokenSource.IdentityProvider, clientResult.AuthenticationResultMetadata.TokenSource);
Assert.Contains(TestConstants.Region, clientResult.AuthenticationResultMetadata.TokenEndpoint);
// OBO from cache
oboResult = await cca.AcquireTokenOnBehalfOf(s_scopes, new UserAssertion(userResult.AccessToken))
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);
Assert.AreEqual(TokenSource.Cache, oboResult.AuthenticationResultMetadata.TokenSource);
// Client from cache
clientResult = await cca.AcquireTokenForClient(new string[] { "https://graph.microsoft.com/.default" })
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);
Assert.AreEqual(TokenSource.Cache, clientResult.AuthenticationResultMetadata.TokenSource);
}
[TestMethod]
public async Task WithMultipleUsers_TestAsync()
{
var aadUser1 = await LabResponseHelper.GetUserConfigAsync(KeyVaultSecrets.UserPublicCloud).ConfigureAwait(false);
var aadUser2 = await LabResponseHelper.GetUserConfigAsync(KeyVaultSecrets.UserPublicCloud2).ConfigureAwait(false);
var aadUser3 = await LabResponseHelper.GetUserConfigAsync(KeyVaultSecrets.UserXcg).ConfigureAwait(false);
await RunOnBehalfOfTestAsync(aadUser3, false).ConfigureAwait(false);
await RunOnBehalfOfTestAsync(aadUser1, false).ConfigureAwait(false);
await RunOnBehalfOfTestAsync(aadUser1, true).ConfigureAwait(false);
await RunOnBehalfOfTestAsync(aadUser2, false).ConfigureAwait(false);
await RunOnBehalfOfTestAsync(aadUser3, true).ConfigureAwait(false);
await RunOnBehalfOfTestAsync(aadUser2, true).ConfigureAwait(false);
await RunOnBehalfOfTestAsync(aadUser2, false, true).ConfigureAwait(false);
}
[TestMethod]
[TestCategory(TestCategories.Arlington)]
public async Task ArlingtonWebAPIAccessingGraphOnBehalfOfUserTestAsync()
{
var arligntonUser = await LabResponseHelper.GetUserConfigAsync(KeyVaultSecrets.UserArlington).ConfigureAwait(false);
arligntonUser.AzureEnvironment = LabConstants.AzureEnvironmentUsGovernment;
var msalPublicClient = PublicClientApplicationBuilder.Create("cb7faed4-b8c0-49ee-b421-f5ed16894c83")
.WithAuthority("https://login.microsoftonline.us/organizations")
.WithRedirectUri(TestConstants.RedirectUri)
.WithTestLogging()
.Build();
#pragma warning disable CS0618 // Type or member is obsolete
var authResult = await msalPublicClient.AcquireTokenByUsernamePassword(
new[] { "https://arlmsidlab1.us/IDLABS_APP_Confidential_Client/user_impersonation" }, arligntonUser.Upn, arligntonUser.GetOrFetchPassword())
.ExecuteAsync()
.ConfigureAwait(false);
#pragma warning restore CS0618
var ccaAuthority = new Uri("https://login.microsoftonline.us/" + authResult.TenantId);
var confidentialApp = ConfidentialClientApplicationBuilder
.Create("c0555d2d-02f2-4838-802e-3463422e571d")
.WithAuthority(ccaAuthority, true)
.WithAzureRegion(TestConstants.Region) // should be ignored by OBO
.WithClientSecret(_keyVaultMsidLab.GetSecretByName(TestConstants.MsalArlingtonOBOKeyVaultSecretName).Value)
.WithTestLogging()
.Build();
var userCacheRecorder = confidentialApp.UserTokenCache.RecordAccess();
UserAssertion userAssertion = new UserAssertion(authResult.AccessToken);
string atHash = userAssertion.AssertionHash;
authResult = await confidentialApp.AcquireTokenOnBehalfOf(s_scopes, userAssertion)
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);
MsalAssert.AssertAuthResult(authResult, arligntonUser);
Assert.AreEqual(atHash, userCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
Assert.AreEqual(
ccaAuthority.ToString() + "/oauth2/v2.0/token",
authResult.AuthenticationResultMetadata.TokenEndpoint,
"OBO does not obey region");
#pragma warning disable CS0618 // Type or member is obsolete
await confidentialApp.GetAccountsAsync().ConfigureAwait(false);
#pragma warning restore CS0618 // Type or member is obsolete
Assert.IsNull(userCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
}
[TestMethod]
public async Task WithCache_TestAsync()
{
var user = await LabResponseHelper.GetUserConfigAsync(KeyVaultSecrets.UserPublicCloud).ConfigureAwait(false);
var app = await LabResponseHelper.GetAppConfigAsync(KeyVaultSecrets.AppS2S).ConfigureAwait(false);
var appApi = await LabResponseHelper.GetAppConfigAsync(KeyVaultSecrets.AppOBOService).ConfigureAwait(false);
var factory = new HttpSnifferClientFactory();
var msalPublicClient = PublicClientApplicationBuilder.Create(app.AppId)
.WithAuthority(TestConstants.AuthorityOrganizationsTenant)
.WithRedirectUri(TestConstants.RedirectUri)
.WithTestLogging()
.WithHttpClientFactory(factory)
.Build();
#pragma warning disable CS0618 // Type or member is obsolete
var authResult = await msalPublicClient.AcquireTokenByUsernamePassword([appApi.DefaultScopes], user.Upn, user.GetOrFetchPassword())
.ExecuteAsync()
.ConfigureAwait(false);
#pragma warning restore CS0618
var confidentialApp = ConfidentialClientApplicationBuilder
.Create(appApi.AppId)
.WithAuthority(new Uri("https://login.microsoftonline.com/" + authResult.TenantId), true)
.WithCertificate(_labAuthCert)
.WithTestLogging()
.BuildConcrete();
var userCacheRecorder = confidentialApp.UserTokenCache.RecordAccess();
UserAssertion userAssertion = new UserAssertion(authResult.AccessToken);
string atHash = userAssertion.AssertionHash;
authResult = await confidentialApp.AcquireTokenOnBehalfOf(s_scopes, userAssertion)
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);
MsalAssert.AssertAuthResult(authResult, user);
Assert.AreEqual(atHash, userCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
//Run OBO again. Should get token from cache
authResult = await confidentialApp.AcquireTokenOnBehalfOf(s_scopes, userAssertion)
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);
Assert.IsNotNull(authResult);
Assert.IsNotNull(authResult.AccessToken);
Assert.IsNotNull(authResult.IdToken);
Assert.IsFalse(userCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
Assert.IsTrue(userCacheRecorder.LastAfterAccessNotificationArgs.HasTokens);
Assert.AreEqual(atHash, userCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource);
//Expire access tokens
TokenCacheHelper.ExpireAllAccessTokens(confidentialApp.UserTokenCacheInternal);
//Run OBO again. Should do OBO flow since the AT is expired and RTs aren't cached for normal OBO flow
authResult = await confidentialApp.AcquireTokenOnBehalfOf(s_scopes, userAssertion)
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);
Assert.IsNotNull(authResult);
Assert.IsNotNull(authResult.AccessToken);
Assert.IsNotNull(authResult.IdToken);
Assert.IsFalse(userCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
Assert.IsTrue(userCacheRecorder.LastAfterAccessNotificationArgs.HasTokens);
Assert.AreEqual(atHash, userCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
AssertLastHttpContent("on_behalf_of");
//creating second app with no refresh tokens
var atItems = confidentialApp.UserTokenCacheInternal.Accessor.GetAllAccessTokens();
var confidentialApp2 = ConfidentialClientApplicationBuilder
.Create(appApi.AppId)
.WithAuthority(new Uri("https://login.microsoftonline.com/" + authResult.TenantId), true)
.WithCertificate(_labAuthCert)
.WithTestLogging()
.WithHttpClientFactory(factory)
.BuildConcrete();
TokenCacheHelper.ExpireAccessToken(confidentialApp2.UserTokenCacheInternal, atItems.FirstOrDefault());
//Should perform OBO flow since the access token is expired and the refresh token does not exist
authResult = await confidentialApp2.AcquireTokenOnBehalfOf(s_scopes, userAssertion)
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);
Assert.IsNotNull(authResult);
Assert.IsNotNull(authResult.AccessToken);
Assert.IsNotNull(authResult.IdToken);
Assert.IsFalse(userCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
Assert.IsTrue(userCacheRecorder.LastAfterAccessNotificationArgs.HasTokens);
Assert.AreEqual(atHash, userCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
AssertLastHttpContent("on_behalf_of");
TokenCacheHelper.ExpireAllAccessTokens(confidentialApp2.UserTokenCacheInternal);
TokenCacheHelper.UpdateUserAssertions(confidentialApp2);
//Should perform OBO flow since the access token and the refresh token contains the wrong user assertion hash
authResult = await confidentialApp2.AcquireTokenOnBehalfOf(s_scopes, userAssertion)
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);
Assert.IsNotNull(authResult);
Assert.IsNotNull(authResult.AccessToken);
Assert.IsNotNull(authResult.IdToken);
Assert.IsFalse(userCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
Assert.IsTrue(userCacheRecorder.LastAfterAccessNotificationArgs.HasTokens);
Assert.AreEqual(atHash, userCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
AssertLastHttpContent("on_behalf_of");
void AssertLastHttpContent(string content)
{
Assert.Contains(content, HttpSnifferClientFactory.LastHttpContentData);
HttpSnifferClientFactory.LastHttpContentData = string.Empty;
}
}
private async Task<IConfidentialClientApplication> RunOnBehalfOfTestAsync(
UserConfig user,
bool silentCallShouldSucceed,
bool forceRefresh = false,
string multiTenantAppId = null)
{
AuthenticationResult authResult;
// Get multiTenantAppId if not provided
if (string.IsNullOrEmpty(multiTenantAppId))
{
var app = await LabResponseHelper.GetAppConfigAsync(KeyVaultSecrets.AppS2S).ConfigureAwait(false);
multiTenantAppId = app.AppId;
}
var appApi = await LabResponseHelper.GetAppConfigAsync(KeyVaultSecrets.AppOBOService).ConfigureAwait(false);
var pca = PublicClientApplicationBuilder
.Create(multiTenantAppId)
.WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
.WithTestLogging()
.Build();
s_inMemoryTokenCache.Bind(pca.UserTokenCache);
try
{
authResult = await pca
.AcquireTokenSilent([appApi.DefaultScopes], user.Upn)
.ExecuteAsync()
.ConfigureAwait(false);
Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource);
}
catch (MsalUiRequiredException)
{
Assert.IsFalse(silentCallShouldSucceed, "ATS should have found a token, but it didn't");
#pragma warning disable CS0618 // Type or member is obsolete
authResult = await pca
.AcquireTokenByUsernamePassword([appApi.DefaultScopes], user.Upn, user.GetOrFetchPassword())
//.AcquireTokenInteractive([appApi.DefaultScopes])
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);
#pragma warning restore CS0618
Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
}
MsalAssert.AssertAuthResult(authResult, user);
Assert.IsTrue(authResult.Scopes.Any(s => string.Equals(s, appApi.DefaultScopes, StringComparison.OrdinalIgnoreCase)));
var cca = ConfidentialClientApplicationBuilder
.Create(appApi.AppId)
.WithAuthority(new Uri("https://login.microsoftonline.com/" + authResult.TenantId), true)
.WithTestLogging(out HttpSnifferClientFactory factory)
.WithCertificate(_labAuthCert)
.Build();
s_inMemoryTokenCache.Bind(cca.UserTokenCache);
authResult = await cca.AcquireTokenOnBehalfOf(s_scopes, new UserAssertion(authResult.AccessToken))
.WithForceRefresh(forceRefresh)
.WithCcsRoutingHint("597f86cd-13f3-44c0-bece-a1e77ba43228", "f645ad92-e38d-4d1a-b510-d1b09a74a8ca")
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);
if (!forceRefresh)
{
Assert.AreEqual(
silentCallShouldSucceed,
authResult.AuthenticationResultMetadata.TokenSource == TokenSource.Cache);
}
else
{
Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
}
MsalAssert.AssertAuthResult(authResult, user);
Assert.IsNotNull(authResult.IdToken); // https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/1950
Assert.IsTrue(authResult.Scopes.Any(s => string.Equals(s, s_scopes.Single(), StringComparison.OrdinalIgnoreCase)));
AssertExtraHttpHeadersAreSent(factory);
return cca;
void AssertExtraHttpHeadersAreSent(HttpSnifferClientFactory factory)
{
//Validate CCS Routing header
if (!factory.RequestsAndResponses.Any())
{
return;
}
var (req, _) = factory.RequestsAndResponses.Single(x =>
x.Item1.RequestUri.AbsoluteUri.Contains("oauth2/v2.0/token") &&
x.Item2.StatusCode == HttpStatusCode.OK);
Assert.IsTrue(req.Headers.TryGetValues(Constants.CcsRoutingHintHeader, out var values));
Assert.AreEqual("oid:597f86cd-13f3-44c0-bece-a1e77ba43228@f645ad92-e38d-4d1a-b510-d1b09a74a8ca", values.First());
}
}
private async Task<ConfidentialClientApplication> BuildCcaAsync(string tenantId, bool withRegion = false)
{
var appApiConfig = await LabResponseHelper.GetAppConfigAsync(KeyVaultSecrets.AppOBOService).ConfigureAwait(false);
var builder = ConfidentialClientApplicationBuilder
.Create(appApiConfig.AppId)
.WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"), true)
.WithCertificate(_labAuthCert, true)
.WithLegacyCacheCompatibility(false);
if (withRegion)
{
builder.WithAzureRegion(TestConstants.Region);
}
return builder.BuildConcrete();
}
}
}