-
Notifications
You must be signed in to change notification settings - Fork 219
/
Copy pathTokenAcquisition.cs
595 lines (535 loc) · 29.4 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
// 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.OpenIdConnect;
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 class TokenAcquisition : ITokenAcquisition, ITokenAcquisitionInternal
{
private readonly MicrosoftIdentityOptions _microsoftIdentityOptions;
private readonly ConfidentialClientApplicationOptions _applicationOptions;
private readonly IMsalTokenCacheProvider _tokenCacheProvider;
private IConfidentialClientApplication _application;
private readonly IHttpContextAccessor _httpContextAccessor;
private HttpContext CurrentHttpContext => _httpContextAccessor.HttpContext;
private IMsalHttpClientFactory _httpClientFactory;
private readonly ILogger _logger;
/// <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>
public TokenAcquisition(
IMsalTokenCacheProvider tokenCacheProvider,
IHttpContextAccessor httpContextAccessor,
IOptions<MicrosoftIdentityOptions> microsoftIdentityOptions,
IOptions<ConfidentialClientApplicationOptions> applicationOptions,
IHttpClientFactory httpClientFactory,
ILogger<TokenAcquisition> logger)
{
_httpContextAccessor = httpContextAccessor;
_microsoftIdentityOptions = microsoftIdentityOptions.Value;
_applicationOptions = applicationOptions.Value;
_tokenCacheProvider = tokenCacheProvider;
_httpClientFactory = new MsalAspNetCoreHttpClientFactory(httpClientFactory);
_logger = logger;
}
/// <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>
/// 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 grant 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
{
// As AcquireTokenByAuthorizationCodeAsync is asynchronous we want to tell ASP.NET core that we are handing the code
// even if it's not done yet, so that it does not concurrently call the Token endpoint. (otherwise there will be a
// race condition ending-up in an error from Azure AD telling "code already redeemed")
context.HandleCodeRedemption();
// The cache will need the claims from the ID token.
// If they are not yet in the HttpContext.User's claims, add them here.
if (!context.HttpContext.User.Claims.Any())
{
(context.HttpContext.User.Identity as ClaimsIdentity).AddClaims(context.Principal.Claims);
}
_application = await GetOrBuildConfidentialClientApplicationAsync().ConfigureAwait(false);
// 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 result = await _application
.AcquireTokenByAuthorizationCode(scopes.Except(_scopesRequestedByMsal), context.ProtocolMessage.Code)
.WithSendX5C(_microsoftIdentityOptions.SendX5C)
.ExecuteAsync()
.ConfigureAwait(false);
context.HandleCodeRedemption(null, result.IdToken);
}
catch (MsalException ex)
{
_logger.LogInformation(
ex,
string.Format(
CultureInfo.InvariantCulture,
"Exception occurred while adding an account to the cache from the auth code. "));
throw;
}
}
/// <summary>
/// Typically used from a Web App or WebAPI 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 are 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="tenant">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 in.</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>
[Obsolete("This method has been deprecated, please use the GetAccessTokenForUserAsync() method instead.")]
public async Task<string> GetAccessTokenOnBehalfOfUserAsync(
IEnumerable<string> scopes,
string tenant = null)
{
return await GetAccessTokenForUserAsync(scopes, tenant).ConfigureAwait(false);
}
/// <summary>
/// Typically used from a Web App or WebAPI 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 are 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="tenant">Enables overriding of the tenant/account for the same identity. This is useful in the
/// cases where a given account is guest in other tenants, and you want to acquire tokens for a specific tenant, like where the user is a guest in.</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 tenant = null)
{
if (scopes == null)
{
throw new ArgumentNullException(nameof(scopes));
}
// Use MSAL to get the right token to call the API
_application = await GetOrBuildConfidentialClientApplicationAsync().ConfigureAwait(false);
string accessToken;
try
{
accessToken = await GetAccessTokenOnBehalfOfUserFromCacheAsync(_application, CurrentHttpContext.User, scopes, tenant)
.ConfigureAwait(false);
}
catch (MsalUiRequiredException ex)
{
// GetAccessTokenForUserAsync is an abstraction that can be called from a Web App or a Web API
_logger.LogInformation(ex.Message);
// to get a token for a Web API on behalf of the user, but not necessarily with the on behalf of OAuth2.0
// flow as this one only applies to Web APIs.
JwtSecurityToken validatedToken = CurrentHttpContext.GetTokenUsedToCallWebAPI();
// Case of Web APIs: we need to do an on-behalf-of flow
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 result = await _application
.AcquireTokenOnBehalfOf(scopes.Except(_scopesRequestedByMsal), new UserAssertion(tokenUsedToCallTheWebApi))
.WithSendX5C(_microsoftIdentityOptions.SendX5C)
.ExecuteAsync()
.ConfigureAwait(false);
accessToken = result.AccessToken;
}
// 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 ...
else
{
throw;
}
}
return accessToken;
}
/// <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="scopes">scopes requested to access a protected API. For this flow (client credentials), the scopes
/// 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 overriden in the application.</param>
/// <returns>An access token for the app itself, based on its scopes.</returns>
public async Task<string> GetAccessTokenForAppAsync(IEnumerable<string> scopes)
{
if (scopes == null)
{
throw new ArgumentNullException(nameof(scopes));
}
// Use MSAL to get the right token to call the API
_application = await GetOrBuildConfidentialClientApplicationAsync().ConfigureAwait(false);
AuthenticationResult result;
result = await _application
.AcquireTokenForClient(scopes.Except(_scopesRequestedByMsal))
.WithSendX5C(_microsoftIdentityOptions.SendX5C)
.ExecuteAsync()
.ConfigureAwait(false);
return result.AccessToken;
}
/// <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></returns>
public async Task RemoveAccountAsync(RedirectContext context)
{
ClaimsPrincipal user = context.HttpContext.User;
IConfidentialClientApplication app = await GetOrBuildConfidentialClientApplicationAsync().ConfigureAwait(false);
IAccount account = null;
// For B2C, we should remove all accounts of the user regardless the user flow
if (_microsoftIdentityOptions.IsB2C)
{
var b2cAccounts = await app.GetAccountsAsync().ConfigureAwait(false);
foreach (var b2cAccount in b2cAccounts)
{
await app.RemoveAsync(b2cAccount).ConfigureAwait(false);
}
_tokenCacheProvider?.ClearAsync().ConfigureAwait(false);
}
else
{
string identifier = context.HttpContext.User.GetMsalAccountId();
account = await app.GetAccountAsync(identifier).ConfigureAwait(false);
if (account != null)
{
await app.RemoveAsync(account).ConfigureAwait(false);
_tokenCacheProvider?.ClearAsync().ConfigureAwait(false);
}
}
}
/// <summary>
/// Creates an MSAL Confidential client application if needed.
/// </summary>
/// <returns></returns>
private async Task<IConfidentialClientApplication> GetOrBuildConfidentialClientApplicationAsync()
{
if (_application == null)
{
_application = await BuildConfidentialClientApplicationAsync().ConfigureAwait(false);
}
return _application;
}
/// <summary>
/// Creates an MSAL Confidential client application.
/// </summary>
private async Task<IConfidentialClientApplication> BuildConfidentialClientApplicationAsync()
{
if (!_applicationOptions.Instance.EndsWith("/", StringComparison.InvariantCulture))
{
_applicationOptions.Instance += "/";
}
string authority;
IConfidentialClientApplication app;
MicrosoftIdentityOptionsValidation microsoftIdentityOptionsValidation = new MicrosoftIdentityOptionsValidation();
microsoftIdentityOptionsValidation.ValidateEitherClientCertificateOrClientSecret(
_applicationOptions.ClientSecret,
_microsoftIdentityOptions.ClientCertificates);
try
{
var builder = ConfidentialClientApplicationBuilder
.CreateWithApplicationOptions(_applicationOptions)
.WithRedirectUri(CreateRedirectUri())
.WithHttpClientFactory(_httpClientFactory);
if (_microsoftIdentityOptions.IsB2C)
{
authority = $"{_applicationOptions.Instance}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);
builder.WithCertificate(certificate);
}
app = builder.Build();
// Initialize token cache providers
await _tokenCacheProvider.InitializeAsync(app.AppTokenCache).ConfigureAwait(false);
await _tokenCacheProvider.InitializeAsync(app.UserTokenCache).ConfigureAwait(false);
return app;
}
catch (Exception ex)
{
_logger.LogInformation(
ex,
string.Format(
CultureInfo.InvariantCulture,
"Exception acquiring token for a confidential client. "));
throw;
}
}
/// <summary>
/// Gets an access token for a downstream API on behalf of the user described by its claimsPrincipal.
/// </summary>
/// <param name="application"></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="tenant">(optional) Specific tenant for which to acquire a token to access the scopes
/// on behalf of the user described in the claimsPrincipal.</param>
private async Task<string> GetAccessTokenOnBehalfOfUserFromCacheAsync(
IConfidentialClientApplication application,
ClaimsPrincipal claimsPrincipal,
IEnumerable<string> scopes,
string tenant)
{
// Gets MsalAccountId for AAD and B2C scenarios
string accountIdentifier = claimsPrincipal.GetMsalAccountId();
string loginHint = claimsPrincipal.GetLoginHint();
IAccount account = null;
if (accountIdentifier != null)
{
account = await application.GetAccountAsync(accountIdentifier).ConfigureAwait(false);
// Special case for guest users as the Guest oid / tenant id are not surfaced.
// B2C should not follow this logic since loginHint is not present
if (!_microsoftIdentityOptions.IsB2C && account == null)
{
if (loginHint == null)
{
throw new ArgumentNullException(nameof(loginHint));
}
var accounts = await application.GetAccountsAsync().ConfigureAwait(false);
account = accounts.FirstOrDefault(a => a.Username == loginHint);
}
}
// If it is B2C and could not get an account (most likely because there is no tid claims), try to get it by user flow
if (_microsoftIdentityOptions.IsB2C && account == null)
{
string currentUserFlow = claimsPrincipal.GetUserFlowId();
account = GetAccountByUserFlow(await application.GetAccountsAsync().ConfigureAwait(false), currentUserFlow);
}
return await GetAccessTokenOnBehalfOfUserFromCacheAsync(application, account, scopes, tenant).ConfigureAwait(false);
}
/// <summary>
/// Gets an access token for a downstream API on behalf of the user which account is passed as an argument.
/// </summary>
/// <param name="application"></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="tenant"></param>
private async Task<string> GetAccessTokenOnBehalfOfUserFromCacheAsync(
IConfidentialClientApplication application,
IAccount account,
IEnumerable<string> scopes,
string tenant)
{
if (scopes == null)
{
throw new ArgumentNullException(nameof(scopes));
}
AuthenticationResult result;
// Acquire an access token as a B2C authority
if (_microsoftIdentityOptions.IsB2C)
{
string authority = application.Authority.Replace(
new Uri(application.Authority).PathAndQuery,
$"/tfp/{_microsoftIdentityOptions.Domain}/{_microsoftIdentityOptions.DefaultUserFlow}");
result = await application
.AcquireTokenSilent(scopes.Except(_scopesRequestedByMsal), account)
.WithB2CAuthority(authority)
.WithSendX5C(_microsoftIdentityOptions.SendX5C)
.ExecuteAsync()
.ConfigureAwait(false);
return result.AccessToken;
}
else if (!string.IsNullOrWhiteSpace(tenant))
{
// Acquire an access token as another AAD authority
string authority = application.Authority.Replace(new Uri(application.Authority).PathAndQuery, $"/{tenant}/");
result = await application
.AcquireTokenSilent(scopes.Except(_scopesRequestedByMsal), account)
.WithAuthority(authority)
.WithSendX5C(_microsoftIdentityOptions.SendX5C)
.ExecuteAsync()
.ConfigureAwait(false);
return result.AccessToken;
}
else
{
result = await application
.AcquireTokenSilent(scopes.Except(_scopesRequestedByMsal), account)
.WithSendX5C(_microsoftIdentityOptions.SendX5C)
.ExecuteAsync()
.ConfigureAwait(false);
return result.AccessToken;
}
}
/// <summary>
/// Used in Web APIs (which therefore cannot have an interaction with the user).
/// Replies to the client through the HttpResponse by sending a 403 (forbidden) and populating wwwAuthenticateHeaders so that
/// the client can trigger an interaction with the user so that the user consents to more scopes.
/// </summary>
/// <param name="scopes">Scopes to consent to.</param>
/// <param name="msalServiceException"><see cref="MsalUiRequiredException"/> triggering the challenge.</param>
public void ReplyForbiddenWithWwwAuthenticateHeader(IEnumerable<string> scopes, MsalUiRequiredException msalServiceException)
{
// 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 = "consent";
if (msalServiceException.ErrorCode == MsalError.InvalidGrantError)
{
if (AcceptedTokenVersionMismatch(msalServiceException))
{
throw msalServiceException;
}
}
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>()
{
{ "consentUri", consentUrl },
{ "claims", msalServiceException.Claims },
{ "scopes", string.Join(",", scopes) },
{ "proposedAction", proposedAction },
};
string parameterString = string.Join(", ", parameters.Select(p => $"{p.Key}=\"{p.Value}\""));
string scheme = "Bearer";
StringValues v = new StringValues($"{scheme} {parameterString}");
var httpResponse = CurrentHttpContext.Response;
var headers = httpResponse.Headers;
httpResponse.StatusCode = (int)HttpStatusCode.Forbidden;
if (headers.ContainsKey(HeaderNames.WWWAuthenticate))
{
headers.Remove(HeaderNames.WWWAuthenticate);
}
headers.Add(HeaderNames.WWWAuthenticate, v);
}
private static bool AcceptedTokenVersionMismatch(MsalUiRequiredException msalSeviceException)
{
// 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 msalSeviceException.Message.Contains("AADSTS50013", StringComparison.InvariantCulture);
}
/// <summary>
/// Gets an IAccount for the current B2C user flow in the user claims.
/// </summary>
/// <param name="accounts"></param>
/// <param name="userFlow"></param>
/// <returns></returns>
private IAccount GetAccountByUserFlow(IEnumerable<IAccount> accounts, string userFlow)
{
foreach (var account in accounts)
{
string accountIdentifier = account.HomeAccountId.ObjectId.Split('.')[0];
if (accountIdentifier.EndsWith(userFlow.ToLower(CultureInfo.InvariantCulture), StringComparison.InvariantCulture))
{
return account;
}
}
return null;
}
internal /*for test only*/ string CreateRedirectUri()
{
if (Uri.TryCreate(_microsoftIdentityOptions.RedirectUri, UriKind.Absolute, out Uri uri))
{
if (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps)
{
return _microsoftIdentityOptions.RedirectUri;
}
_logger.LogInformation("MicrosoftIdentityOptions RedirectUri value must have a Uri Scheme " +
"of http or https in order to be a valid RedirectUri. ");
}
var request = CurrentHttpContext.Request;
return UriHelper.BuildAbsolute(
request.Scheme,
request.Host,
request.PathBase,
_microsoftIdentityOptions.CallbackPath.Value ?? string.Empty);
}
}
}