-
Notifications
You must be signed in to change notification settings - Fork 217
/
TokenAcquisition.cs
1022 lines (928 loc) · 49.3 KB
/
TokenAcquisition.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
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Identity.Abstractions;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Advanced;
using Microsoft.Identity.Client.Extensibility;
using Microsoft.Identity.Web.TokenCacheProviders;
using Microsoft.Identity.Web.TokenCacheProviders.InMemory;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
namespace Microsoft.Identity.Web
{
/// <summary>
/// Token acquisition service.
/// </summary>
#if NETSTANDARD2_0 || NET462 || NET472
internal partial class TokenAcquisition : ITokenAcquisitionInternal
#else
internal partial class TokenAcquisition
#endif
{
#if NETSTANDARD2_0 || NET462 || NET472
class OAuthConstants
{
public static readonly string CodeVerifierKey = "code_verifier";
}
#endif
protected readonly IMsalTokenCacheProvider _tokenCacheProvider;
private readonly object _applicationSyncObj = new();
/// <summary>
/// Please call GetOrBuildConfidentialClientApplication instead of accessing this field directly.
/// </summary>
private readonly ConcurrentDictionary<string, IConfidentialClientApplication?> _applicationsByAuthorityClientId = new ConcurrentDictionary<string, IConfidentialClientApplication?>();
private bool _retryClientCertificate;
protected readonly IMsalHttpClientFactory _httpClientFactory;
protected readonly ILogger _logger;
protected readonly IServiceProvider _serviceProvider;
protected readonly ITokenAcquisitionHost _tokenAcquisitionHost;
protected readonly ICredentialsLoader _credentialsLoader;
/// <summary>
/// Scopes which are already requested by MSAL.NET. They should not be re-requested;.
/// </summary>
private readonly string[] _scopesRequestedByMsal = new[] {
OidcConstants.ScopeOpenId,
OidcConstants.ScopeProfile,
OidcConstants.ScopeOfflineAccess,
};
/// <summary>
/// Meta-tenant identifiers which are not allowed in client credentials.
/// </summary>
private readonly HashSet<string> _metaTenantIdentifiers = new HashSet<string>(
new[]
{
Constants.Common,
Constants.Organizations,
},
StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Constructor of the TokenAcquisition service. This requires the Azure AD Options to
/// configure the confidential client application and a token cache provider.
/// This constructor is called by ASP.NET Core dependency injection.
/// </summary>
/// <param name="tokenCacheProvider">The App token cache provider.</param>
/// <param name="tokenAcquisitionHost">Host of the token acquisition.</param>
/// <param name="httpClientFactory">HTTP client factory.</param>
/// <param name="logger">Logger.</param>
/// <param name="serviceProvider">Service provider.</param>
/// <param name="credentialsLoader">Credential loader used to provide the credentials.</param>
public TokenAcquisition(
IMsalTokenCacheProvider tokenCacheProvider,
ITokenAcquisitionHost tokenAcquisitionHost,
IHttpClientFactory httpClientFactory,
ILogger<TokenAcquisition> logger,
IServiceProvider serviceProvider,
ICredentialsLoader credentialsLoader)
{
_tokenCacheProvider = tokenCacheProvider;
_httpClientFactory = new MsalAspNetCoreHttpClientFactory(httpClientFactory);
_logger = logger;
_serviceProvider = serviceProvider;
_tokenAcquisitionHost = tokenAcquisitionHost;
_credentialsLoader = credentialsLoader;
}
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Calls Microsoft.Identity.Web.ClientInfo.CreateFromJson(String)")]
#endif
public async Task<AcquireTokenResult> AddAccountToCacheFromAuthorizationCodeAsync(
AuthCodeRedemptionParameters authCodeRedemptionParameters)
{
_ = Throws.IfNull(authCodeRedemptionParameters.Scopes);
MergedOptions mergedOptions = _tokenAcquisitionHost.GetOptions(authCodeRedemptionParameters.AuthenticationScheme, out string effectiveAuthenticationScheme);
try
{
var application = GetOrBuildConfidentialClientApplication(mergedOptions);
// Do not share the access token with ASP.NET Core otherwise ASP.NET will cache it and will not send the OAuth 2.0 request in
// case a further call to AcquireTokenByAuthorizationCodeAsync in the future is required for incremental consent (getting a code requesting more scopes)
// Share the ID token though
string? backUpAuthRoutingHint = string.Empty;
if (!string.IsNullOrEmpty(authCodeRedemptionParameters.ClientInfo))
{
ClientInfo? clientInfoFromAuthorize = ClientInfo.CreateFromJson(authCodeRedemptionParameters.ClientInfo);
if (clientInfoFromAuthorize != null && clientInfoFromAuthorize.UniqueTenantIdentifier != null && clientInfoFromAuthorize.UniqueObjectIdentifier != null)
{
backUpAuthRoutingHint = $"oid:{clientInfoFromAuthorize.UniqueObjectIdentifier}@{clientInfoFromAuthorize.UniqueTenantIdentifier}";
}
}
var builder = application
.AcquireTokenByAuthorizationCode(authCodeRedemptionParameters.Scopes.Except(_scopesRequestedByMsal), authCodeRedemptionParameters.AuthCode)
.WithSendX5C(mergedOptions.SendX5C)
.WithPkceCodeVerifier(authCodeRedemptionParameters.CodeVerifier)
.WithCcsRoutingHint(backUpAuthRoutingHint)
.WithSpaAuthorizationCode(mergedOptions.WithSpaAuthCode);
if (mergedOptions.ExtraQueryParameters != null)
{
builder.WithExtraQueryParameters((Dictionary<string, string>)mergedOptions.ExtraQueryParameters);
}
if (!string.IsNullOrEmpty(authCodeRedemptionParameters.Tenant))
{
builder.WithTenantId(authCodeRedemptionParameters.Tenant);
}
if (mergedOptions.IsB2C)
{
var authority = $"{mergedOptions.Instance}{ClaimConstants.Tfp}/{mergedOptions.Domain}/{authCodeRedemptionParameters.UserFlow ?? mergedOptions.DefaultUserFlow}";
builder.WithB2CAuthority(authority);
}
var result = await builder.ExecuteAsync()
.ConfigureAwait(false);
if (!string.IsNullOrEmpty(result.SpaAuthCode))
{
_tokenAcquisitionHost.SetSession(Constants.SpaAuthCode, result.SpaAuthCode);
}
return new AcquireTokenResult(
result.AccessToken,
result.ExpiresOn,
result.TenantId,
result.IdToken,
result.Scopes,
result.CorrelationId,
result.TokenType);
}
catch (MsalServiceException exMsal) when (IsInvalidClientCertificateOrSignedAssertionError(exMsal))
{
DefaultCertificateLoader.ResetCertificates(mergedOptions.ClientCertificates);
_applicationsByAuthorityClientId[GetApplicationKey(mergedOptions)] = null;
// Retry
_retryClientCertificate = true;
return await AddAccountToCacheFromAuthorizationCodeAsync(authCodeRedemptionParameters).ConfigureAwait(false);
}
catch (MsalException ex)
{
Logger.TokenAcquisitionError(_logger, LogMessages.ExceptionOccurredWhenAddingAnAccountToTheCacheFromAuthCode, ex);
throw;
}
finally
{
_retryClientCertificate = false;
}
}
private static string GetApplicationKey(MergedOptions mergedOptions)
{
return mergedOptions.Instance! + mergedOptions.ClientId;
}
/// <summary>
/// Typically used from a web app or web API controller, this method retrieves an access token
/// for a downstream API using;
/// 1) the token cache (for web apps and web APIs) if a token exists in the cache
/// 2) or the <a href='https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow'>on-behalf-of flow</a>
/// in web APIs, for the user account that is ascertained from claims provided in the current claims principal.
/// instance of the current HttpContext.
/// </summary>
/// <param name="scopes">Scopes to request for the downstream API to call.</param>
/// <param name="authenticationScheme">Authentication scheme. If null, will use OpenIdConnectDefault.AuthenticationScheme
/// if called from a web app, and JwtBearerDefault.AuthenticationScheme if called from a web APIs.</param>
/// <param name="tenantId">Enables overriding of the tenant/account for the same identity. This is useful in the
/// cases where a given account is a guest in other tenants, and you want to acquire tokens for a specific tenant, like where the user is a guest.</param>
/// <param name="userFlow">Azure AD B2C user flow to target.</param>
/// <param name="user">Optional claims principal representing the user. If not provided, will use the signed-in
/// user (in a web app), or the user for which the token was received (in a web API)
/// cases where a given account is a guest in other tenants, and you want to acquire tokens for a specific tenant, like where the user is a guest.</param>
/// <param name="tokenAcquisitionOptions">Options passed-in to create the token acquisition options object which calls into MSAL .NET.</param>
/// <returns>An access token to call the downstream API and populated with this downstream API's scopes.</returns>
/// <remarks>Calling this method from a web API supposes that you have previously called,
/// in a method called by JwtBearerOptions.Events.OnTokenValidated, the HttpContextExtensions.StoreTokenUsedToCallWebAPI method
/// passing the validated token (as a JwtSecurityToken or JSonWebToken). Calling it from a web app supposes that
/// you have previously called AddAccountToCacheFromAuthorizationCodeAsync from a method called by
/// OpenIdConnectOptions.Events.OnAuthorizationCodeReceived.</remarks>
public async Task<AuthenticationResult> GetAuthenticationResultForUserAsync(
IEnumerable<string> scopes,
string? authenticationScheme = null,
string? tenantId = null,
string? userFlow = null,
ClaimsPrincipal? user = null,
TokenAcquisitionOptions? tokenAcquisitionOptions = null)
{
_ = Throws.IfNull(scopes);
MergedOptions mergedOptions = _tokenAcquisitionHost.GetOptions(authenticationScheme, out _);
user ??= await _tokenAcquisitionHost.GetAuthenticatedUserAsync(user).ConfigureAwait(false);
var application = GetOrBuildConfidentialClientApplication(mergedOptions);
try
{
AuthenticationResult? authenticationResult;
// Access token will return if call is from a web API
authenticationResult = await GetAuthenticationResultForWebApiToCallDownstreamApiAsync(
application,
tenantId,
scopes,
tokenAcquisitionOptions,
mergedOptions,
user).ConfigureAwait(false);
if (authenticationResult != null)
{
LogAuthResult(authenticationResult);
return authenticationResult;
}
// If access token is null, this is a web app
authenticationResult = await GetAuthenticationResultForWebAppWithAccountFromCacheAsync(
application,
user,
scopes,
tenantId,
mergedOptions,
userFlow,
tokenAcquisitionOptions)
.ConfigureAwait(false);
LogAuthResult(authenticationResult);
return authenticationResult;
}
catch (MsalServiceException exMsal) when (IsInvalidClientCertificateOrSignedAssertionError(exMsal))
{
DefaultCertificateLoader.ResetCertificates(mergedOptions.ClientCertificates);
_applicationsByAuthorityClientId[GetApplicationKey(mergedOptions)] = null;
// Retry
_retryClientCertificate = true;
return await GetAuthenticationResultForUserAsync(
scopes,
authenticationScheme: authenticationScheme,
tenantId: tenantId,
userFlow: userFlow,
user: user,
tokenAcquisitionOptions: tokenAcquisitionOptions).ConfigureAwait(false);
}
catch (MsalUiRequiredException ex)
{
// GetAccessTokenForUserAsync is an abstraction that can be called from a web app or a web API
Logger.TokenAcquisitionError(_logger, ex.Message, ex);
// Case of the web app: we let the MsalUiRequiredException be caught by the
// AuthorizeForScopesAttribute exception filter so that the user can consent, do 2FA, etc ...
throw new MicrosoftIdentityWebChallengeUserException(ex, scopes.ToArray(), userFlow);
}
finally
{
_retryClientCertificate = false;
}
}
private void LogAuthResult(AuthenticationResult? authenticationResult)
{
if (authenticationResult != null)
{
Logger.TokenAcquisitionMsalAuthenticationResultTime(
_logger,
authenticationResult.AuthenticationResultMetadata.DurationTotalInMs,
authenticationResult.AuthenticationResultMetadata.DurationInHttpInMs,
authenticationResult.AuthenticationResultMetadata.DurationInCacheInMs,
authenticationResult.AuthenticationResultMetadata.TokenSource.ToString(),
authenticationResult.CorrelationId.ToString(),
authenticationResult.AuthenticationResultMetadata.CacheRefreshReason.ToString(),
null);
}
}
/// <summary>
/// Acquires an authentication result from the authority configured in the app, for the confidential client itself (not on behalf of a user)
/// using the client credentials flow. See https://aka.ms/msal-net-client-credentials.
/// </summary>
/// <param name="scope">The scope requested to access a protected API. For this flow (client credentials), the scope
/// should be of the form "{ResourceIdUri/.default}" for instance <c>https://management.azure.net/.default</c> or, for Microsoft
/// Graph, <c>https://graph.microsoft.com/.default</c> as the requested scopes are defined statically with the application registration
/// in the portal, and cannot be overridden in the application, as you can request a token for only one resource at a time (use
/// several calls to get tokens for other resources).</param>
/// <param name="authenticationScheme">AuthenticationScheme to use.</param>
/// <param name="tenant">Enables overriding of the tenant/account for the same identity. This is useful
/// for multi tenant apps or daemons.</param>
/// <param name="tokenAcquisitionOptions">Options passed-in to create the token acquisition object which calls into MSAL .NET.</param>
/// <returns>An authentication result for the app itself, based on its scopes.</returns>
public Task<AuthenticationResult> GetAuthenticationResultForAppAsync(
string scope,
string? authenticationScheme = null,
string? tenant = null,
TokenAcquisitionOptions? tokenAcquisitionOptions = null)
{
_ = Throws.IfNull(scope);
if (!scope.EndsWith("/.default", true, CultureInfo.InvariantCulture))
{
throw new ArgumentException(IDWebErrorMessage.ClientCredentialScopeParameterShouldEndInDotDefault, nameof(scope));
}
MergedOptions mergedOptions = _tokenAcquisitionHost.GetOptions(authenticationScheme ?? tokenAcquisitionOptions?.AuthenticationOptionsName, out _);
if (string.IsNullOrEmpty(tenant))
{
tenant = mergedOptions.TenantId;
}
if (!string.IsNullOrEmpty(tenant) && _metaTenantIdentifiers.Contains(tenant!))
{
throw new ArgumentException(IDWebErrorMessage.ClientCredentialTenantShouldBeTenanted, nameof(tenant));
}
// Use MSAL to get the right token to call the API
var application = GetOrBuildConfidentialClientApplication(mergedOptions);
var builder = application
.AcquireTokenForClient(new[] { scope }.Except(_scopesRequestedByMsal))
.WithSendX5C(mergedOptions.SendX5C);
// MSAL.net only allows .WithTenantId for AAD authorities. This makes sense as there should
// not be cross tenant operations with such an authority.
if (!mergedOptions.Instance.Contains(Constants.CiamAuthoritySuffix
#if NETCOREAPP3_1_OR_GREATER
, StringComparison.OrdinalIgnoreCase
#endif
))
{
builder.WithTenantId(tenant);
}
if (tokenAcquisitionOptions != null)
{
var dict = MergeExtraQueryParameters(mergedOptions, tokenAcquisitionOptions);
if (dict != null)
{
builder.WithExtraQueryParameters(dict);
}
if (tokenAcquisitionOptions.ExtraHeadersParameters != null)
{
builder.WithExtraHttpHeaders(tokenAcquisitionOptions.ExtraHeadersParameters);
}
if (tokenAcquisitionOptions.CorrelationId != null)
{
builder.WithCorrelationId(tokenAcquisitionOptions.CorrelationId.Value);
}
builder.WithForceRefresh(tokenAcquisitionOptions.ForceRefresh);
builder.WithClaims(tokenAcquisitionOptions.Claims);
if (tokenAcquisitionOptions.PoPConfiguration != null)
{
builder.WithProofOfPossession(tokenAcquisitionOptions.PoPConfiguration);
}
if (!string.IsNullOrEmpty(tokenAcquisitionOptions.PopPublicKey))
{
if (string.IsNullOrEmpty(tokenAcquisitionOptions.PopClaim))
{
builder.WithProofOfPosessionKeyId(tokenAcquisitionOptions.PopPublicKey, "pop");
builder.OnBeforeTokenRequest((data) =>
{
data.BodyParameters.Add("req_cnf", tokenAcquisitionOptions.PopPublicKey);
data.BodyParameters.Add("token_type", "pop");
return Task.CompletedTask;
});
}
else
{
builder.WithAtPop(
application.AppConfig.ClientCredentialCertificate,
tokenAcquisitionOptions.PopPublicKey!,
tokenAcquisitionOptions.PopClaim!,
application.AppConfig.ClientId);
}
}
}
try
{
return builder.ExecuteAsync(tokenAcquisitionOptions != null ? tokenAcquisitionOptions.CancellationToken : CancellationToken.None);
}
catch (MsalServiceException exMsal) when (IsInvalidClientCertificateOrSignedAssertionError(exMsal))
{
DefaultCertificateLoader.ResetCertificates(mergedOptions.ClientCertificates);
_applicationsByAuthorityClientId[GetApplicationKey(mergedOptions)] = null;
// Retry
_retryClientCertificate = true;
return GetAuthenticationResultForAppAsync(
scope,
authenticationScheme: authenticationScheme,
tenant: tenant,
tokenAcquisitionOptions: tokenAcquisitionOptions);
}
finally
{
_retryClientCertificate = false;
}
}
/// <summary>
/// Acquires a token from the authority configured in the app, for the confidential client itself (not on behalf of a user)
/// using the client credentials flow. See https://aka.ms/msal-net-client-credentials.
/// </summary>
/// <param name="scope">The scope requested to access a protected API. For this flow (client credentials), the scope
/// should be of the form "{ResourceIdUri/.default}" for instance <c>https://management.azure.net/.default</c> or, for Microsoft
/// Graph, <c>https://graph.microsoft.com/.default</c> as the requested scopes are defined statically with the application registration
/// in the portal, and cannot be overridden in the application, as you can request a token for only one resource at a time (use
/// several calls to get tokens for other resources).</param>
/// <param name="authenticationScheme">AuthenticationScheme to use.</param>
/// <param name="tenant">Enables overriding of the tenant/account for the same identity. This is useful
/// for multi tenant apps or daemons.</param>
/// <param name="tokenAcquisitionOptions">Options passed-in to create the token acquisition object which calls into MSAL .NET.</param>
/// <returns>An access token for the app itself, based on its scopes.</returns>
public async Task<string> GetAccessTokenForAppAsync(
string scope,
string? authenticationScheme = null,
string? tenant = null,
TokenAcquisitionOptions? tokenAcquisitionOptions = null)
{
AuthenticationResult authResult = await GetAuthenticationResultForAppAsync(
scope,
authenticationScheme,
tenant,
tokenAcquisitionOptions).ConfigureAwait(false);
return authResult.AccessToken;
}
/// <summary>
/// Typically used from a web app or web API controller, this method retrieves an access token
/// for a downstream API using;
/// 1) the token cache (for web apps and web APIs) if a token exists in the cache
/// 2) or the <a href='https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow'>on-behalf-of flow</a>
/// in web APIs, for the user account that is ascertained from the claims provided in the current claims principal.
/// instance of the current HttpContext.
/// </summary>
/// <param name="scopes">Scopes to request for the downstream API to call.</param>
/// <param name="authenticationScheme">Authentication scheme. If null, will use OpenIdConnectDefault.AuthenticationScheme
/// if called from a web app, and JwtBearerDefault.AuthenticationScheme if called from a web API.</param>
/// <param name="tenantId">Enables overriding of the tenant/account for the same identity. This is useful in the
/// cases where a given account is a guest in other tenants, and you want to acquire tokens for a specific tenant.</param>
/// <param name="userFlow">Azure AD B2C user flow to target.</param>
/// <param name="user">Optional claims principal representing the user. If not provided, will use the signed-in
/// user (in a web app), or the user for which the token was received (in a web API)
/// cases where a given account is a guest in other tenants, and you want to acquire tokens for a specific tenant.</param>
/// <param name="tokenAcquisitionOptions">Options passed-in to create the token acquisition object which calls into MSAL .NET.</param>
/// <returns>An access token to call the downstream API and populated with this downstream API's scopes.</returns>
/// <remarks>Calling this method from a web API supposes that you have previously called,
/// in a method called by JwtBearerOptions.Events.OnTokenValidated, the HttpContextExtensions.StoreTokenUsedToCallWebAPI method
/// passing the validated token (as a JwtSecurityToken or JSonWebToken). Calling it from a web app supposes that
/// you have previously called AddAccountToCacheFromAuthorizationCodeAsync from a method called by
/// OpenIdConnectOptions.Events.OnAuthorizationCodeReceived.</remarks>
public async Task<string> GetAccessTokenForUserAsync(
IEnumerable<string> scopes,
string? authenticationScheme = null,
string? tenantId = null,
string? userFlow = null,
ClaimsPrincipal? user = null,
TokenAcquisitionOptions? tokenAcquisitionOptions = null)
{
AuthenticationResult result =
await GetAuthenticationResultForUserAsync(
scopes,
authenticationScheme,
tenantId,
userFlow,
user,
tokenAcquisitionOptions).ConfigureAwait(false);
return result.AccessToken;
}
/// <summary>
/// Removes the account associated with context.HttpContext.User from the MSAL.NET cache.
/// </summary>
/// <param name="user">User</param>
/// <param name="authenticationScheme">Authentication scheme. If null, will use OpenIdConnectDefault.AuthenticationScheme
/// if called from a web app, and JwtBearerDefault.AuthenticationScheme if called from a web API.</param>
/// <returns>A <see cref="Task"/> that represents a completed account removal operation.</returns>
public async Task RemoveAccountAsync(
ClaimsPrincipal user,
string? authenticationScheme = null)
{
string? userId = user.GetMsalAccountId();
if (!string.IsNullOrEmpty(userId))
{
MergedOptions mergedOptions = _tokenAcquisitionHost.GetOptions(authenticationScheme, out _);
IConfidentialClientApplication app = GetOrBuildConfidentialClientApplication(mergedOptions);
if (mergedOptions.IsB2C)
{
await _tokenCacheProvider.ClearAsync(userId!).ConfigureAwait(false);
}
else
{
string? identifier = user.GetMsalAccountId();
IAccount account = await app.GetAccountAsync(identifier).ConfigureAwait(false);
if (account != null)
{
await app.RemoveAsync(account).ConfigureAwait(false);
await _tokenCacheProvider.ClearAsync(userId!).ConfigureAwait(false);
}
}
}
}
private bool IsInvalidClientCertificateOrSignedAssertionError(MsalServiceException exMsal)
{
return !_retryClientCertificate &&
string.Equals(exMsal.ErrorCode, Constants.InvalidClient, StringComparison.OrdinalIgnoreCase) &&
#if !NETSTANDARD2_0 && !NET462 && !NET472
(exMsal.Message.Contains(Constants.InvalidKeyError, StringComparison.OrdinalIgnoreCase)
|| exMsal.Message.Contains(Constants.SignedAssertionInvalidTimeRange, StringComparison.OrdinalIgnoreCase));
#else
(exMsal.Message.Contains(Constants.InvalidKeyError) || exMsal.Message.Contains(Constants.SignedAssertionInvalidTimeRange));
#endif
}
internal /* for testing */ IConfidentialClientApplication GetOrBuildConfidentialClientApplication(
MergedOptions mergedOptions)
{
if (!_applicationsByAuthorityClientId.TryGetValue(GetApplicationKey(mergedOptions), out IConfidentialClientApplication? application) || application == null)
{
lock (_applicationSyncObj)
{
application = BuildConfidentialClientApplication(mergedOptions);
_applicationsByAuthorityClientId.TryAdd(GetApplicationKey(mergedOptions), application);
}
}
return application;
}
/// <summary>
/// Creates an MSAL confidential client application.
/// </summary>
private IConfidentialClientApplication BuildConfidentialClientApplication(MergedOptions mergedOptions)
{
string? currentUri = _tokenAcquisitionHost.GetCurrentRedirectUri(mergedOptions);
mergedOptions.PrepareAuthorityInstanceForMsal();
try
{
var builder = ConfidentialClientApplicationBuilder
.CreateWithApplicationOptions(mergedOptions.ConfidentialClientApplicationOptions)
.WithHttpClientFactory(_httpClientFactory)
.WithLogging(
Log,
ConvertMicrosoftExtensionsLogLevelToMsal(_logger),
enablePiiLogging: mergedOptions.ConfidentialClientApplicationOptions.EnablePiiLogging)
.WithExperimentalFeatures();
if (_tokenCacheProvider is MsalMemoryTokenCacheProvider)
{
builder.WithCacheOptions(CacheOptions.EnableSharedCacheOptions);
}
// The redirect URI is not needed for OBO
if (!string.IsNullOrEmpty(currentUri))
{
builder.WithRedirectUri(currentUri);
}
string authority;
if (mergedOptions.IsB2C)
{
authority = $"{mergedOptions.Instance}{ClaimConstants.Tfp}/{mergedOptions.Domain}/{mergedOptions.DefaultUserFlow}";
builder.WithB2CAuthority(authority);
}
else
{
authority = $"{mergedOptions.Instance}{mergedOptions.TenantId}/";
builder.WithAuthority(authority);
}
try
{
builder.WithClientCredentials(
mergedOptions.ClientCredentials!,
_logger,
_credentialsLoader,
new CredentialSourceLoaderParameters(mergedOptions.ClientId!, authority));
}
catch (ArgumentException ex) when (ex.Message == IDWebErrorMessage.ClientCertificatesHaveExpiredOrCannotBeLoaded)
{
Logger.TokenAcquisitionError(
_logger,
IDWebErrorMessage.ClientCertificatesHaveExpiredOrCannotBeLoaded,
null);
throw;
}
IConfidentialClientApplication app = builder.Build();
// Initialize token cache providers
if (!(_tokenCacheProvider is MsalMemoryTokenCacheProvider))
{
_tokenCacheProvider.Initialize(app.AppTokenCache);
_tokenCacheProvider.Initialize(app.UserTokenCache);
}
return app;
}
catch (Exception ex)
{
Logger.TokenAcquisitionError(
_logger,
IDWebErrorMessage.ExceptionAcquiringTokenForConfidentialClient,
ex);
throw;
}
}
private async Task<AuthenticationResult?> GetAuthenticationResultForWebApiToCallDownstreamApiAsync(
IConfidentialClientApplication application,
string? tenantId,
IEnumerable<string> scopes,
TokenAcquisitionOptions? tokenAcquisitionOptions,
MergedOptions mergedOptions,
ClaimsPrincipal? userHint)
{
try
{
// In web API, validatedToken will not be null
SecurityToken? validatedToken = userHint?.GetBootstrapToken() ?? _tokenAcquisitionHost.GetTokenUsedToCallWebAPI();
// In the case the token is a JWE (encrypted token), we use the decrypted token.
string? tokenUsedToCallTheWebApi = GetActualToken(validatedToken);
AcquireTokenOnBehalfOfParameterBuilder? builder = null;
// Case of web APIs: we need to do an on-behalf-of flow, with the token used to call the API
if (tokenUsedToCallTheWebApi != null)
{
if (string.IsNullOrEmpty(tokenAcquisitionOptions?.LongRunningWebApiSessionKey))
{
builder = application
.AcquireTokenOnBehalfOf(
scopes.Except(_scopesRequestedByMsal),
new UserAssertion(tokenUsedToCallTheWebApi));
}
else
{
string? sessionKey = tokenAcquisitionOptions!.LongRunningWebApiSessionKey;
if (sessionKey == Abstractions.AcquireTokenOptions.LongRunningWebApiSessionKeyAuto)
{
sessionKey = null;
}
builder = (application as ILongRunningWebApi)?
.InitiateLongRunningProcessInWebApi(
scopes.Except(_scopesRequestedByMsal),
tokenUsedToCallTheWebApi,
ref sessionKey);
tokenAcquisitionOptions.LongRunningWebApiSessionKey = sessionKey;
}
}
else if (!string.IsNullOrEmpty(tokenAcquisitionOptions?.LongRunningWebApiSessionKey))
{
string sessionKey = tokenAcquisitionOptions!.LongRunningWebApiSessionKey!;
builder = (application as ILongRunningWebApi)?
.AcquireTokenInLongRunningProcess(
scopes.Except(_scopesRequestedByMsal),
sessionKey);
}
if (builder != null)
{
builder.WithSendX5C(mergedOptions.SendX5C);
ClaimsPrincipal? user = _tokenAcquisitionHost.GetUserFromRequest();
var userTenant = string.Empty;
if (user != null)
{
userTenant = user.GetTenantId();
builder.WithCcsRoutingHint(user.GetObjectId(), userTenant);
}
if (!string.IsNullOrEmpty(tenantId))
{
builder.WithTenantId(tenantId);
}
else
{
if (!string.IsNullOrEmpty(userTenant))
{
builder.WithTenantId(userTenant);
}
}
if (tokenAcquisitionOptions != null)
{
var dict = MergeExtraQueryParameters(mergedOptions, tokenAcquisitionOptions);
if (dict != null)
{
const string assertionConstant = "assertion";
const string subAssertionConstant = "sub_assertion";
// Special case when the OBO inbound token is composite (for instance PFT)
if (dict.ContainsKey(assertionConstant) && dict.ContainsKey(subAssertionConstant))
{
builder.OnBeforeTokenRequest((data) =>
{
// Replace the assertion and adds sub_assertion with the values from the extra query parameters
data.BodyParameters[assertionConstant] = dict[assertionConstant];
data.BodyParameters.Add(subAssertionConstant, dict[subAssertionConstant]);
return Task.CompletedTask;
});
// Remove the assertion and sub_assertion from the extra query parameters
// as they are already handled as body parameters.
dict.Remove(assertionConstant);
dict.Remove(subAssertionConstant);
}
builder.WithExtraQueryParameters(dict);
}
if (tokenAcquisitionOptions.ExtraHeadersParameters != null)
{
builder.WithExtraHttpHeaders(tokenAcquisitionOptions.ExtraHeadersParameters);
}
if (tokenAcquisitionOptions.CorrelationId != null)
{
builder.WithCorrelationId(tokenAcquisitionOptions.CorrelationId.Value);
}
builder.WithForceRefresh(tokenAcquisitionOptions.ForceRefresh);
builder.WithClaims(tokenAcquisitionOptions.Claims);
if (tokenAcquisitionOptions.PoPConfiguration != null)
{
builder.WithProofOfPossession(tokenAcquisitionOptions.PoPConfiguration);
}
}
return await builder.ExecuteAsync(tokenAcquisitionOptions != null ? tokenAcquisitionOptions.CancellationToken : CancellationToken.None)
.ConfigureAwait(false);
}
return null;
}
catch (MsalUiRequiredException ex)
{
Logger.TokenAcquisitionError(
_logger,
LogMessages.ErrorAcquiringTokenForDownstreamWebApi + ex.Message,
ex);
throw;
}
}
private static string? GetActualToken(SecurityToken? validatedToken)
{
JwtSecurityToken? jwtSecurityToken = validatedToken as JwtSecurityToken;
if (jwtSecurityToken != null)
{
// In the case the token is a JWE (encrypted token), we use the decrypted token.
return jwtSecurityToken.InnerToken == null ? jwtSecurityToken.RawData
: jwtSecurityToken.InnerToken.RawData;
}
JsonWebToken? jsonWebToken = validatedToken as JsonWebToken;
if (jsonWebToken != null)
{
// In the case the token is a JWE (encrypted token), we use the decrypted token.
return jsonWebToken.InnerToken == null ? jsonWebToken.EncodedToken
: jsonWebToken.InnerToken.EncodedToken;
}
return null;
}
/// <summary>
/// Gets an access token for a downstream API on behalf of the user described by its claimsPrincipal.
/// </summary>
/// <param name="application"><see cref="IConfidentialClientApplication"/>.</param>
/// <param name="claimsPrincipal">Claims principal for the user on behalf of whom to get a token.</param>
/// <param name="scopes">Scopes for the downstream API to call.</param>
/// <param name="tenantId">(optional) TenantID based on a specific tenant for which to acquire a token to access the scopes
/// on behalf of the user described in the claimsPrincipal.</param>
/// <param name="mergedOptions">Merged options.</param>
/// <param name="userFlow">Azure AD B2C user flow to target.</param>
/// <param name="tokenAcquisitionOptions">Options passed-in to create the token acquisition object which calls into MSAL .NET.</param>
private async Task<AuthenticationResult> GetAuthenticationResultForWebAppWithAccountFromCacheAsync(
IConfidentialClientApplication application,
ClaimsPrincipal? claimsPrincipal,
IEnumerable<string> scopes,
string? tenantId,
MergedOptions mergedOptions,
string? userFlow = null,
TokenAcquisitionOptions? tokenAcquisitionOptions = null)
{
IAccount? account = null;
if (mergedOptions.IsB2C && !string.IsNullOrEmpty(userFlow))
{
string? nameIdentifierId = claimsPrincipal?.GetNameIdentifierId();
string? utid = claimsPrincipal?.GetHomeTenantId();
string? b2cAccountIdentifier = string.Format(CultureInfo.InvariantCulture, "{0}-{1}.{2}", nameIdentifierId, userFlow, utid);
account = await application.GetAccountAsync(b2cAccountIdentifier).ConfigureAwait(false);
}
else
{
string? accountIdentifier = claimsPrincipal?.GetMsalAccountId();
if (accountIdentifier != null)
{
account = await application.GetAccountAsync(accountIdentifier).ConfigureAwait(false);
}
}
return await GetAuthenticationResultForWebAppWithAccountFromCacheAsync(
application,
account,
scopes,
tenantId,
mergedOptions,
userFlow,
tokenAcquisitionOptions).ConfigureAwait(false);
}
/// <summary>
/// Gets an access token for a downstream API on behalf of the user whose account is passed as an argument.
/// </summary>
/// <param name="application"><see cref="IConfidentialClientApplication"/>.</param>
/// <param name="account">User IAccount for which to acquire a token.
/// See <see cref="Microsoft.Identity.Client.AccountId.Identifier"/>.</param>
/// <param name="scopes">Scopes for the downstream API to call.</param>
/// <param name="tenantId">TenantID based on a specific tenant for which to acquire a token to access the scopes
/// on behalf of the user.</param>
/// <param name="mergedOptions">Merged options.</param>
/// <param name="userFlow">Azure AD B2C user flow.</param>
/// <param name="tokenAcquisitionOptions">Options passed-in to create the token acquisition object which calls into MSAL .NET.</param>
private Task<AuthenticationResult> GetAuthenticationResultForWebAppWithAccountFromCacheAsync(
IConfidentialClientApplication application,
IAccount? account,
IEnumerable<string> scopes,
string? tenantId,
MergedOptions mergedOptions,
string? userFlow = null,
TokenAcquisitionOptions? tokenAcquisitionOptions = null)
{
_ = Throws.IfNull(scopes);
var builder = application
.AcquireTokenSilent(scopes.Except(_scopesRequestedByMsal), account)
.WithSendX5C(mergedOptions.SendX5C);
if (tokenAcquisitionOptions != null)
{
var dict = MergeExtraQueryParameters(mergedOptions, tokenAcquisitionOptions);
if (dict != null)
{
builder.WithExtraQueryParameters(dict);
}
if (tokenAcquisitionOptions.ExtraHeadersParameters != null)
{
builder.WithExtraHttpHeaders(tokenAcquisitionOptions.ExtraHeadersParameters);
}
if (tokenAcquisitionOptions.CorrelationId != null)
{
builder.WithCorrelationId(tokenAcquisitionOptions.CorrelationId.Value);
}
builder.WithForceRefresh(tokenAcquisitionOptions.ForceRefresh);
builder.WithClaims(tokenAcquisitionOptions.Claims);
if (tokenAcquisitionOptions.PoPConfiguration != null)
{
builder.WithProofOfPossession(tokenAcquisitionOptions.PoPConfiguration);
}
}
// Acquire an access token as a B2C authority
if (mergedOptions.IsB2C)
{
string b2cAuthority = application.Authority.Replace(
new Uri(application.Authority).PathAndQuery,
$"/{ClaimConstants.Tfp}/{mergedOptions.Domain}/{userFlow ?? mergedOptions.DefaultUserFlow}"
#if !NETSTANDARD2_0 && !NET462 && !NET472
, StringComparison.OrdinalIgnoreCase
#endif
);
builder.WithB2CAuthority(b2cAuthority)
.WithSendX5C(mergedOptions.SendX5C);
}
else if (!string.IsNullOrEmpty(tenantId))
{
builder.WithTenantId(tenantId);
}
return builder.ExecuteAsync(tokenAcquisitionOptions != null ? tokenAcquisitionOptions.CancellationToken : CancellationToken.None);
}
internal static Dictionary<string, string>? MergeExtraQueryParameters(
MergedOptions mergedOptions,
TokenAcquisitionOptions tokenAcquisitionOptions)
{
if (tokenAcquisitionOptions.ExtraQueryParameters != null)
{
var mergedDict = new Dictionary<string, string>(tokenAcquisitionOptions.ExtraQueryParameters);
if (mergedOptions.ExtraQueryParameters != null)
{
foreach (var pair in mergedOptions!.ExtraQueryParameters)
{
if (!mergedDict!.ContainsKey(pair.Key))
mergedDict.Add(pair.Key, pair.Value);
}
}
return mergedDict;
}
return (Dictionary<string, string>?)mergedOptions.ExtraQueryParameters;
}
protected static bool AcceptedTokenVersionMismatch(MsalUiRequiredException msalServiceException)
{
// Normally app developers should not make decisions based on the internal AAD code
// however until the STS sends sub-error codes for this error, this is the only
// way to distinguish the case.
// This is subject to change in the future
return msalServiceException.Message.Contains(
ErrorCodes.B2CPasswordResetErrorCode
#if !NETSTANDARD2_0 && !NET462 && !NET472
, StringComparison.InvariantCulture
#endif
);
}
public string GetEffectiveAuthenticationScheme(string? authenticationScheme)
{
return _tokenAcquisitionHost.GetEffectiveAuthenticationScheme(authenticationScheme);
}
private void Log(
Client.LogLevel level,
string message,
bool containsPii)
{
switch (level)
{
case Client.LogLevel.Always:
_logger.LogInformation(message);
break;
case Client.LogLevel.Error:
_logger.LogError(message);
break;
case Client.LogLevel.Warning:
_logger.LogWarning(message);
break;
case Client.LogLevel.Info:
_logger.LogInformation(message);
break;
case Client.LogLevel.Verbose:
_logger.LogDebug(message);
break;
}
}
private Client.LogLevel? ConvertMicrosoftExtensionsLogLevelToMsal(ILogger logger)
{
if (logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)
|| logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Trace))
{