-
Notifications
You must be signed in to change notification settings - Fork 411
Expand file tree
/
Copy pathRequestBase.cs
More file actions
603 lines (509 loc) · 28.2 KB
/
Copy pathRequestBase.cs
File metadata and controls
603 lines (509 loc) · 28.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Client.ApiConfig.Parameters;
using Microsoft.Identity.Client.Cache;
using Microsoft.Identity.Client.Cache.Items;
using Microsoft.Identity.Client.Core;
using Microsoft.Identity.Client.Instance.Discovery;
using Microsoft.Identity.Client.OAuth2;
using Microsoft.Identity.Client.TelemetryCore.Internal.Events;
using Microsoft.Identity.Client.Utils;
using Microsoft.Identity.Client.TelemetryCore;
using Microsoft.IdentityModel.Abstractions;
using Microsoft.Identity.Client.TelemetryCore.TelemetryClient;
using Microsoft.Identity.Client.TelemetryCore.OpenTelemetry;
using Microsoft.Identity.Client.Internal.Broker;
using System.Runtime.ConstrainedExecution;
using Microsoft.Identity.Client.AuthScheme;
namespace Microsoft.Identity.Client.Internal.Requests
{
/// <summary>
/// Base class for all flows. Use by implementing <see cref="ExecuteAsync(CancellationToken)"/>
/// and optionally calling protected helper methods such as SendTokenRequestAsync, which know
/// how to use all params when making the request.
/// </summary>
internal abstract class RequestBase
{
internal AuthenticationRequestParameters AuthenticationRequestParameters { get; }
internal ICacheSessionManager CacheManager => AuthenticationRequestParameters.CacheSessionManager;
internal IServiceBundle ServiceBundle { get; }
protected RequestBase(
IServiceBundle serviceBundle,
AuthenticationRequestParameters authenticationRequestParameters,
IAcquireTokenParameters acquireTokenParameters)
{
ServiceBundle = serviceBundle ??
throw new ArgumentNullException(nameof(serviceBundle));
AuthenticationRequestParameters = authenticationRequestParameters ??
throw new ArgumentNullException(nameof(authenticationRequestParameters));
if (acquireTokenParameters == null)
{
throw new ArgumentNullException(nameof(acquireTokenParameters));
}
acquireTokenParameters.LogParameters(AuthenticationRequestParameters.RequestContext.Logger);
}
/// <summary>
/// Return a custom set of scopes to override the default MSAL logic of merging
/// input scopes with reserved scopes (openid, profile etc.)
/// Leave as is / return null otherwise
/// </summary>
protected virtual SortedSet<string> GetOverriddenScopes(ISet<string> inputScopes)
{
return null;
}
protected abstract Task<AuthenticationResult> ExecuteAsync(CancellationToken cancellationToken);
public async Task<AuthenticationResult> RunAsync(CancellationToken cancellationToken = default)
{
ApiEvent apiEvent = null;
var measureTelemetryDurationResult = StopwatchService.MeasureCodeBlock(() =>
{
apiEvent = InitializeApiEvent(AuthenticationRequestParameters.Account?.HomeAccountId?.Identifier);
AuthenticationRequestParameters.RequestContext.ApiEvent = apiEvent;
});
try
{
AuthenticationResult authenticationResult = null;
var measureDurationResult = await StopwatchService.MeasureCodeBlockAsync(async () =>
{
AuthenticationRequestParameters.LogParameters();
LogRequestStarted(AuthenticationRequestParameters);
authenticationResult = await ExecuteAsync(cancellationToken).ConfigureAwait(false);
LogReturnedToken(authenticationResult);
}).ConfigureAwait(false);
UpdateTelemetry(measureDurationResult.Milliseconds + measureTelemetryDurationResult.Milliseconds, apiEvent, authenticationResult);
LogMetricsFromAuthResult(authenticationResult, AuthenticationRequestParameters.RequestContext.Logger);
LogSuccessTelemetryToOtel(authenticationResult, apiEvent, measureDurationResult.Microseconds);
return authenticationResult;
}
catch (MsalException ex)
{
apiEvent.ApiErrorCode = ex.ErrorCode;
if (string.IsNullOrWhiteSpace(ex.CorrelationId))
{
ex.CorrelationId = AuthenticationRequestParameters.CorrelationId.ToString();
}
AuthenticationRequestParameters.RequestContext.Logger.ErrorPii(ex);
LogFailureTelemetryToOtel(ex.ErrorCode, apiEvent, apiEvent.CacheInfo);
throw;
}
catch (Exception ex)
{
apiEvent.ApiErrorCode = ex.GetType().Name;
AuthenticationRequestParameters.RequestContext.Logger.ErrorPii(ex);
LogFailureTelemetryToOtel(ex.GetType().Name, apiEvent, apiEvent.CacheInfo);
throw;
}
}
private void LogSuccessTelemetryToOtel(AuthenticationResult authenticationResult, ApiEvent apiEvent, long durationInUs)
{
CacheLevel cacheLevel = GetCacheLevel(authenticationResult);
// Log metrics
ServiceBundle.PlatformProxy.OtelInstrumentation.LogSuccessMetrics(
ServiceBundle.PlatformProxy.GetProductName(),
apiEvent.ApiId,
apiEvent.CallerSdkApiId,
apiEvent.CallerSdkVersion,
cacheLevel,
durationInUs,
authenticationResult.AuthenticationResultMetadata,
AuthenticationRequestParameters.RequestContext.Logger,
authenticationResult.ExpiresOn);
}
private void LogFailureTelemetryToOtel(string errorCodeToLog, ApiEvent apiEvent, CacheRefreshReason cacheRefreshReason)
{
// Log metrics
ServiceBundle.PlatformProxy.OtelInstrumentation.LogFailureMetrics(
ServiceBundle.PlatformProxy.GetProductName(),
errorCodeToLog,
apiEvent.ApiId,
apiEvent.CallerSdkApiId,
apiEvent.CallerSdkVersion,
cacheRefreshReason,
apiEvent.TokenType);
}
private Tuple<string, string> ParseScopesForTelemetry()
{
string resource = null;
string scopes = null;
if (AuthenticationRequestParameters.Scope.Count > 0)
{
string firstScope = AuthenticationRequestParameters.Scope.First();
if (Uri.IsWellFormedUriString(firstScope, UriKind.Absolute))
{
Uri firstScopeAsUri = new Uri(firstScope);
resource = $"{firstScopeAsUri.Scheme}://{firstScopeAsUri.Host}";
StringBuilder stringBuilder = new StringBuilder();
foreach (string scope in AuthenticationRequestParameters.Scope)
{
var splitString = scope.Split(new[] { firstScopeAsUri.Host }, StringSplitOptions.None);
string scopeToAppend = splitString.Length > 1 ? splitString[1].TrimStart('/') + " " : splitString.FirstOrDefault();
stringBuilder.Append(scopeToAppend);
}
scopes = stringBuilder.ToString().TrimEnd(' ');
}
else
{
scopes = AuthenticationRequestParameters.Scope.AsSingleString();
}
}
return new(resource, scopes);
}
private CacheLevel GetCacheLevel(AuthenticationResult authenticationResult)
{
if (authenticationResult.AuthenticationResultMetadata.TokenSource == TokenSource.Cache) //Check if token source is cache
{
if (AuthenticationRequestParameters.RequestContext.ApiEvent.CacheLevel > CacheLevel.Unknown) //Check if cache has indicated which level was used
{
return AuthenticationRequestParameters.RequestContext.ApiEvent.CacheLevel;
}
//If no level was used, set to unknown
return CacheLevel.Unknown;
}
return CacheLevel.None;
}
private static void LogMetricsFromAuthResult(AuthenticationResult authenticationResult, ILoggerAdapter logger)
{
if (logger.IsLoggingEnabled(LogLevel.Always))
{
var metadata = authenticationResult.AuthenticationResultMetadata;
logger.Always(
$"""
[LogMetricsFromAuthResult] Cache Refresh Reason: {metadata.CacheRefreshReason}
[LogMetricsFromAuthResult] DurationInCacheInMs: {metadata.DurationInCacheInMs}
[LogMetricsFromAuthResult] DurationTotalInMs: {metadata.DurationTotalInMs}
[LogMetricsFromAuthResult] DurationInHttpInMs: {metadata.DurationInHttpInMs}
""");
logger.AlwaysPii($"[LogMetricsFromAuthResult] TokenEndpoint: {metadata.TokenEndpoint ?? ""}",
"TokenEndpoint: ****");
}
}
private void UpdateTelemetry(long elapsedMilliseconds, ApiEvent apiEvent, AuthenticationResult authenticationResult)
{
authenticationResult.AuthenticationResultMetadata.DurationTotalInMs = elapsedMilliseconds;
authenticationResult.AuthenticationResultMetadata.DurationInHttpInMs = apiEvent.DurationInHttpInMs;
authenticationResult.AuthenticationResultMetadata.DurationInCacheInMs = apiEvent.DurationInCacheInMs;
authenticationResult.AuthenticationResultMetadata.TokenEndpoint = apiEvent.TokenEndpoint;
authenticationResult.AuthenticationResultMetadata.CacheRefreshReason = apiEvent.CacheInfo;
authenticationResult.AuthenticationResultMetadata.CacheLevel = GetCacheLevel(authenticationResult);
authenticationResult.AuthenticationResultMetadata.Telemetry = apiEvent.MsalRuntimeTelemetry;
authenticationResult.AuthenticationResultMetadata.RegionDetails = CreateRegionDetails(apiEvent);
authenticationResult.AuthenticationResultMetadata.CachedAccessTokenCount = apiEvent.CachedAccessTokenCount;
Metrics.IncrementTotalDurationInMs(authenticationResult.AuthenticationResultMetadata.DurationTotalInMs);
}
protected virtual void EnrichTelemetryApiEvent(ApiEvent apiEvent)
{
// In base classes have them override this to add their properties/fields to the event.
}
private ApiEvent InitializeApiEvent(string accountId)
{
ApiEvent apiEvent = new ApiEvent(AuthenticationRequestParameters.RequestContext.CorrelationId)
{
ApiId = AuthenticationRequestParameters.ApiId,
};
apiEvent.IsTokenCacheSerialized =
AuthenticationRequestParameters.CacheSessionManager.TokenCacheInternal.IsAppSubscribedToSerializationEvents();
apiEvent.IsLegacyCacheEnabled =
AuthenticationRequestParameters.RequestContext.ServiceBundle.Config.LegacyCacheCompatibilityEnabled;
apiEvent.CacheInfo = CacheRefreshReason.NotApplicable;
apiEvent.TokenType = AuthenticationRequestParameters.AuthenticationScheme.TelemetryTokenType;
apiEvent.AssertionType = GetAssertionType();
if (AuthenticationRequestParameters.ExtraQueryParameters.TryGetValue(Constants.ManagedCertKey, out string managedCertValue)
&& !string.IsNullOrEmpty(managedCertValue))
{
apiEvent.IsManagedCertUsed = managedCertValue[0];
}
AuthenticationRequestParameters.ExtraQueryParameters.Remove(Constants.ManagedCertKey);
UpdateCallerSdkDetails(apiEvent);
// Give derived classes the ability to add or modify fields in the telemetry as needed.
EnrichTelemetryApiEvent(apiEvent);
return apiEvent;
}
private void UpdateCallerSdkDetails(ApiEvent apiEvent)
{
string callerSdkId;
string callerSdkVer;
// Check if ExtraQueryParameters contains caller-sdk-id and caller-sdk-ver
if (AuthenticationRequestParameters.ExtraQueryParameters.TryGetValue(Constants.CallerSdkIdKey, out callerSdkId))
{
AuthenticationRequestParameters.ExtraQueryParameters.Remove(Constants.CallerSdkIdKey);
}
else
{
callerSdkId = AuthenticationRequestParameters.RequestContext.ServiceBundle.Config.ClientName;
}
if (AuthenticationRequestParameters.ExtraQueryParameters.TryGetValue(Constants.CallerSdkVersionKey, out callerSdkVer))
{
AuthenticationRequestParameters.ExtraQueryParameters.Remove(Constants.CallerSdkVersionKey);
}
else
{
callerSdkVer = AuthenticationRequestParameters.RequestContext.ServiceBundle.Config.ClientVersion;
}
apiEvent.CallerSdkApiId = callerSdkId == null ? null : callerSdkId.Substring(0, Math.Min(callerSdkId.Length, Constants.CallerSdkIdMaxLength));
apiEvent.CallerSdkVersion = callerSdkVer == null ? null : callerSdkVer.Substring(0, Math.Min(callerSdkVer.Length, Constants.CallerSdkVersionMaxLength));
}
private AssertionType GetAssertionType()
{
if (ServiceBundle.Config.IsManagedIdentity ||
ServiceBundle.Config.AppTokenProvider != null)
{
return AssertionType.ManagedIdentity;
}
if (ServiceBundle.Config.ClientCredential != null)
{
if (ServiceBundle.Config.ClientCredential.AssertionType == AssertionType.CertificateWithoutSni)
{
if (ServiceBundle.Config.SendX5C)
{
return AssertionType.CertificateWithSni;
}
return AssertionType.CertificateWithoutSni;
}
return ServiceBundle.Config.ClientCredential.AssertionType;
}
return AssertionType.None;
}
protected async Task<AuthenticationResult> CacheTokenResponseAndCreateAuthenticationResultAsync(MsalTokenResponse msalTokenResponse, CancellationToken cancellationToken = default)
{
// developer passed in user object.
AuthenticationRequestParameters.RequestContext.Logger.Info("Checking client info returned from the server..");
ClientInfo clientInfoFromServer = null;
if (AuthenticationRequestParameters.ApiId != ApiEvent.ApiIds.AcquireTokenForSystemAssignedManagedIdentity &&
AuthenticationRequestParameters.ApiId != ApiEvent.ApiIds.AcquireTokenForUserAssignedManagedIdentity &&
AuthenticationRequestParameters.ApiId != ApiEvent.ApiIds.AcquireTokenByRefreshToken &&
AuthenticationRequestParameters.AuthorityInfo.AuthorityType != AuthorityType.Adfs &&
!(msalTokenResponse.ClientInfo is null))
{
//client_info is not returned from managed identity flows because there is no user present.
clientInfoFromServer = ClientInfo.CreateFromJson(msalTokenResponse.ClientInfo);
ValidateAccountIdentifiers(clientInfoFromServer);
}
AuthenticationRequestParameters.RequestContext.Logger.Info("Saving token response to cache..");
var tuple = await CacheManager.SaveTokenResponseAsync(msalTokenResponse).ConfigureAwait(false);
var atItem = tuple.Item1;
var idtItem = tuple.Item2;
Account account = tuple.Item3;
#if !MOBILE
atItem?.AddAdditionalCacheParameters(clientInfoFromServer?.AdditionalResponseParameters);
#endif
return await AuthenticationResult.CreateAsync(
atItem,
idtItem,
AuthenticationRequestParameters.AuthenticationScheme,
AuthenticationRequestParameters.RequestContext.CorrelationId,
msalTokenResponse.TokenSource,
AuthenticationRequestParameters.RequestContext.ApiEvent,
account,
msalTokenResponse.SpaAuthCode,
msalTokenResponse.CreateExtensionDataStringMap(),
cancellationToken).ConfigureAwait(false);
}
protected virtual void ValidateAccountIdentifiers(ClientInfo fromServer)
{
//No Op
}
protected Task ResolveAuthorityAsync()
{
return AuthenticationRequestParameters.AuthorityManager.RunInstanceDiscoveryAndValidationAsync();
}
internal async Task<MsalTokenResponse> SendTokenRequestAsync(
IDictionary<string, string> additionalBodyParameters,
CancellationToken cancellationToken)
{
var tokenEndpoint = await AuthenticationRequestParameters.Authority.GetTokenEndpointAsync(AuthenticationRequestParameters.RequestContext).ConfigureAwait(false);
var tokenResponse = await SendTokenRequestAsync(
tokenEndpoint,
additionalBodyParameters,
cancellationToken).ConfigureAwait(false);
Metrics.IncrementTotalAccessTokensFromIdP();
return tokenResponse;
}
protected Task<MsalTokenResponse> SendTokenRequestAsync(
string tokenEndpoint,
IDictionary<string, string> additionalBodyParameters,
CancellationToken cancellationToken)
{
string scopes = GetOverriddenScopes(AuthenticationRequestParameters.Scope).AsSingleString();
var tokenClient = new TokenClient(AuthenticationRequestParameters);
var CcsHeader = GetCcsHeader(additionalBodyParameters);
if (CcsHeader != null && !string.IsNullOrEmpty(CcsHeader.Value.Key))
{
tokenClient.AddHeaderToClient(CcsHeader.Value.Key, CcsHeader.Value.Value);
}
InjectPcaSsoPolicyHeader(tokenClient);
return tokenClient.SendTokenRequestAsync(
additionalBodyParameters,
scopes,
tokenEndpoint,
cancellationToken);
}
private void InjectPcaSsoPolicyHeader(TokenClient tokenClient)
{
if (ServiceBundle.Config.IsPublicClient && ServiceBundle.Config.IsWebviewSsoPolicyEnabled)
{
IBroker broker = ServiceBundle.Config.BrokerCreatorFunc(
null,
ServiceBundle.Config,
AuthenticationRequestParameters.RequestContext.Logger);
var ssoPolicyHeaders = broker.GetSsoPolicyHeaders();
foreach (KeyValuePair<string, string> kvp in ssoPolicyHeaders)
{
tokenClient.AddHeaderToClient(kvp.Key, kvp.Value);
}
}
}
//The AAD backup authentication system header is used by the AAD backup authentication system service
//to help route requests to resources in Azure during requests to speed up authentication.
//It consists of either the ObjectId.TenantId or the upn of the account signing in.
//See https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/2525
protected virtual KeyValuePair<string, string>? GetCcsHeader(IDictionary<string, string> additionalBodyParameters)
{
if (AuthenticationRequestParameters?.Account?.HomeAccountId != null)
{
if (!String.IsNullOrEmpty(AuthenticationRequestParameters.Account.HomeAccountId.Identifier))
{
var userObjectId = AuthenticationRequestParameters.Account.HomeAccountId.ObjectId;
var userTenantID = AuthenticationRequestParameters.Account.HomeAccountId.TenantId;
string OidCcsHeader = CoreHelpers.GetCcsClientInfoHint(userObjectId, userTenantID);
return new KeyValuePair<string, string>(Constants.CcsRoutingHintHeader, OidCcsHeader);
}
if (!String.IsNullOrEmpty(AuthenticationRequestParameters.Account.Username))
{
return GetCcsUpnHeader(AuthenticationRequestParameters.Account.Username);
}
}
if (additionalBodyParameters.TryGetValue(OAuth2Parameter.Username, out string username))
{
return GetCcsUpnHeader(username);
}
if (!String.IsNullOrEmpty(AuthenticationRequestParameters.LoginHint))
{
return GetCcsUpnHeader(AuthenticationRequestParameters.LoginHint);
}
return null;
}
protected KeyValuePair<string, string>? GetCcsUpnHeader(string upnHeader)
{
if (AuthenticationRequestParameters.Authority.AuthorityInfo.AuthorityType == AuthorityType.B2C)
{
return null;
}
string OidCcsHeader = CoreHelpers.GetCcsUpnHint(upnHeader);
return new KeyValuePair<string, string>(Constants.CcsRoutingHintHeader, OidCcsHeader);
}
private void LogRequestStarted(AuthenticationRequestParameters authenticationRequestParameters)
{
if (authenticationRequestParameters.RequestContext.Logger.IsLoggingEnabled(LogLevel.Info))
{
string scopes = authenticationRequestParameters.Scope.AsSingleString();
var type = GetType().Name;
var messageWithPii = $"=== Token Acquisition ({type}) started:\n\tAuthority: {authenticationRequestParameters.AuthorityInfo?.CanonicalAuthority}\n\tScope: {scopes}\n\tClientId: {authenticationRequestParameters.AppConfig.ClientId}\n\t";
var messageWithoutPii = $"=== Token Acquisition ({type}) started:\n\t Scopes: {scopes}";
if (authenticationRequestParameters.AuthorityInfo != null &&
KnownMetadataProvider.IsKnownEnvironment(authenticationRequestParameters.AuthorityInfo?.Host))
{
messageWithoutPii += $"\n\tAuthority Host: {authenticationRequestParameters.AuthorityInfo?.Host}";
}
authenticationRequestParameters.RequestContext.Logger.InfoPii(messageWithPii, messageWithoutPii);
}
if (authenticationRequestParameters.AppConfig.IsConfidentialClient &&
!authenticationRequestParameters.IsClientCredentialRequest &&
!CacheManager.TokenCacheInternal.IsAppSubscribedToSerializationEvents())
{
authenticationRequestParameters.RequestContext.Logger.Warning(
"Only in-memory caching is used. The cache is not persisted and will be lost if the machine is restarted. It also does not scale for a web app or web API, where the number of users can grow large. In production, web apps and web APIs should use distributed caching like Redis. See https://aka.ms/msal-net-cca-token-cache-serialization");
}
}
private void LogReturnedToken(AuthenticationResult result)
{
if (result.AccessToken != null &&
AuthenticationRequestParameters.RequestContext.Logger.IsLoggingEnabled(LogLevel.Info))
{
string scopes = string.Join(" ", result.Scopes);
AuthenticationRequestParameters.RequestContext.Logger.Info("\n\t=== Token Acquisition finished successfully:");
AuthenticationRequestParameters.RequestContext.Logger.InfoPii(
() => $" AT expiration time: {result.ExpiresOn}, scopes: {scopes}. " +
$"source: {result.AuthenticationResultMetadata.TokenSource}",
() => $" AT expiration time: {result.ExpiresOn}, scopes: {scopes}. " +
$"source: {result.AuthenticationResultMetadata.TokenSource}");
if (result.AuthenticationResultMetadata.TokenSource != TokenSource.Cache)
{
Uri canonicalAuthority = AuthenticationRequestParameters.AuthorityInfo.CanonicalAuthority;
AuthenticationRequestParameters.RequestContext.Logger.InfoPii(
() => $"Fetched access token from host {canonicalAuthority.Host}. Endpoint: {canonicalAuthority}. ",
() => $"Fetched access token from host {canonicalAuthority.Host}. ");
}
}
}
internal async Task<AuthenticationResult> HandleTokenRefreshErrorAsync(
MsalServiceException e,
MsalAccessTokenCacheItem cachedAccessTokenItem,
CancellationToken cancellationToken)
{
var logger = AuthenticationRequestParameters.RequestContext.Logger;
logger.Warning($"Fetching a new AT failed. Is exception retry-able? {e.IsRetryable}. Is there an AT in the cache that is usable? {cachedAccessTokenItem != null}");
if (cachedAccessTokenItem != null && e.IsRetryable)
{
logger.Info("Returning existing access token. It is not expired, but should be refreshed. ");
var idToken = await CacheManager.GetIdTokenCacheItemAsync(cachedAccessTokenItem).ConfigureAwait(false);
var account = await CacheManager.GetAccountAssociatedWithAccessTokenAsync(cachedAccessTokenItem).ConfigureAwait(false);
return await AuthenticationResult.CreateAsync(
cachedAccessTokenItem,
idToken,
AuthenticationRequestParameters.AuthenticationScheme,
AuthenticationRequestParameters.RequestContext.CorrelationId,
TokenSource.Cache,
AuthenticationRequestParameters.RequestContext.ApiEvent,
account,
spaAuthCode: null,
additionalResponseParameters: null,
cancellationToken: cancellationToken).ConfigureAwait(false);
}
logger.Warning("Either the exception does not indicate a problem with AAD or the token cache does not have an AT that is usable. ");
throw e;
}
/// <summary>
/// Creates the region Details
/// </summary>
/// <param name="apiEvent"></param>
/// <returns></returns>
private static RegionDetails CreateRegionDetails(ApiEvent apiEvent)
{
return new RegionDetails(
apiEvent.RegionOutcome,
apiEvent.RegionUsed,
apiEvent.RegionDiscoveryFailureReason);
}
/// <summary>
/// Validates a cached access token using the authentication operation, if the scheme implements <see cref="IAuthenticationOperation2"/>.
/// Returns the original cache item if validation passes or is not applicable, or null if validation fails.
/// </summary>
internal static async Task<MsalAccessTokenCacheItem> ValidateCachedAccessTokenAsync(
AuthenticationRequestParameters authenticationRequestParameters,
MsalAccessTokenCacheItem cachedAccessTokenItem,
string requestType)
{
if (cachedAccessTokenItem != null &&
authenticationRequestParameters.AuthenticationScheme is IAuthenticationOperation2 authOp2)
{
var cacheValidationData = new MsalCacheValidationData();
cacheValidationData.PersistedCacheParameters = cachedAccessTokenItem.PersistedCacheParameters;
if (!await authOp2.ValidateCachedTokenAsync(cacheValidationData).ConfigureAwait(false))
{
authenticationRequestParameters.RequestContext.Logger.Info(
$"[{requestType}] Cached token failed authentication operation validation.");
return null;
}
}
return cachedAccessTokenItem;
}
}
}