-
Notifications
You must be signed in to change notification settings - Fork 218
/
TokenAcquisition.cs
936 lines (845 loc) · 44.9 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using Microsoft.Identity.Client;
using Microsoft.Identity.Web.TokenCacheProviders;
using Microsoft.Net.Http.Headers;
namespace Microsoft.Identity.Web
{
/// <summary>
/// Token acquisition service.
/// </summary>
internal partial class TokenAcquisition : ITokenAcquisitionInternal
{
private readonly MicrosoftIdentityOptions _microsoftIdentityOptions;
private readonly ConfidentialClientApplicationOptions _applicationOptions;
private readonly IMsalTokenCacheProvider _tokenCacheProvider;
private readonly object _applicationSyncObj = new object();
/// <summary>
/// Please call GetOrBuildConfidentialClientApplication instead of accessing this field directly.
/// </summary>
private IConfidentialClientApplication? _application;
private bool retryClientCertificate;
private readonly IHttpContextAccessor _httpContextAccessor;
private HttpContext? CurrentHttpContext => _httpContextAccessor.HttpContext;
private readonly IMsalHttpClientFactory _httpClientFactory;
private readonly ILogger _logger;
private readonly IServiceProvider _serviceProvider;
/// <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="httpContextAccessor">Access to the HttpContext of the request.</param>
/// <param name="microsoftIdentityOptions">Configuration options.</param>
/// <param name="applicationOptions">MSAL.NET configuration options.</param>
/// <param name="httpClientFactory">HTTP client factory.</param>
/// <param name="logger">Logger.</param>
/// <param name="serviceProvider">Service provider.</param>
public TokenAcquisition(
IMsalTokenCacheProvider tokenCacheProvider,
IHttpContextAccessor httpContextAccessor,
IOptions<MicrosoftIdentityOptions> microsoftIdentityOptions,
IOptions<ConfidentialClientApplicationOptions> applicationOptions,
IHttpClientFactory httpClientFactory,
ILogger<TokenAcquisition> logger,
IServiceProvider serviceProvider)
{
_httpContextAccessor = httpContextAccessor;
_microsoftIdentityOptions = microsoftIdentityOptions.Value;
_applicationOptions = applicationOptions.Value;
_tokenCacheProvider = tokenCacheProvider;
_httpClientFactory = new MsalAspNetCoreHttpClientFactory(httpClientFactory);
_logger = logger;
_serviceProvider = serviceProvider;
_applicationOptions.ClientId ??= _microsoftIdentityOptions.ClientId;
_applicationOptions.Instance ??= _microsoftIdentityOptions.Instance;
_applicationOptions.ClientSecret ??= _microsoftIdentityOptions.ClientSecret;
_applicationOptions.TenantId ??= _microsoftIdentityOptions.TenantId;
_applicationOptions.LegacyCacheCompatibilityEnabled = _microsoftIdentityOptions.LegacyCacheCompatibilityEnabled;
DefaultCertificateLoader.UserAssignedManagedIdentityClientId = _microsoftIdentityOptions.UserAssignedManagedIdentityClientId;
}
/// <summary>
/// Scopes which are already requested by MSAL.NET. They should not be re-requested;.
/// </summary>
private readonly string[] _scopesRequestedByMsal = new string[]
{
OidcConstants.ScopeOpenId,
OidcConstants.ScopeProfile,
OidcConstants.ScopeOfflineAccess,
};
/// <summary>
/// Meta-tenant identifiers which are not allowed in client credentials.
/// </summary>
private readonly ISet<string> _metaTenantIdentifiers = new HashSet<string>(
new[]
{
Constants.Common,
Constants.Organizations,
},
StringComparer.OrdinalIgnoreCase);
/// <summary>
/// This handler is executed after the authorization code is received (once the user signs-in and consents) during the
/// <a href='https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow'>authorization code flow</a> in a web app.
/// It uses the code to request an access token from the Microsoft identity platform and caches the tokens and an entry about the signed-in user's account in the MSAL's token cache.
/// The access token (and refresh token) provided in the <see cref="AuthorizationCodeReceivedContext"/>, once added to the cache, are then used to acquire more tokens using the
/// <a href='https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow'>on-behalf-of flow</a> for the signed-in user's account,
/// in order to call to downstream APIs.
/// </summary>
/// <param name="context">The context used when an 'AuthorizationCode' is received over the OpenIdConnect protocol.</param>
/// <param name="scopes">scopes to request access to.</param>
/// <example>
/// From the configuration of the Authentication of the ASP.NET Core web API:
/// <code>OpenIdConnectOptions options;</code>
///
/// Subscribe to the authorization code received event:
/// <code>
/// options.Events = new OpenIdConnectEvents();
/// options.Events.OnAuthorizationCodeReceived = OnAuthorizationCodeReceived;
/// }
/// </code>
///
/// And then in the OnAuthorizationCodeRecieved method, call <see cref="AddAccountToCacheFromAuthorizationCodeAsync"/>:
/// <code>
/// private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
/// {
/// var tokenAcquisition = context.HttpContext.RequestServices.GetRequiredService<ITokenAcquisition>();
/// await _tokenAcquisition.AddAccountToCacheFromAuthorizationCode(context, new string[] { "user.read" });
/// }
/// </code>
/// </example>
public async Task AddAccountToCacheFromAuthorizationCodeAsync(
AuthorizationCodeReceivedContext context,
IEnumerable<string> scopes)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (scopes == null)
{
throw new ArgumentNullException(nameof(scopes));
}
try
{
var application = GetOrBuildConfidentialClientApplication();
context.TokenEndpointRequest.Parameters.TryGetValue(OAuthConstants.CodeVerifierKey, out string? codeVerifier);
// 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
var builder = application
.AcquireTokenByAuthorizationCode(scopes.Except(_scopesRequestedByMsal), context.ProtocolMessage.Code)
.WithSendX5C(_microsoftIdentityOptions.SendX5C)
.WithPkceCodeVerifier(codeVerifier);
if (_microsoftIdentityOptions.IsB2C)
{
string? userFlow = context.Principal?.GetUserFlowId();
var authority = $"{_applicationOptions.Instance}{ClaimConstants.Tfp}/{_microsoftIdentityOptions.Domain}/{userFlow ?? _microsoftIdentityOptions.DefaultUserFlow}";
builder.WithB2CAuthority(authority);
}
var result = await builder.ExecuteAsync()
.ConfigureAwait(false);
context.HandleCodeRedemption(null, result.IdToken);
}
catch (MsalServiceException exMsal) when (IsInvalidClientCertificateError(exMsal))
{
DefaultCertificateLoader.ResetCertificates(_microsoftIdentityOptions.ClientCertificates);
_application = null;
// Retry
retryClientCertificate = true;
await AddAccountToCacheFromAuthorizationCodeAsync(context, scopes).ConfigureAwait(false);
}
catch (MsalException ex)
{
Logger.TokenAcquisitionError(_logger, LogMessages.ExceptionOccurredWhenAddingAnAccountToTheCacheFromAuthCode, ex);
throw;
}
finally
{
retryClientCertificate = false;
}
}
/// <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 <see cref="HttpContext.User"/>
/// instance of the current HttpContext.
/// </summary>
/// <param name="scopes">Scopes to request for the downstream API to call.</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). 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? tenantId = null,
string? userFlow = null,
ClaimsPrincipal? user = null,
TokenAcquisitionOptions? tokenAcquisitionOptions = null)
{
if (scopes == null)
{
throw new ArgumentNullException(nameof(scopes));
}
user = await GetAuthenticatedUserAsync(user).ConfigureAwait(false);
var application = GetOrBuildConfidentialClientApplication();
string authority = CreateAuthorityBasedOnTenantIfProvided(application, tenantId);
try
{
// Access token will return if call is from a web API
var authenticationResult = await GetAuthenticationResultForWebApiToCallDownstreamApiAsync(
application,
authority,
scopes,
tokenAcquisitionOptions).ConfigureAwait(false);
if (authenticationResult != null)
{
return authenticationResult;
}
// If access token is null, this is a web app
return await GetAuthenticationResultForWebAppWithAccountFromCacheAsync(
application,
user,
scopes,
authority,
userFlow)
.ConfigureAwait(false);
}
catch (MsalServiceException exMsal) when (IsInvalidClientCertificateError(exMsal))
{
DefaultCertificateLoader.ResetCertificates(_microsoftIdentityOptions.ClientCertificates);
_application = null;
// Retry
retryClientCertificate = true;
return await GetAuthenticationResultForUserAsync(scopes, tenantId, userFlow, user, 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;
}
}
/// <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="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? tenant = null,
TokenAcquisitionOptions? tokenAcquisitionOptions = null)
{
if (string.IsNullOrEmpty(scope))
{
throw new ArgumentNullException(nameof(scope));
}
if (!scope.EndsWith("/.default", true, CultureInfo.InvariantCulture))
{
throw new ArgumentException(IDWebErrorMessage.ClientCredentialScopeParameterShouldEndInDotDefault, nameof(scope));
}
if (string.IsNullOrEmpty(tenant))
{
tenant = _applicationOptions.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();
string authority = CreateAuthorityBasedOnTenantIfProvided(application, tenant);
var builder = application
.AcquireTokenForClient(new string[] { scope }.Except(_scopesRequestedByMsal))
.WithSendX5C(_microsoftIdentityOptions.SendX5C)
.WithAuthority(authority);
if (tokenAcquisitionOptions != null)
{
builder.WithExtraQueryParameters(tokenAcquisitionOptions.ExtraQueryParameters);
builder.WithCorrelationId(tokenAcquisitionOptions.CorrelationId);
builder.WithForceRefresh(tokenAcquisitionOptions.ForceRefresh);
builder.WithClaims(tokenAcquisitionOptions.Claims);
if (tokenAcquisitionOptions.PoPConfiguration != null)
{
builder.WithProofOfPossession(tokenAcquisitionOptions.PoPConfiguration);
}
}
try
{
return builder.ExecuteAsync();
}
catch (MsalServiceException exMsal) when (IsInvalidClientCertificateError(exMsal))
{
DefaultCertificateLoader.ResetCertificates(_microsoftIdentityOptions.ClientCertificates);
_application = null;
// Retry
retryClientCertificate = true;
return GetAuthenticationResultForAppAsync(scope, tenant, 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="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? tenant = null,
TokenAcquisitionOptions? tokenAcquisitionOptions = null)
{
AuthenticationResult authResult = await GetAuthenticationResultForAppAsync(scope, 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 <see cref="HttpContext.User"/>
/// instance of the current HttpContext.
/// </summary>
/// <param name="scopes">Scopes to request for the downstream API to call.</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). 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? tenantId = null,
string? userFlow = null,
ClaimsPrincipal? user = null,
TokenAcquisitionOptions? tokenAcquisitionOptions = null)
{
AuthenticationResult result =
await GetAuthenticationResultForUserAsync(
scopes,
tenantId,
userFlow,
user,
tokenAcquisitionOptions).ConfigureAwait(false);
return result.AccessToken;
}
/// <summary>
/// Used in web APIs (no user interaction).
/// Replies to the client through the HTTP response by sending a 403 (forbidden) and populating the 'WWW-Authenticate' header so that
/// the client, in turn, can trigger a user interaction so that the user consents to more scopes.
/// </summary>
/// <param name="scopes">Scopes to consent to.</param>
/// <param name="msalServiceException">The <see cref="MsalUiRequiredException"/> that triggered the challenge.</param>
/// <param name="httpResponse">The <see cref="HttpResponse"/> to update.</param>
public Task ReplyForbiddenWithWwwAuthenticateHeaderAsync(
IEnumerable<string> scopes,
MsalUiRequiredException msalServiceException,
HttpResponse? httpResponse = null)
{
ReplyForbiddenWithWwwAuthenticateHeader(scopes, msalServiceException, httpResponse);
return Task.CompletedTask;
}
/// <summary>
/// Used in web APIs (no user interaction).
/// Replies to the client through the HTTP response by sending a 403 (forbidden) and populating the 'WWW-Authenticate' header so that
/// the client, in turn, can trigger a user interaction so that the user consents to more scopes.
/// </summary>
/// <param name="scopes">Scopes to consent to.</param>
/// <param name="msalServiceException">The <see cref="MsalUiRequiredException"/> that triggered the challenge.</param>
/// <param name="httpResponse">The <see cref="HttpResponse"/> to update.</param>
public void ReplyForbiddenWithWwwAuthenticateHeader(
IEnumerable<string> scopes,
MsalUiRequiredException msalServiceException,
HttpResponse? httpResponse = null)
{
// A user interaction is required, but we are in a web API, and therefore, we need to report back to the client through a 'WWW-Authenticate' header https://tools.ietf.org/html/rfc6750#section-3.1
string proposedAction = Constants.Consent;
if (msalServiceException.ErrorCode == MsalError.InvalidGrantError && AcceptedTokenVersionMismatch(msalServiceException))
{
throw msalServiceException;
}
var application = GetOrBuildConfidentialClientApplication();
string consentUrl = $"{application.Authority}/oauth2/v2.0/authorize?client_id={_applicationOptions.ClientId}"
+ $"&response_type=code&redirect_uri={application.AppConfig.RedirectUri}"
+ $"&response_mode=query&scope=offline_access%20{string.Join("%20", scopes)}";
IDictionary<string, string> parameters = new Dictionary<string, string>()
{
{ Constants.ConsentUrl, consentUrl },
{ Constants.Claims, msalServiceException.Claims },
{ Constants.Scopes, string.Join(",", scopes) },
{ Constants.ProposedAction, proposedAction },
};
string parameterString = string.Join(", ", parameters.Select(p => $"{p.Key}=\"{p.Value}\""));
httpResponse ??= CurrentHttpContext?.Response;
if (httpResponse == null)
{
throw new InvalidOperationException(IDWebErrorMessage.HttpContextAndHttpResponseAreNull);
}
var headers = httpResponse.Headers;
httpResponse.StatusCode = (int)HttpStatusCode.Forbidden;
headers[HeaderNames.WWWAuthenticate] = new StringValues($"{Constants.Bearer} {parameterString}");
}
/// <summary>
/// Removes the account associated with context.HttpContext.User from the MSAL.NET cache.
/// </summary>
/// <param name="context">RedirectContext passed-in to a <see cref="OpenIdConnectEvents.OnRedirectToIdentityProviderForSignOut"/>
/// OpenID Connect event.</param>
/// <returns>A <see cref="Task"/> that represents a completed account removal operation.</returns>
public async Task RemoveAccountAsync(RedirectContext context)
{
ClaimsPrincipal user = context.HttpContext.User;
string? userId = user.GetMsalAccountId();
if (!string.IsNullOrEmpty(userId))
{
IConfidentialClientApplication app = GetOrBuildConfidentialClientApplication();
if (_microsoftIdentityOptions.IsB2C)
{
await _tokenCacheProvider.ClearAsync(userId).ConfigureAwait(false);
}
else
{
string? identifier = context.HttpContext.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 IsInvalidClientCertificateError(MsalServiceException exMsal)
{
return !retryClientCertificate && exMsal.ErrorCode == Constants.InvalidClient && exMsal.Message.Contains(Constants.InvalidKeyError);
}
private string BuildCurrentUriFromRequest(HttpContext httpContext, HttpRequest request)
{
// need to lock to avoid threading issues with code outside of this library
// https://docs.microsoft.com/en-us/aspnet/core/performance/performance-best-practices?#do-not-access-httpcontext-from-multiple-threads
lock (httpContext)
{
return UriHelper.BuildAbsolute(
request.Scheme,
request.Host,
request.PathBase,
_microsoftIdentityOptions.CallbackPath.Value ?? string.Empty);
}
}
internal /* for testing */ IConfidentialClientApplication GetOrBuildConfidentialClientApplication()
{
if (_application == null)
{
lock (_applicationSyncObj)
{
if (_application == null)
{
_application = BuildConfidentialClientApplication();
}
}
}
return _application;
}
/// <summary>
/// Creates an MSAL confidential client application.
/// </summary>
private IConfidentialClientApplication BuildConfidentialClientApplication()
{
var httpContext = CurrentHttpContext;
var request = httpContext?.Request;
string? currentUri = null;
if (!string.IsNullOrEmpty(_applicationOptions.RedirectUri))
{
currentUri = _applicationOptions.RedirectUri;
}
if (request != null && string.IsNullOrEmpty(currentUri))
{
currentUri = BuildCurrentUriFromRequest(httpContext!, request);
}
PrepareAuthorityInstanceForMsal();
MicrosoftIdentityOptionsValidation.ValidateEitherClientCertificateOrClientSecret(
_applicationOptions.ClientSecret,
_microsoftIdentityOptions.ClientCertificates);
try
{
var builder = ConfidentialClientApplicationBuilder
.CreateWithApplicationOptions(_applicationOptions)
.WithHttpClientFactory(_httpClientFactory)
.WithLogging(
Log,
ConvertMicrosoftExtensionsLogLevelToMsal(_logger),
enablePiiLogging: _applicationOptions.EnablePiiLogging)
.WithExperimentalFeatures();
// The redirect URI is not needed for OBO
if (!string.IsNullOrEmpty(currentUri))
{
builder.WithRedirectUri(currentUri);
}
string authority;
if (_microsoftIdentityOptions.IsB2C)
{
authority = $"{_applicationOptions.Instance}{ClaimConstants.Tfp}/{_microsoftIdentityOptions.Domain}/{_microsoftIdentityOptions.DefaultUserFlow}";
builder.WithB2CAuthority(authority);
}
else
{
authority = $"{_applicationOptions.Instance}{_applicationOptions.TenantId}/";
builder.WithAuthority(authority);
}
if (_microsoftIdentityOptions.ClientCertificates != null)
{
X509Certificate2? certificate = DefaultCertificateLoader.LoadFirstCertificate(_microsoftIdentityOptions.ClientCertificates);
if (certificate == null)
{
Logger.TokenAcquisitionError(
_logger,
IDWebErrorMessage.ClientCertificatesHaveExpiredOrCannotBeLoaded,
null);
throw new ArgumentException(
IDWebErrorMessage.ClientCertificatesHaveExpiredOrCannotBeLoaded,
nameof(_microsoftIdentityOptions.ClientCertificates));
}
builder.WithCertificate(certificate);
}
IConfidentialClientApplication app = builder.Build();
_application = app;
// Initialize token cache providers
_tokenCacheProvider.Initialize(app.AppTokenCache);
_tokenCacheProvider.Initialize(app.UserTokenCache);
return app;
}
catch (Exception ex)
{
Logger.TokenAcquisitionError(
_logger,
IDWebErrorMessage.ExceptionAcquiringTokenForConfidentialClient,
ex);
throw;
}
}
private void PrepareAuthorityInstanceForMsal()
{
if (_microsoftIdentityOptions.IsB2C && _applicationOptions.Instance.EndsWith("/tfp/"))
{
_applicationOptions.Instance = _applicationOptions.Instance.Replace("/tfp/", string.Empty).TrimEnd('/') + "/";
}
else
{
_applicationOptions.Instance = _applicationOptions.Instance.TrimEnd('/') + "/";
}
}
private async Task<AuthenticationResult?> GetAuthenticationResultForWebApiToCallDownstreamApiAsync(
IConfidentialClientApplication application,
string authority,
IEnumerable<string> scopes,
TokenAcquisitionOptions? tokenAcquisitionOptions)
{
try
{
// In web API, validatedToken will not be null
JwtSecurityToken? validatedToken = CurrentHttpContext?.GetTokenUsedToCallWebAPI();
// Case of web APIs: we need to do an on-behalf-of flow, with the token used to call the API
if (validatedToken != null)
{
// In the case the token is a JWE (encrypted token), we use the decrypted token.
string tokenUsedToCallTheWebApi = validatedToken.InnerToken == null ? validatedToken.RawData
: validatedToken.InnerToken.RawData;
var builder = application
.AcquireTokenOnBehalfOf(
scopes.Except(_scopesRequestedByMsal),
new UserAssertion(tokenUsedToCallTheWebApi))
.WithSendX5C(_microsoftIdentityOptions.SendX5C)
.WithAuthority(authority);
if (tokenAcquisitionOptions != null)
{
builder.WithExtraQueryParameters(tokenAcquisitionOptions.ExtraQueryParameters);
builder.WithCorrelationId(tokenAcquisitionOptions.CorrelationId);
builder.WithForceRefresh(tokenAcquisitionOptions.ForceRefresh);
builder.WithClaims(tokenAcquisitionOptions.Claims);
if (tokenAcquisitionOptions.PoPConfiguration != null)
{
builder.WithProofOfPossession(tokenAcquisitionOptions.PoPConfiguration);
}
}
return await builder.ExecuteAsync()
.ConfigureAwait(false);
}
return null;
}
catch (MsalUiRequiredException ex)
{
Logger.TokenAcquisitionError(
_logger,
LogMessages.ErrorAcquiringTokenForDownstreamWebApi + ex.Message,
ex);
throw;
}
}
/// <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="authority">(optional) Authority 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="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? authority,
string? userFlow = null,
TokenAcquisitionOptions? tokenAcquisitionOptions = null)
{
IAccount? account = null;
if (_microsoftIdentityOptions.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,
authority,
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="authority">Authority based on a specific tenant for which to acquire a token to access the scopes
/// on behalf of the user.</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? authority,
string? userFlow = null,
TokenAcquisitionOptions? tokenAcquisitionOptions = null)
{
if (scopes == null)
{
throw new ArgumentNullException(nameof(scopes));
}
var builder = application
.AcquireTokenSilent(scopes.Except(_scopesRequestedByMsal), account)
.WithSendX5C(_microsoftIdentityOptions.SendX5C);
if (tokenAcquisitionOptions != null)
{
builder.WithExtraQueryParameters(tokenAcquisitionOptions.ExtraQueryParameters);
builder.WithCorrelationId(tokenAcquisitionOptions.CorrelationId);
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 (_microsoftIdentityOptions.IsB2C)
{
string b2cAuthority = application.Authority.Replace(
new Uri(application.Authority).PathAndQuery,
$"/{ClaimConstants.Tfp}/{_microsoftIdentityOptions.Domain}/{userFlow ?? _microsoftIdentityOptions.DefaultUserFlow}");
builder.WithB2CAuthority(b2cAuthority)
.WithSendX5C(_microsoftIdentityOptions.SendX5C);
}
else
{
builder.WithAuthority(authority);
}
return builder.ExecuteAsync();
}
private 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,
StringComparison.InvariantCulture);
}
private ClaimsPrincipal? GetUserFromHttpContext()
{
var httpContext = CurrentHttpContext;
if (httpContext != null)
{
// Need to lock due to https://docs.microsoft.com/en-us/aspnet/core/performance/performance-best-practices?#do-not-access-httpcontext-from-multiple-threads
lock (httpContext)
{
return httpContext.User;
}
}
return null;
}
private async Task<ClaimsPrincipal?> GetAuthenticatedUserAsync(ClaimsPrincipal? user)
{
if (user == null)
{
user = GetUserFromHttpContext();
}
if (user == null)
{
try
{
AuthenticationStateProvider? authenticationStateProvider =
_serviceProvider.GetService(typeof(AuthenticationStateProvider))
as AuthenticationStateProvider;
if (authenticationStateProvider != null)
{
// AuthenticationState provider is only available in Blazor
AuthenticationState state = await authenticationStateProvider.GetAuthenticationStateAsync().ConfigureAwait(false);
user = state.User;
}
}
catch
{
// do nothing.
}
}
return user;
}
internal /*for tests*/ string CreateAuthorityBasedOnTenantIfProvided(
IConfidentialClientApplication application,
string? tenant)
{
string authority;
if (!string.IsNullOrEmpty(tenant))
{
authority = application.Authority.Replace(new Uri(application.Authority).PathAndQuery, $"/{tenant}/");
}
else
{
authority = application.Authority;
}
return authority;
}
private void Log(
Client.LogLevel level,
string message,
bool containsPii)
{
switch (level)
{
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;
default:
break;
}
}
private Client.LogLevel? ConvertMicrosoftExtensionsLogLevelToMsal(ILogger logger)
{
if (logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Information))
{
return Client.LogLevel.Info;
}
else if (logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)
|| logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Trace))
{
return Client.LogLevel.Verbose;
}
else if (logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Warning))
{
return Client.LogLevel.Warning;
}
else if (logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Error)
|| logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Critical))
{
return Client.LogLevel.Error;
}
else
{
return null;
}
}
}
}