-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathPlatformAuthInteractionClient.ts
More file actions
1210 lines (1109 loc) · 41.2 KB
/
PlatformAuthInteractionClient.ts
File metadata and controls
1210 lines (1109 loc) · 41.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
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.
*/
import {
AADServerParamKeys,
AccessTokenEntity,
AccountEntity,
AccountEntityUtils,
AccountInfo,
AuthError,
AuthToken,
AuthorityType,
CacheHelpers,
ClientAuthErrorCodes,
CommonSilentFlowRequest,
Constants,
ICrypto,
IPerformanceClient,
IdTokenEntity,
InProgressPerformanceEvent,
Logger,
PerformanceEvents,
PopTokenGenerator,
RequestParameterBuilder,
ScopeSet,
ServerTelemetryManager,
SignedHttpRequestParameters,
TimeUtils,
TokenClaims,
UrlString,
buildAccountToCache,
createClientAuthError,
invokeAsync,
updateAccountTenantProfileData,
} from "@azure/msal-common/browser";
import { IPlatformAuthHandler } from "../broker/nativeBroker/IPlatformAuthHandler.js";
import { PlatformAuthRequest } from "../broker/nativeBroker/PlatformAuthRequest.js";
import {
MATS,
PlatformAuthResponse,
} from "../broker/nativeBroker/PlatformAuthResponse.js";
import { BrowserCacheManager } from "../cache/BrowserCacheManager.js";
import { BrowserConfiguration } from "../config/Configuration.js";
import { base64Decode } from "../encode/Base64Decode.js";
import {
BrowserAuthErrorCodes,
createBrowserAuthError,
} from "../error/BrowserAuthError.js";
import {
NativeAuthError,
NativeAuthErrorCodes,
createNativeAuthError,
isFatalNativeAuthError,
} from "../error/NativeAuthError.js";
import { EventHandler } from "../event/EventHandler.js";
import { INavigationClient } from "../navigation/INavigationClient.js";
import { NavigationOptions } from "../navigation/NavigationOptions.js";
import { version } from "../packageMetadata.js";
import { HandleRedirectPromiseOptions } from "../request/HandleRedirectPromiseOptions.js";
import { PopupRequest } from "../request/PopupRequest.js";
import { RedirectRequest } from "../request/RedirectRequest.js";
import { SilentRequest } from "../request/SilentRequest.js";
import { SsoSilentRequest } from "../request/SsoSilentRequest.js";
import { AuthenticationResult } from "../response/AuthenticationResult.js";
import * as BrowserPerformanceEvents from "../telemetry/BrowserPerformanceEvents.js";
import {
ApiId,
BrowserConstants,
CacheLookupPolicy,
PlatformAuthConstants,
TemporaryCacheKeys,
} from "../utils/BrowserConstants.js";
import { getCurrentUri } from "../utils/BrowserUtils.js";
import {
BaseInteractionClient,
getDiscoveredAuthority,
getRedirectUri,
initializeServerTelemetryManager,
} from "./BaseInteractionClient.js";
import { SilentCacheClient } from "./SilentCacheClient.js";
export class PlatformAuthInteractionClient extends BaseInteractionClient {
protected apiId: ApiId;
protected accountId: string;
protected platformAuthProvider: IPlatformAuthHandler;
protected silentCacheClient: SilentCacheClient;
protected nativeStorageManager: BrowserCacheManager;
protected skus: string;
constructor(
config: BrowserConfiguration,
browserStorage: BrowserCacheManager,
browserCrypto: ICrypto,
logger: Logger,
eventHandler: EventHandler,
navigationClient: INavigationClient,
apiId: ApiId,
performanceClient: IPerformanceClient,
provider: IPlatformAuthHandler,
accountId: string,
nativeStorageImpl: BrowserCacheManager,
correlationId: string
) {
super(
config,
browserStorage,
browserCrypto,
logger,
eventHandler,
navigationClient,
performanceClient,
correlationId,
provider
);
this.apiId = apiId;
this.accountId = accountId;
this.platformAuthProvider = provider;
this.nativeStorageManager = nativeStorageImpl;
this.silentCacheClient = new SilentCacheClient(
config,
this.nativeStorageManager,
browserCrypto,
logger,
eventHandler,
navigationClient,
performanceClient,
correlationId,
provider
);
const extensionName = this.platformAuthProvider.getExtensionName();
this.skus = ServerTelemetryManager.makeExtraSkuString({
libraryName: BrowserConstants.MSAL_SKU,
libraryVersion: version,
extensionName: extensionName,
extensionVersion: this.platformAuthProvider.getExtensionVersion(),
});
}
/**
* Adds SKUs to request extra query parameters
* @param request {PlatformAuthRequest}
* @private
*/
private addRequestSKUs(request: PlatformAuthRequest): void {
request.extraParameters = {
...request.extraParameters,
[AADServerParamKeys.X_CLIENT_EXTRA_SKU]: this.skus,
};
}
/**
* Acquire token from native platform via browser extension
* @param request
*/
async acquireToken(
request: PopupRequest | SilentRequest | SsoSilentRequest,
cacheLookupPolicy?: CacheLookupPolicy
): Promise<AuthenticationResult> {
this.logger.trace(
"NativeInteractionClient - acquireToken called.",
this.correlationId
);
// start the perf measurement
const nativeATMeasurement = this.performanceClient.startMeasurement(
BrowserPerformanceEvents.NativeInteractionClientAcquireToken,
this.correlationId
);
const reqTimestamp = TimeUtils.nowSeconds();
const serverTelemetryManager = initializeServerTelemetryManager(
this.apiId,
this.config.auth.clientId,
this.correlationId,
this.browserStorage,
this.logger,
undefined,
this.config.system.serverTelemetryEnabled
);
try {
// initialize native request
const nativeRequest = await this.initializePlatformRequest(request);
// check if the tokens can be retrieved from internal cache
try {
const result = await this.acquireTokensFromCache(
this.accountId,
nativeRequest
);
nativeATMeasurement.end({
success: true,
isNativeBroker: false, // Should be true only when the result is coming directly from the broker
fromCache: true,
});
return result;
} catch (e) {
if (cacheLookupPolicy === CacheLookupPolicy.AccessToken) {
this.logger.info(
"MSAL internal Cache does not contain tokens, return error as per cache policy",
this.correlationId
);
nativeATMeasurement.end({
success: false,
brokerErrorCode: "cache_request_failed",
});
throw e;
}
// continue with a native call for any and all errors
this.logger.info(
"MSAL internal Cache does not contain tokens, proceed to make a native call",
this.correlationId
);
}
const validatedResponse: PlatformAuthResponse =
await this.platformAuthProvider.sendMessage(nativeRequest);
return await this.handleNativeResponse(
validatedResponse,
nativeRequest,
reqTimestamp
)
.then((result: AuthenticationResult) => {
nativeATMeasurement.end({
success: true,
isNativeBroker: true,
requestId: result.requestId,
});
serverTelemetryManager.clearNativeBrokerErrorCode();
return result;
})
.catch((error: AuthError) => {
nativeATMeasurement.end({
success: false,
errorCode: error.errorCode,
subErrorCode: error.subError,
});
throw error;
});
} catch (e) {
if (e instanceof NativeAuthError) {
serverTelemetryManager.setNativeBrokerErrorCode(e.errorCode);
}
nativeATMeasurement.end({
success: false,
});
throw e;
}
}
/**
* Creates silent flow request
* @param request
* @param cachedAccount
* @returns CommonSilentFlowRequest
*/
private createSilentCacheRequest(
request: PlatformAuthRequest,
cachedAccount: AccountInfo
): CommonSilentFlowRequest {
return {
authority: request.authority,
correlationId: this.correlationId,
scopes: ScopeSet.fromString(request.scope).asArray(),
account: cachedAccount,
forceRefresh: false,
};
}
/**
* Fetches the tokens from the cache if un-expired
* @param nativeAccountId
* @param request
* @returns authenticationResult
*/
protected async acquireTokensFromCache(
nativeAccountId: string,
request: PlatformAuthRequest
): Promise<AuthenticationResult> {
if (!nativeAccountId) {
this.logger.warning(
"NativeInteractionClient:acquireTokensFromCache - No nativeAccountId provided",
this.correlationId
);
throw createClientAuthError(ClientAuthErrorCodes.noAccountFound);
}
// fetch the account from browser cache
const account = this.browserStorage.getBaseAccountInfo(
{
nativeAccountId,
},
this.correlationId
);
if (!account) {
throw createClientAuthError(ClientAuthErrorCodes.noAccountFound);
}
// leverage silent flow for cached tokens retrieval
try {
const silentRequest = this.createSilentCacheRequest(
request,
account
);
const result = await this.silentCacheClient.acquireToken(
silentRequest
);
const idToken = this.browserStorage.getIdToken(
account,
this.correlationId,
this.browserStorage.getTokenKeys(),
account.tenantId
);
const idTokenClaims = AuthToken.extractTokenClaims(
idToken?.secret || "",
base64Decode
);
const fullAccount = updateAccountTenantProfileData(
account,
undefined, // tenantProfile optional
idTokenClaims,
idToken?.secret
);
return {
...result,
idToken: idToken?.secret || "",
idTokenClaims: idTokenClaims as TokenClaims,
account: fullAccount,
};
} catch (e) {
throw e;
}
}
/**
* Acquires a token from native platform then redirects to the redirectUri instead of returning the response
* @param {RedirectRequest} request
* @param {InProgressPerformanceEvent} rootMeasurement
* @param {HandleRedirectPromiseOptions} options
*/
async acquireTokenRedirect(
request: RedirectRequest,
rootMeasurement: InProgressPerformanceEvent,
options?: HandleRedirectPromiseOptions
): Promise<void> {
this.logger.trace(
"NativeInteractionClient - acquireTokenRedirect called.",
this.correlationId
);
const nativeRequest = await this.initializePlatformRequest(request);
const navigateToLoginRequestUrl =
options?.navigateToLoginRequestUrl ?? true;
try {
await this.platformAuthProvider.sendMessage(nativeRequest);
} catch (e) {
// Only throw fatal errors here to allow application to fallback to regular redirect. Otherwise proceed and the error will be thrown in handleRedirectPromise
if (e instanceof NativeAuthError) {
const serverTelemetryManager = initializeServerTelemetryManager(
this.apiId,
this.config.auth.clientId,
this.correlationId,
this.browserStorage,
this.logger,
undefined,
this.config.system.serverTelemetryEnabled
);
serverTelemetryManager.setNativeBrokerErrorCode(e.errorCode);
if (isFatalNativeAuthError(e)) {
throw e;
}
}
}
this.browserStorage.setTemporaryCache(
TemporaryCacheKeys.NATIVE_REQUEST,
JSON.stringify(nativeRequest),
true
);
const navigationOptions: NavigationOptions = {
apiId: ApiId.acquireTokenRedirect,
timeout: this.config.system.redirectNavigationTimeout,
noHistory: false,
};
const redirectUri = navigateToLoginRequestUrl
? UrlString.getAbsoluteUrl(
request.redirectStartPage || window.location.href,
getCurrentUri()
)
: getRedirectUri(
request.redirectUri,
this.config.auth.redirectUri,
this.logger,
this.correlationId
);
rootMeasurement.end({ success: true });
await this.navigationClient.navigateExternal(
redirectUri,
navigationOptions
); // Need to treat this as external to ensure handleRedirectPromise is run again
}
/**
* If the previous page called native platform for a token using redirect APIs, send the same request again and return the response
* @param performanceClient {IPerformanceClient?}
* @param correlationId {string?} correlation identifier
*/
async handleRedirectPromise(): Promise<AuthenticationResult | null> {
this.logger.trace(
"NativeInteractionClient - handleRedirectPromise called.",
this.correlationId
);
if (!this.browserStorage.isInteractionInProgress(true)) {
this.logger.info(
"handleRedirectPromise called but there is no interaction in progress, returning null.",
this.correlationId
);
return null;
}
// remove prompt from the request to prevent WAM from prompting twice
const cachedRequest = this.browserStorage.getCachedNativeRequest();
if (!cachedRequest) {
this.logger.verbose(
"NativeInteractionClient - handleRedirectPromise called but there is no cached request, returning null.",
this.correlationId
);
this.performanceClient?.addFields(
{ errorCode: "no_cached_request" },
this.correlationId
);
return null;
}
const { prompt, ...request } = cachedRequest;
if (prompt) {
this.logger.verbose(
"NativeInteractionClient - handleRedirectPromise called and prompt was included in the original request, removing prompt from cached request to prevent second interaction with native broker window.",
this.correlationId
);
}
this.browserStorage.removeItem(
this.browserStorage.generateCacheKey(
TemporaryCacheKeys.NATIVE_REQUEST
)
);
const reqTimestamp = TimeUtils.nowSeconds();
try {
this.logger.verbose(
"NativeInteractionClient - handleRedirectPromise sending message to native broker.",
this.correlationId
);
const response: PlatformAuthResponse =
await this.platformAuthProvider.sendMessage(request);
const authResult = await this.handleNativeResponse(
response,
request,
reqTimestamp
);
const serverTelemetryManager = initializeServerTelemetryManager(
this.apiId,
this.config.auth.clientId,
this.correlationId,
this.browserStorage,
this.logger,
undefined,
this.config.system.serverTelemetryEnabled
);
serverTelemetryManager.clearNativeBrokerErrorCode();
this.performanceClient?.addFields(
{ isNativeBroker: true },
this.correlationId
);
return authResult;
} catch (e) {
throw e;
}
}
/**
* Logout from native platform via browser extension
* @param request
*/
logout(): Promise<void> {
this.logger.trace(
"NativeInteractionClient - logout called.",
this.correlationId
);
return Promise.reject("Logout not implemented yet");
}
/**
* Transform response from native platform into AuthenticationResult object which will be returned to the end user
* @param response
* @param request
* @param reqTimestamp
*/
protected async handleNativeResponse(
response: PlatformAuthResponse,
request: PlatformAuthRequest,
reqTimestamp: number
): Promise<AuthenticationResult> {
this.logger.trace(
"NativeInteractionClient - handleNativeResponse called.",
this.correlationId
);
// generate identifiers
const idTokenClaims = AuthToken.extractTokenClaims(
response.id_token,
base64Decode
);
const homeAccountIdentifier = this.createHomeAccountIdentifier(
response,
idTokenClaims
);
const cachedhomeAccountId =
this.browserStorage.getAccountInfoFilteredBy(
{
nativeAccountId: request.accountId,
},
this.correlationId
)?.homeAccountId;
// add exception for double brokering, please note this is temporary and will be fortified in future
if (
request.extraParameters?.child_client_id &&
response.account.id !== request.accountId
) {
this.logger.info(
"handleNativeServerResponse: Double broker flow detected, ignoring accountId mismatch",
this.correlationId
);
} else if (
homeAccountIdentifier !== cachedhomeAccountId &&
response.account.id !== request.accountId
) {
// User switch in native broker prompt is not supported. All users must first sign in through web flow to ensure server state is in sync
throw createNativeAuthError(NativeAuthErrorCodes.userSwitch);
}
// Get the preferred_cache domain for the given authority
const authority = await getDiscoveredAuthority(
this.config,
this.correlationId,
this.performanceClient,
this.browserStorage,
this.logger,
request.authority
);
const baseAccount = buildAccountToCache(
this.browserStorage,
authority,
homeAccountIdentifier,
base64Decode,
this.correlationId,
idTokenClaims,
response.client_info,
authority.getPreferredCache(), // environment
idTokenClaims.tid,
undefined, // auth code payload
response.account.id,
this.logger,
this.performanceClient
);
// Ensure expires_in is in number format
response.expires_in = Number(response.expires_in);
// generate authenticationResult
const result = await this.generateAuthenticationResult(
response,
request,
idTokenClaims,
baseAccount,
authority.canonicalAuthority,
reqTimestamp
);
// cache accounts and tokens in the appropriate storage
await this.cacheAccount(baseAccount, AuthToken.isKmsi(idTokenClaims));
await this.cacheNativeTokens(
response,
request,
homeAccountIdentifier,
idTokenClaims,
result.tenantId,
reqTimestamp,
authority.getPreferredCache() // environment
);
return result;
}
/**
* creates an homeAccountIdentifier for the account
* @param response
* @param idTokenObj
* @returns
*/
protected createHomeAccountIdentifier(
response: PlatformAuthResponse,
idTokenClaims: TokenClaims
): string {
// Save account in browser storage
const homeAccountIdentifier = AccountEntityUtils.generateHomeAccountId(
response.client_info || "",
AuthorityType.Default,
this.logger,
this.browserCrypto,
this.correlationId,
idTokenClaims
);
return homeAccountIdentifier;
}
/**
* Helper to generate scopes
* @param response
* @param request
* @returns
*/
generateScopes(requestScopes: string, responseScopes?: string): ScopeSet {
return responseScopes
? ScopeSet.fromString(responseScopes)
: ScopeSet.fromString(requestScopes);
}
/**
* If PoP token is requesred, records the PoP token if returned from the WAM, else generates one in the browser
* @param request
* @param response
*/
async generatePopAccessToken(
response: PlatformAuthResponse,
request: PlatformAuthRequest
): Promise<string> {
if (
request.tokenType === Constants.AuthenticationScheme.POP &&
request.signPopToken
) {
/**
* This code prioritizes SHR returned from the native layer. In case of error/SHR not calculated from WAM and the AT
* is still received, SHR is calculated locally
*/
// Check if native layer returned an SHR token
if (response.shr) {
this.logger.trace(
"handleNativeServerResponse: SHR is enabled in native layer",
this.correlationId
);
return response.shr;
}
// Generate SHR in msal js if WAM does not compute it when POP is enabled
const popTokenGenerator: PopTokenGenerator = new PopTokenGenerator(
this.browserCrypto,
this.performanceClient
);
const shrParameters: SignedHttpRequestParameters = {
resourceRequestMethod: request.resourceRequestMethod,
resourceRequestUri: request.resourceRequestUri,
shrClaims: request.shrClaims,
shrNonce: request.shrNonce,
correlationId: this.correlationId,
};
/**
* KeyID must be present in the native request from when the PoP key was generated in order for
* PopTokenGenerator to query the full key for signing
*/
if (!request.keyId) {
throw createClientAuthError(ClientAuthErrorCodes.keyIdMissing);
}
return popTokenGenerator.signPopToken(
response.access_token,
request.keyId,
shrParameters
);
} else {
return response.access_token;
}
}
/**
* Generates authentication result
* @param response
* @param request
* @param idTokenObj
* @param accountEntity
* @param authority
* @param reqTimestamp
* @returns
*/
protected async generateAuthenticationResult(
response: PlatformAuthResponse,
request: PlatformAuthRequest,
idTokenClaims: TokenClaims,
accountEntity: AccountEntity,
authority: string,
reqTimestamp: number
): Promise<AuthenticationResult> {
// Add Native Broker fields to Telemetry
const mats = this.addTelemetryFromNativeResponse(
response.properties.MATS
);
// If scopes not returned in server response, use request scopes
const responseScopes = this.generateScopes(
request.scope,
response.scope
);
const accountProperties = response.account.properties || {};
const uid =
accountProperties["UID"] ||
idTokenClaims.oid ||
idTokenClaims.sub ||
"";
const tid = accountProperties["TenantId"] || idTokenClaims.tid || "";
const accountInfo: AccountInfo | null = updateAccountTenantProfileData(
AccountEntityUtils.getAccountInfo(accountEntity),
undefined, // tenantProfile optional
idTokenClaims,
response.id_token
);
/**
* In pairwise broker flows, this check prevents the broker's native account id
* from being returned over the embedded app's account id.
*/
if (accountInfo.nativeAccountId !== response.account.id) {
accountInfo.nativeAccountId = response.account.id;
}
// generate PoP token as needed
const responseAccessToken = await this.generatePopAccessToken(
response,
request
);
const tokenType =
request.tokenType === Constants.AuthenticationScheme.POP
? Constants.AuthenticationScheme.POP
: Constants.AuthenticationScheme.BEARER;
const result: AuthenticationResult = {
authority: authority,
uniqueId: uid,
tenantId: tid,
scopes: responseScopes.asArray(),
account: accountInfo,
idToken: response.id_token,
idTokenClaims: idTokenClaims,
accessToken: responseAccessToken,
fromCache: mats ? this.isResponseFromCache(mats) : false,
// Request timestamp and NativeResponse expires_in are in seconds, converting to Date for AuthenticationResult
expiresOn: TimeUtils.toDateFromSeconds(
reqTimestamp + response.expires_in
),
tokenType: tokenType,
correlationId: this.correlationId,
state: response.state,
fromPlatformBroker: true,
...(request.resource && { resource: request.resource }),
};
return result;
}
/**
* cache the account entity in browser storage
* @param accountEntity
*/
async cacheAccount(
accountEntity: AccountEntity,
kmsi: boolean
): Promise<void> {
// Store the account info and hence `nativeAccountId` in browser cache
await this.browserStorage.setAccount(
accountEntity,
this.correlationId,
kmsi,
this.apiId
);
// Remove any existing cached tokens for this account in browser storage
this.browserStorage.removeAccountContext(
AccountEntityUtils.getAccountInfo(accountEntity),
this.correlationId
);
}
/**
* Stores the access_token and id_token in inmemory storage
* @param response
* @param request
* @param homeAccountIdentifier
* @param idTokenObj
* @param responseAccessToken
* @param tenantId
* @param reqTimestamp
*/
async cacheNativeTokens(
response: PlatformAuthResponse,
request: PlatformAuthRequest,
homeAccountIdentifier: string,
idTokenClaims: TokenClaims,
tenantId: string,
reqTimestamp: number,
environment: string
): Promise<void> {
const cachedIdToken: IdTokenEntity | null =
CacheHelpers.createIdTokenEntity(
homeAccountIdentifier,
environment,
response.id_token || "",
request.clientId,
idTokenClaims.tid || ""
);
// cache accessToken in inmemory storage
const expiresIn: number =
request.tokenType === Constants.AuthenticationScheme.POP
? Constants.SHR_NONCE_VALIDITY
: (typeof response.expires_in === "string"
? parseInt(response.expires_in, 10)
: response.expires_in) || 0;
const tokenExpirationSeconds = reqTimestamp + expiresIn;
const responseScopes = this.generateScopes(
response.scope,
request.scope
);
const cachedAccessToken: AccessTokenEntity | null =
CacheHelpers.createAccessTokenEntity(
homeAccountIdentifier,
environment,
response.access_token,
request.clientId,
idTokenClaims.tid || tenantId,
responseScopes.printScopes(),
tokenExpirationSeconds,
0,
base64Decode,
undefined,
request.tokenType as Constants.AuthenticationScheme,
undefined,
request.keyId
);
// save idtoken credential in configured browser storage
if (!!cachedIdToken && request.storeInCache?.idToken !== false) {
await this.browserStorage.setIdTokenCredential(
cachedIdToken,
this.correlationId,
AuthToken.isKmsi(idTokenClaims)
);
}
// save access token credential in memory storage
const nativeCacheRecord = {
accessToken: cachedAccessToken,
};
return this.nativeStorageManager.saveCacheRecord(
nativeCacheRecord,
this.correlationId,
AuthToken.isKmsi(idTokenClaims),
this.apiId,
request.storeInCache
);
}
getExpiresInValue(
tokenType: string,
expiresIn: string | number | undefined
): number {
return tokenType === Constants.AuthenticationScheme.POP
? Constants.SHR_NONCE_VALIDITY
: (typeof expiresIn === "string"
? parseInt(expiresIn, 10)
: expiresIn) || 0;
}
protected addTelemetryFromNativeResponse(
matsResponse?: string
): MATS | null {
const mats = this.getMATSFromResponse(matsResponse);
if (!mats) {
return null;
}
this.performanceClient.addFields(
{
extensionId: this.platformAuthProvider.getExtensionId(),
extensionVersion:
this.platformAuthProvider.getExtensionVersion(),
matsBrokerVersion: mats.broker_version,
matsAccountJoinOnStart: mats.account_join_on_start,
matsAccountJoinOnEnd: mats.account_join_on_end,
matsDeviceJoin: mats.device_join,
matsPromptBehavior: mats.prompt_behavior,
matsApiErrorCode: mats.api_error_code,
matsUiVisible: mats.ui_visible,
matsSilentCode: mats.silent_code,
matsSilentBiSubCode: mats.silent_bi_sub_code,
matsSilentMessage: mats.silent_message,
matsSilentStatus: mats.silent_status,
matsHttpStatus: mats.http_status,
matsHttpEventCount: mats.http_event_count,
},
this.correlationId
);
return mats;
}
/**
* Gets MATS telemetry from native response
* @param response
* @returns
*/
private getMATSFromResponse(matsResponse: string | undefined): MATS | null {
if (matsResponse) {
try {
return JSON.parse(matsResponse);
} catch (e) {
this.logger.error(
"NativeInteractionClient - Error parsing MATS telemetry, returning null instead",
this.correlationId
);
}
}
return null;
}
/**
* Returns whether or not response came from native cache
* @param response
* @returns
*/
protected isResponseFromCache(mats: MATS): boolean {
if (typeof mats.is_cached === "undefined") {
this.logger.verbose(
"NativeInteractionClient - MATS telemetry does not contain field indicating if response was served from cache. Returning false.",
this.correlationId
);
return false;
}
return !!mats.is_cached;
}
/**
* Translates developer provided request object into NativeRequest object
* @param request
*/
protected async initializePlatformRequest(
request: PopupRequest | SsoSilentRequest
): Promise<PlatformAuthRequest> {
this.logger.trace(
"NativeInteractionClient - initializePlatformRequest called",
this.correlationId
);
const canonicalAuthority = await this.getCanonicalAuthority(request);
// ignore config claims if skipBrokerClaims is set to true and this is a brokered authentication flow
const configClaims =
request.skipBrokerClaims && !!request.embeddedClientId
? undefined
: this.config.auth.clientCapabilities;
// scopes are expected to be received by the native broker as "scope" and will be added to the request below. Other properties that should be dropped from the request to the native broker can be included in the object destructuring here.
const { scopes, claims, ...remainingProperties } = request;
const scopeSet = new ScopeSet(scopes || []);
scopeSet.appendScopes(Constants.OIDC_DEFAULT_SCOPES);
const mergedClaims =