-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathUserAgentApplication.ts
1989 lines (1792 loc) · 88.3 KB
/
UserAgentApplication.ts
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
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the 'Software'), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
* OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { AccessTokenCacheItem } from "./AccessTokenCacheItem";
import { AccessTokenKey } from "./AccessTokenKey";
import { AccessTokenValue } from "./AccessTokenValue";
import { AuthenticationRequestParameters } from "./AuthenticationRequestParameters";
import { Authority } from "./Authority";
import { ClientInfo } from "./ClientInfo";
import { Constants, ErrorCodes, ErrorDescription } from "./Constants";
import { IdToken } from "./IdToken";
import { Logger } from "./Logger";
import { Storage } from "./Storage";
import { TokenResponse } from "./RequestInfo";
import { User } from "./User";
import { Utils } from "./Utils";
import { AuthorityFactory } from "./AuthorityFactory";
declare global {
interface Window {
msal: Object;
CustomEvent: CustomEvent;
Event: Event;
activeRenewals: {};
renewStates: Array<string>;
callBackMappedToRenewStates : {};
callBacksMappedToRenewStates: {};
openedWindows: Array<Window>;
requestType: string;
}
}
/*
* @hidden
*/
let ResponseTypes = {
id_token: "id_token",
token: "token",
id_token_token: "id_token token"
};
/*
* @hidden
*/
export interface CacheResult {
errorDesc: string;
token: string;
error: string;
}
/*
* A type alias of for a tokenReceivedCallback function.
* @param tokenReceivedCallback.errorDesc error description returned from the STS if API call fails.
* @param tokenReceivedCallback.token token returned from STS if token request is successful.
* @param tokenReceivedCallback.error error code returned from the STS if API call fails.
* @param tokenReceivedCallback.tokenType tokenType returned from the STS if API call is successful. Possible values are: id_token OR access_token.
*/
export type tokenReceivedCallback = (errorDesc: string, token: string, error: string, tokenType: string, userState: string ) => void;
const resolveTokenOnlyIfOutOfIframe = (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
const tokenAcquisitionMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
return this.isInIframe()
? new Promise(() => { })
: tokenAcquisitionMethod.apply(this, args);
};
return descriptor;
};
export class UserAgentApplication {
/*
* @hidden
*/
private _cacheLocations = {
localStorage: "localStorage",
sessionStorage: "sessionStorage"
};
/*
* @hidden
*/
private _cacheLocation: string;
/*
* Used to get the cache location
*/
get cacheLocation(): string {
return this._cacheLocation;
}
/*
* @hidden
*/
protected _logger: Logger;
/*
* @hidden
*/
private _loginInProgress: boolean;
/*
* @hidden
*/
private _acquireTokenInProgress: boolean;
/*
* @hidden
*/
private _clockSkew = 300;
/*
* @hidden
*/
protected _cacheStorage: Storage;
/*
* @hidden
*/
private _tokenReceivedCallback: tokenReceivedCallback = null;
/*
* @hidden
*/
private _user: User;
/*
* Client ID assigned to your app by Azure Active Directory.
*/
clientId: string;
/*
* @hidden
*/
protected authorityInstance: Authority;
/*
* Used to set the authority.
* @param {string} authority - A URL indicating a directory that MSAL can use to obtain tokens.
* - In Azure AD, it is of the form https://<tenant>/<tenant>, where <tenant> is the directory host (e.g. https://login.microsoftonline.com) and <tenant> is a identifier within the directory itself (e.g. a domain associated to the tenant, such as contoso.onmicrosoft.com, or the GUID representing the TenantID property of the directory)
* - In Azure B2C, it is of the form https://<instance>/tfp/<tenant>/<policyName>/
* - Default value is: "https://login.microsoftonline.com/common"
*/
public set authority(val) {
this.authorityInstance = AuthorityFactory.CreateInstance(val, this.validateAuthority);
}
/*
* Used to get the authority.
*/
public get authority(): string {
return this.authorityInstance.CanonicalAuthority;
}
/*
* Used to turn authority validation on/off.
* When set to true (default), MSAL will compare the application"s authority against well-known URLs templates representing well-formed authorities. It is useful when the authority is obtained at run time to prevent MSAL from displaying authentication prompts from malicious pages.
*/
validateAuthority: boolean;
/*
* The redirect URI of the application, this should be same as the value in the application registration portal.
* Defaults to `window.location.href`.
*/
private _redirectUri: string;
/*
* Use to send the state parameter with authentication request
*/
private _state: string;
/*
* Used to redirect the user to this location after logout.
* Defaults to `window.location.href`.
*/
private _postLogoutredirectUri: string;
loadFrameTimeout: number;
protected _navigateToLoginRequestUrl: boolean;
private _isAngular: boolean = false;
private _protectedResourceMap: Map<string, Array<string>>;
private _unprotectedResources: Array<string>;
private storeAuthStateInCookie: boolean;
private _silentAuthenticationState: string;
private _silentLogin: boolean;
/*
* Initialize a UserAgentApplication with a given clientId and authority.
* @constructor
* @param {string} clientId - The clientID of your application, you should get this from the application registration portal.
* @param {string} authority - A URL indicating a directory that MSAL can use to obtain tokens.
* - In Azure AD, it is of the form https://<instance>/<tenant>,\ where <instance> is the directory host (e.g. https://login.microsoftonline.com) and <tenant> is a identifier within the directory itself (e.g. a domain associated to the tenant, such as contoso.onmicrosoft.com, or the GUID representing the TenantID property of the directory)
* - In Azure B2C, it is of the form https://<instance>/tfp/<tenantId>/<policyName>/
* - Default value is: "https://login.microsoftonline.com/common"
* @param _tokenReceivedCallback - The function that will get the call back once this API is completed (either successfully or with a failure).
* @param {boolean} validateAuthority - boolean to turn authority validation on/off.
*/
constructor(
clientId: string,
authority: string | null,
tokenReceivedCallback: tokenReceivedCallback,
options:
{
validateAuthority?: boolean,
cacheLocation?: string,
redirectUri?: string,
postLogoutRedirectUri?: string,
logger?: Logger,
loadFrameTimeout?: number,
navigateToLoginRequestUrl?: boolean,
state?: string,
isAngular?: boolean,
unprotectedResources?: Array<string>
protectedResourceMap?:Map<string,Array<string>>,
storeAuthStateInCookie?:boolean
} = {}) {
const {
validateAuthority = true,
cacheLocation = "sessionStorage",
redirectUri = window.location.href.split("?")[0].split("#")[0],
postLogoutRedirectUri = window.location.href.split("?")[0].split("#")[0],
logger = new Logger(null),
loadFrameTimeout = 6000,
navigateToLoginRequestUrl = true,
state = "",
isAngular = false,
unprotectedResources = new Array<string>(),
protectedResourceMap = new Map<string, Array<string>>(),
storeAuthStateInCookie = false
} = options;
this.loadFrameTimeout = loadFrameTimeout;
this.clientId = clientId;
this.validateAuthority = validateAuthority;
this.authority = authority || "https://login.microsoftonline.com/common";
this._tokenReceivedCallback = tokenReceivedCallback;
this._redirectUri = redirectUri;
this._postLogoutredirectUri = postLogoutRedirectUri;
this._loginInProgress = false;
this._acquireTokenInProgress = false;
this._cacheLocation = cacheLocation;
this._navigateToLoginRequestUrl = navigateToLoginRequestUrl;
this._state = state;
this._isAngular = isAngular;
this._unprotectedResources = unprotectedResources;
this._protectedResourceMap = protectedResourceMap;
if (!this._cacheLocations[cacheLocation]) {
throw new Error("Cache Location is not valid. Provided value:" + this._cacheLocation + ".Possible values are: " + this._cacheLocations.localStorage + ", " + this._cacheLocations.sessionStorage);
}
this._cacheStorage = new Storage(this._cacheLocation); //cache keys msal
this._logger = logger;
this.storeAuthStateInCookie = storeAuthStateInCookie;
window.openedWindows = [];
window.activeRenewals = {};
window.renewStates = [];
window.callBackMappedToRenewStates = { };
window.callBacksMappedToRenewStates = { };
window.msal = this;
var urlHash = window.location.hash;
var isCallback = this.isCallback(urlHash);
if (!this._isAngular) {
if (isCallback) {
this.handleAuthenticationResponse.call(this, urlHash);
}
else {
var pendingCallback = this._cacheStorage.getItem(Constants.urlHash);
if (pendingCallback) {
this.processCallBack(pendingCallback);
}
}
}
}
/*
* Used to call the constructor callback with the token/error
* @param {string} [hash=window.location.hash] - Hash fragment of Url.
* @hidden
*/
private processCallBack(hash: string): void {
this._logger.info('Processing the callback from redirect response');
const requestInfo = this.getRequestInfo(hash);
this.saveTokenFromHash(requestInfo);
const token = requestInfo.parameters[Constants.accessToken] || requestInfo.parameters[Constants.idToken];
const errorDesc = requestInfo.parameters[Constants.errorDescription];
const error = requestInfo.parameters[Constants.error];
var tokenType: string;
if (requestInfo.parameters[Constants.accessToken]) {
tokenType = Constants.accessToken;
}
else {
tokenType = Constants.idToken;
}
this._cacheStorage.removeItem(Constants.urlHash);
try {
if (this._tokenReceivedCallback) {
this._cacheStorage.clearCookie();
this._tokenReceivedCallback.call(this, errorDesc, token, error, tokenType, this.getUserState(this._cacheStorage.getItem(Constants.stateLogin, this.storeAuthStateInCookie)));
}
} catch (err) {
this._logger.error("Error occurred in token received callback function: " + err);
}
}
/*
* Initiate the login process by redirecting the user to the STS authorization endpoint.
* @param {Array.<string>} scopes - Permissions you want included in the access token. Not all scopes are guaranteed to be included in the access token returned.
* @param {string} extraQueryParameters - Key-value pairs to pass to the authentication server during the interactive authentication flow.
*/
loginRedirect(scopes?: Array<string>, extraQueryParameters?: string): void {
/*
1. Create navigate url
2. saves value in cache
3. redirect user to AAD
*/
if (this._loginInProgress) {
if (this._tokenReceivedCallback) {
this._tokenReceivedCallback(ErrorDescription.loginProgressError, null, ErrorCodes.loginProgressError, Constants.idToken, this.getUserState(this._cacheStorage.getItem(Constants.stateLogin, this.storeAuthStateInCookie)));
return;
}
}
if (scopes) {
const isValidScope = this.validateInputScope(scopes);
if (isValidScope && !Utils.isEmpty(isValidScope)) {
if (this._tokenReceivedCallback) {
this._tokenReceivedCallback(ErrorDescription.inputScopesError, null, ErrorCodes.inputScopesError, Constants.idToken, this.getUserState(this._cacheStorage.getItem(Constants.stateLogin, this.storeAuthStateInCookie)));
return;
}
}
scopes = this.filterScopes(scopes);
}
var idTokenObject;
idTokenObject= this.extractADALIdToken();
if (idTokenObject && !scopes) {
this._logger.info("ADAL's idToken exists. Extracting login information from ADAL's idToken ");
extraQueryParameters = Utils.constructUnifiedCacheExtraQueryParameter(idTokenObject, extraQueryParameters);
this._silentLogin = true;
this.acquireTokenSilent([this.clientId], this.authority, this.getUser(), extraQueryParameters)
.then((idToken) => {
this._silentLogin = false;
this._logger.info("Unified cache call is successful");
if (this._tokenReceivedCallback) {
this._tokenReceivedCallback.call(this, null, idToken, null, Constants.idToken, this.getUserState(this._silentAuthenticationState));
}
}, (error) => {
this._silentLogin = false;
this._logger.error("Error occurred during unified cache ATS");
this.loginRedirectHelper(scopes, extraQueryParameters);
});
}
else {
this.loginRedirectHelper(scopes, extraQueryParameters);
}
}
private loginRedirectHelper(scopes?: Array<string>, extraQueryParameters?: string)
{
this._loginInProgress = true;
this.authorityInstance.ResolveEndpointsAsync()
.then(() => {
const authenticationRequest = new AuthenticationRequestParameters(this.authorityInstance, this.clientId, scopes, ResponseTypes.id_token, this._redirectUri, this._state);
if (extraQueryParameters) {
authenticationRequest.extraQueryParameters = extraQueryParameters;
}
var loginStartPage = this._cacheStorage.getItem(Constants.angularLoginRequest);
if (!loginStartPage || loginStartPage === "") {
loginStartPage = window.location.href;
}
else {
this._cacheStorage.setItem(Constants.angularLoginRequest, "")
}
this._cacheStorage.setItem(Constants.loginRequest, loginStartPage, this.storeAuthStateInCookie);
this._cacheStorage.setItem(Constants.loginError, "");
this._cacheStorage.setItem(Constants.stateLogin, authenticationRequest.state, this.storeAuthStateInCookie);
this._cacheStorage.setItem(Constants.nonceIdToken, authenticationRequest.nonce, this.storeAuthStateInCookie);
this._cacheStorage.setItem(Constants.msalError, "");
this._cacheStorage.setItem(Constants.msalErrorDescription, "");
const authorityKey = Constants.authority + Constants.resourceDelimeter + authenticationRequest.state;
if (Utils.isEmpty(this._cacheStorage.getItem(authorityKey))) {
this._cacheStorage.setItem(authorityKey, this.authority);
}
const urlNavigate = authenticationRequest.createNavigateUrl(scopes) + Constants.prompt_select_account + Constants.response_mode_fragment;
this.promptUser(urlNavigate);
});
}
/*
* Initiate the login process by opening a popup window.
* @param {Array.<string>} scopes - Permissions you want included in the access token. Not all scopes are guaranteed to be included in the access token returned.
* @param {string} extraQueryParameters - Key-value pairs to pass to the STS during the interactive authentication flow.
* @returns {Promise.<string>} - A Promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the token or error.
*/
loginPopup(scopes ?: Array<string>, extraQueryParameters?: string): Promise<string> {
/*
1. Create navigate url
2. saves value in cache
3. redirect user to AAD
*/
return new Promise<string>((resolve, reject) => {
if (this._loginInProgress) {
reject(ErrorCodes.loginProgressError + Constants.resourceDelimeter + ErrorDescription.loginProgressError);
return;
}
if (scopes) {
const isValidScope = this.validateInputScope(scopes);
if (isValidScope && !Utils.isEmpty(isValidScope)) {
reject(ErrorCodes.inputScopesError + Constants.resourceDelimeter + ErrorDescription.inputScopesError);
return;
}
scopes = this.filterScopes(scopes);
}
var idTokenObject;
idTokenObject= this.extractADALIdToken();
if (idTokenObject && !scopes) {
this._logger.info("ADAL's idToken exists. Extracting login information from ADAL's idToken ");
extraQueryParameters = Utils.constructUnifiedCacheExtraQueryParameter(idTokenObject, extraQueryParameters);
this._silentLogin = true;
this.acquireTokenSilent([this.clientId], this.authority, this.getUser(), extraQueryParameters)
.then((idToken) => {
this._silentLogin = false;
this._logger.info("Unified cache call is successful");
resolve(idToken);
}, (error) => {
this._silentLogin = false;
this._logger.error("Error occurred during unified cache ATS");
this.loginPopupHelper(resolve, reject, scopes, extraQueryParameters);
});
}
else {
this.loginPopupHelper(resolve, reject, scopes, extraQueryParameters );
}
});
}
private loginPopupHelper( resolve: any , reject: any, scopes: Array<string>, extraQueryParameters?: string)
{
//TODO why this is needed only for loginpopup
if(!scopes) {
scopes = [this.clientId];
}
const scope = scopes.join(" ").toLowerCase();
var popUpWindow = this.openWindow("about:blank", "_blank", 1, this, resolve, reject);
if (!popUpWindow) {
return;
}
this._loginInProgress = true;
this.authorityInstance.ResolveEndpointsAsync().then(() => {
const authenticationRequest = new AuthenticationRequestParameters(this.authorityInstance, this.clientId, scopes, ResponseTypes.id_token, this._redirectUri, this._state);
if (extraQueryParameters) {
authenticationRequest.extraQueryParameters = extraQueryParameters;
}
this._cacheStorage.setItem(Constants.loginRequest, window.location.href, this.storeAuthStateInCookie);
this._cacheStorage.setItem(Constants.loginError, "");
this._cacheStorage.setItem(Constants.nonceIdToken, authenticationRequest.nonce, this.storeAuthStateInCookie);
this._cacheStorage.setItem(Constants.msalError, "");
this._cacheStorage.setItem(Constants.msalErrorDescription, "");
const authorityKey = Constants.authority + Constants.resourceDelimeter + authenticationRequest.state;
if (Utils.isEmpty(this._cacheStorage.getItem(authorityKey))) {
this._cacheStorage.setItem(authorityKey, this.authority);
}
const urlNavigate = authenticationRequest.createNavigateUrl(scopes) + Constants.prompt_select_account + Constants.response_mode_fragment;
window.renewStates.push(authenticationRequest.state);
window.requestType = Constants.login;
this.registerCallback(authenticationRequest.state, scope, resolve, reject);
if (popUpWindow) {
this._logger.infoPii("Navigated Popup window to:" + urlNavigate);
popUpWindow.location.href = urlNavigate;
}
}, () => {
this._logger.info(ErrorCodes.endpointResolutionError + ":" + ErrorDescription.endpointResolutionError);
this._cacheStorage.setItem(Constants.msalError, ErrorCodes.endpointResolutionError);
this._cacheStorage.setItem(Constants.msalErrorDescription, ErrorDescription.endpointResolutionError);
if (reject) {
reject(ErrorCodes.endpointResolutionError + ":" + ErrorDescription.endpointResolutionError);
}
if (popUpWindow) {
popUpWindow.close();
}
}).catch((err) => {
this._logger.warning("could not resolve endpoints");
reject(err);
});
}
/*
* Used to redirect the browser to the STS authorization endpoint
* @param {string} urlNavigate - URL of the authorization endpoint
* @hidden
*/
private promptUser(urlNavigate: string) {
if (urlNavigate && !Utils.isEmpty(urlNavigate)) {
this._logger.infoPii("Navigate to:" + urlNavigate);
window.location.replace(urlNavigate);
} else {
this._logger.info("Navigate url is empty");
}
}
/*
* Used to send the user to the redirect_uri after authentication is complete. The user"s bearer token is attached to the URI fragment as an id_token/access_token field.
* This function also closes the popup window after redirection.
* @hidden
* @ignore
*/
private openWindow(urlNavigate: string, title: string, interval: number, instance: this, resolve?: Function, reject?: Function): Window {
var popupWindow = this.openPopup(urlNavigate, title, Constants.popUpWidth, Constants.popUpHeight);
if (popupWindow == null) {
instance._loginInProgress = false;
instance._acquireTokenInProgress = false;
this._logger.info(ErrorCodes.popUpWindowError + ":" + ErrorDescription.popUpWindowError);
this._cacheStorage.setItem(Constants.msalError, ErrorCodes.popUpWindowError);
this._cacheStorage.setItem(Constants.msalErrorDescription, ErrorDescription.popUpWindowError);
if (reject) {
reject(ErrorCodes.popUpWindowError + Constants.resourceDelimeter + ErrorDescription.popUpWindowError);
}
return null;
}
window.openedWindows.push(popupWindow);
var pollTimer = window.setInterval(() => {
if (popupWindow && popupWindow.closed && instance._loginInProgress) {
if (reject) {
reject(ErrorCodes.userCancelledError + Constants.resourceDelimeter + ErrorDescription.userCancelledError);
}
window.clearInterval(pollTimer);
if (this._isAngular) {
this.broadcast('msal:popUpClosed', ErrorCodes.userCancelledError + Constants.resourceDelimeter + ErrorDescription.userCancelledError);
return;
}
instance._loginInProgress = false;
instance._acquireTokenInProgress = false;
}
try {
var popUpWindowLocation = popupWindow.location;
if (popUpWindowLocation.href.indexOf(this._redirectUri) !== -1) {
window.clearInterval(pollTimer);
instance._loginInProgress = false;
instance._acquireTokenInProgress = false;
this._logger.info("Closing popup window");
if (this._isAngular) {
this.broadcast('msal:popUpHashChanged', popUpWindowLocation.hash);
for (var i = 0; i < window.openedWindows.length; i++) {
window.openedWindows[i].close();
}
}
}
} catch (e) {
//Cross Domain url check error. Will be thrown until AAD redirects the user back to the app"s root page with the token. No need to log or throw this error as it will create unnecessary traffic.
}
},
interval);
return popupWindow;
}
private broadcast(eventName: string, data: string) {
var evt = new CustomEvent(eventName, { detail: data });
window.dispatchEvent(evt);
}
/*
* Used to log out the current user, and redirect the user to the postLogoutRedirectUri.
* Defaults behaviour is to redirect the user to `window.location.href`.
*/
logout(): void {
this.clearCache();
this._user = null;
let logout = "";
if (this._postLogoutredirectUri) {
logout = "post_logout_redirect_uri=" + encodeURIComponent(this._postLogoutredirectUri);
}
const urlNavigate = this.authority + "/oauth2/v2.0/logout?" + logout;
this.promptUser(urlNavigate);
}
/*
* Used to configure the popup window for login.
* @ignore
* @hidden
*/
protected clearCache(): void {
window.renewStates = [];
const accessTokenItems = this._cacheStorage.getAllAccessTokens(Constants.clientId, Constants.userIdentifier);
for (let i = 0; i < accessTokenItems.length; i++) {
this._cacheStorage.removeItem(JSON.stringify(accessTokenItems[i].key));
}
this._cacheStorage.resetCacheItems();
this._cacheStorage.clearCookie();
}
protected clearCacheForScope(accessToken: string) {
const accessTokenItems = this._cacheStorage.getAllAccessTokens(Constants.clientId, Constants.userIdentifier);
for (var i = 0; i < accessTokenItems.length; i++){
var token = accessTokenItems[i];
if (token.value.accessToken == accessToken) {
this._cacheStorage.removeItem(JSON.stringify(token.key));
}
}
}
/*
* Configures popup window for login.
* @ignore
* @hidden
*/
private openPopup(urlNavigate: string, title: string, popUpWidth: number, popUpHeight: number) {
try {
/*
* adding winLeft and winTop to account for dual monitor
* using screenLeft and screenTop for IE8 and earlier
*/
const winLeft = window.screenLeft ? window.screenLeft : window.screenX;
const winTop = window.screenTop ? window.screenTop : window.screenY;
/*
* window.innerWidth displays browser window"s height and width excluding toolbars
* using document.documentElement.clientWidth for IE8 and earlier
*/
const width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
const height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
const left = ((width / 2) - (popUpWidth / 2)) + winLeft;
const top = ((height / 2) - (popUpHeight / 2)) + winTop;
const popupWindow = window.open(urlNavigate, title, "width=" + popUpWidth + ", height=" + popUpHeight + ", top=" + top + ", left=" + left);
if (popupWindow.focus) {
popupWindow.focus();
}
return popupWindow;
} catch (e) {
this._logger.error("error opening popup " + e.message);
this._loginInProgress = false;
this._acquireTokenInProgress = false;
return null;
}
}
/*
* Used to validate the scopes input parameter requested by the developer.
* @param {Array<string>} scopes - Developer requested permissions. Not all scopes are guaranteed to be included in the access token returned.
* @ignore
* @hidden
*/
private validateInputScope(scopes: Array<string>): string {
if (!scopes || scopes.length < 1) {
return "Scopes cannot be passed as an empty array";
}
if (!Array.isArray(scopes)) {
throw new Error("API does not accept non-array scopes");
}
if (scopes.indexOf(this.clientId) > -1) {
if (scopes.length > 1) {
return "ClientId can only be provided as a single scope";
}
}
return "";
}
/*
* Used to remove openid and profile from the list of scopes passed by the developer.These scopes are added by default
* @hidden
*/
private filterScopes(scopes: Array<string>): Array<string> {
scopes = scopes.filter(function (element) {
return element !== "openid";
});
scopes = scopes.filter(function (element) {
return element !== "profile";
});
return scopes;
}
/*
* Used to add the developer requested callback to the array of callbacks for the specified scopes. The updated array is stored on the window object
* @param {string} scope - Developer requested permissions. Not all scopes are guaranteed to be included in the access token returned.
* @param {string} expectedState - Unique state identifier (guid).
* @param {Function} resolve - The resolve function of the promise object.
* @param {Function} reject - The reject function of the promise object.
* @ignore
* @hidden
*/
private registerCallback(expectedState: string, scope: string, resolve: Function, reject: Function): void {
window.activeRenewals[scope] = expectedState;
if (!window.callBacksMappedToRenewStates[expectedState]) {
window.callBacksMappedToRenewStates[expectedState] = [];
}
window.callBacksMappedToRenewStates[expectedState].push({ resolve: resolve, reject: reject });
if (!window.callBackMappedToRenewStates[expectedState]) {
window.callBackMappedToRenewStates[expectedState] =
(errorDesc: string, token: string, error: string, tokenType: string) => {
window.activeRenewals[scope] = null;
for (let i = 0; i < window.callBacksMappedToRenewStates[expectedState].length; ++i) {
try {
if (errorDesc || error) {
window.callBacksMappedToRenewStates[expectedState][i].reject(errorDesc + Constants.resourceDelimeter + error);
}
else if (token) {
window.callBacksMappedToRenewStates[expectedState][i].resolve(token);
}
} catch (e) {
this._logger.warning(e);
}
}
window.callBacksMappedToRenewStates[expectedState] = null;
window.callBackMappedToRenewStates[expectedState] = null;
};
}
}
protected getCachedTokenInternal(scopes : Array<string> , user: User): CacheResult
{
const userObject = user ? user : this.getUser();
if (!userObject) {
return;
}
let authenticationRequest: AuthenticationRequestParameters;
let newAuthority = this.authorityInstance?this.authorityInstance: AuthorityFactory.CreateInstance(this.authority, this.validateAuthority);
if (Utils.compareObjects(userObject, this.getUser())) {
if (scopes.indexOf(this.clientId) > -1) {
authenticationRequest = new AuthenticationRequestParameters(newAuthority, this.clientId, scopes, ResponseTypes.id_token, this._redirectUri, this._state);
}
else {
authenticationRequest = new AuthenticationRequestParameters(newAuthority, this.clientId, scopes, ResponseTypes.token, this._redirectUri, this._state);
}
} else {
authenticationRequest = new AuthenticationRequestParameters(newAuthority, this.clientId, scopes, ResponseTypes.id_token_token, this._redirectUri, this._state);
}
return this.getCachedToken(authenticationRequest, user);
}
/*
* Used to get token for the specified set of scopes from the cache
* @param {AuthenticationRequestParameters} authenticationRequest - Request sent to the STS to obtain an id_token/access_token
* @param {User} user - User for which the scopes were requested
* @hidden
*/
private getCachedToken(authenticationRequest: AuthenticationRequestParameters, user: User): CacheResult {
let accessTokenCacheItem: AccessTokenCacheItem = null;
const scopes = authenticationRequest.scopes;
const tokenCacheItems = this._cacheStorage.getAllAccessTokens(this.clientId, user ? user.userIdentifier:null); //filter by clientId and user
if (tokenCacheItems.length === 0) { // No match found after initial filtering
return null;
}
const filteredItems: Array<AccessTokenCacheItem> = [];
//if no authority passed
if (!authenticationRequest.authority) {
//filter by scope
for (let i = 0; i < tokenCacheItems.length; i++) {
const cacheItem = tokenCacheItems[i];
const cachedScopes = cacheItem.key.scopes.split(" ");
if (Utils.containsScope(cachedScopes, scopes)) {
filteredItems.push(cacheItem);
}
}
//if only one cached token found
if (filteredItems.length === 1) {
accessTokenCacheItem = filteredItems[0];
authenticationRequest.authorityInstance = AuthorityFactory.CreateInstance(accessTokenCacheItem.key.authority, this.validateAuthority);
}
else if (filteredItems.length > 1) {
return {
errorDesc: "The cache contains multiple tokens satisfying the requirements. Call AcquireToken again providing more requirements like authority",
token: null,
error: "multiple_matching_tokens_detected"
};
}
else {
//no match found. check if there was a single authority used
const authorityList = this.getUniqueAuthority(tokenCacheItems, "authority");
if (authorityList.length > 1) {
return {
errorDesc: "Multiple authorities found in the cache. Pass authority in the API overload.",
token: null,
error: "multiple_matching_tokens_detected"
};
}
authenticationRequest.authorityInstance = AuthorityFactory.CreateInstance(authorityList[0], this.validateAuthority);
}
}
else {
//authority was passed in the API, filter by authority and scope
for (let i = 0; i < tokenCacheItems.length; i++) {
const cacheItem = tokenCacheItems[i];
const cachedScopes = cacheItem.key.scopes.split(" ");
if (Utils.containsScope(cachedScopes, scopes) && cacheItem.key.authority === authenticationRequest.authority) {
filteredItems.push(cacheItem);
}
}
//no match
if (filteredItems.length === 0) {
return null;
}
//only one cachedToken Found
else if (filteredItems.length === 1) {
accessTokenCacheItem = filteredItems[0];
}
else {
//more than one match found.
return {
errorDesc: "The cache contains multiple tokens satisfying the requirements.Call AcquireToken again providing more requirements like authority",
token: null,
error: "multiple_matching_tokens_detected"
};
}
}
if (accessTokenCacheItem != null) {
const expired = Number(accessTokenCacheItem.value.expiresIn);
// If expiration is within offset, it will force renew
const offset = this._clockSkew || 300;
if (expired && (expired > Utils.now() + offset)) {
return {
errorDesc: null,
token: accessTokenCacheItem.value.accessToken,
error: null
};
} else {
this._cacheStorage.removeItem(JSON.stringify(filteredItems[0].key));
return null;
}
} else {
return null;
}
}
/*
* Used to filter all cached items and return a list of unique users based on userIdentifier.
* @param {Array<User>} Users - users saved in the cache.
*/
getAllUsers(): Array<User> {
const users: Array<User> = [];
const accessTokenCacheItems = this._cacheStorage.getAllAccessTokens(Constants.clientId, Constants.userIdentifier);
for (let i = 0; i < accessTokenCacheItems.length; i++) {
const idToken = new IdToken(accessTokenCacheItems[i].value.idToken);
const clientInfo = new ClientInfo(accessTokenCacheItems[i].value.clientInfo);
const user = User.createUser(idToken, clientInfo, this.authority);
users.push(user);
}
return this.getUniqueUsers(users);
}
/*
* Used to filter users based on userIdentifier
* @param {Array<User>} Users - users saved in the cache
* @ignore
* @hidden
*/
private getUniqueUsers(users: Array<User>): Array<User> {
if (!users || users.length <= 1) {
return users;
}
const flags: Array<string> = [];
const uniqueUsers: Array<User> = [];
for (let index = 0; index < users.length; ++index) {
if (users[index].userIdentifier && flags.indexOf(users[index].userIdentifier) === -1) {
flags.push(users[index].userIdentifier);
uniqueUsers.push(users[index]);
}
}
return uniqueUsers;
}
/*
* Used to get a unique list of authoritues from the cache
* @param {Array<AccessTokenCacheItem>} accessTokenCacheItems - accessTokenCacheItems saved in the cache
* @ignore
* @hidden
*/
private getUniqueAuthority(accessTokenCacheItems: Array<AccessTokenCacheItem>, property: string): Array<string> {
const authorityList: Array<string> = [];
const flags: Array<string> = [];
accessTokenCacheItems.forEach(element => {
if (element.key.hasOwnProperty(property) && (flags.indexOf(element.key[property]) === -1)) {
flags.push(element.key[property]);
authorityList.push(element.key[property]);
}
});
return authorityList;
}
/*
* Adds login_hint to authorization URL which is used to pre-fill the username field of sign in page for the user if known ahead of time
* domain_hint can be one of users/organisations which when added skips the email based discovery process of the user
* domain_req utid received as part of the clientInfo
* login_req uid received as part of clientInfo
* @param {string} urlNavigate - Authentication request url
* @param {User} user - User for which the token is requested
* @ignore
* @hidden
*/
private addHintParameters(urlNavigate: string, user: User): string {
const userObject = user ? user : this.getUser();
if (userObject) {
const decodedClientInfo = userObject.userIdentifier.split(".");
const uid = Utils.base64DecodeStringUrlSafe(decodedClientInfo[0]);
const utid = Utils.base64DecodeStringUrlSafe(decodedClientInfo[1]);
if (userObject.sid && urlNavigate.indexOf(Constants.prompt_none) !== -1) {
if (!this.urlContainsQueryStringParameter(Constants.sid, urlNavigate) && !this.urlContainsQueryStringParameter(Constants.login_hint, urlNavigate)) {
urlNavigate += "&" + Constants.sid + "=" + encodeURIComponent(userObject.sid);
}
}
else {
if (!this.urlContainsQueryStringParameter(Constants.login_hint, urlNavigate) && userObject.displayableId && !Utils.isEmpty(userObject.displayableId)) {
urlNavigate += "&" + Constants.login_hint + "=" + encodeURIComponent(userObject.displayableId);
}
}
if (!Utils.isEmpty(uid) && !Utils.isEmpty(utid)) {
if (!this.urlContainsQueryStringParameter("domain_req", urlNavigate) && !Utils.isEmpty(utid)) {
urlNavigate += "&domain_req=" + encodeURIComponent(utid);
}
if (!this.urlContainsQueryStringParameter("login_req", urlNavigate) && !Utils.isEmpty(uid)) {
urlNavigate += "&login_req=" + encodeURIComponent(uid);
}
}
if (!this.urlContainsQueryStringParameter(Constants.domain_hint, urlNavigate) && !Utils.isEmpty(utid)) {
if (utid === Constants.consumersUtid) {
urlNavigate += "&" + Constants.domain_hint + "=" + encodeURIComponent(Constants.consumers);
} else {
urlNavigate += "&" + Constants.domain_hint + "=" + encodeURIComponent(Constants.organizations);
}
}
}
return urlNavigate;
}
/*
* Checks if the authorization endpoint URL contains query string parameters
* @ignore
* @hidden
*/
private urlContainsQueryStringParameter(name: string, url: string): boolean {
// regex to detect pattern of a ? or & followed by the name parameter and an equals character
const regex = new RegExp("[\\?&]" + name + "=");
return regex.test(url);
}