/
UserAgentApplication.ts
2621 lines (2279 loc) · 97.7 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.
// Licensed under the MIT License.
import { AccessTokenCacheItem } from "./AccessTokenCacheItem";
import { AccessTokenKey } from "./AccessTokenKey";
import { AccessTokenValue } from "./AccessTokenValue";
import { ServerRequestParameters } from "./ServerRequestParameters";
import { Authority } from "./Authority";
import { ClientInfo } from "./ClientInfo";
import { Constants, SSOTypes, PromptState, BlacklistedEQParams, InteractionErrorType } from "./Constants";
import { IdToken } from "./IdToken";
import { Logger } from "./Logger";
import { Storage } from "./Storage";
import { Account } from "./Account";
import { Utils } from "./Utils";
import { AuthorityFactory } from "./AuthorityFactory";
import { Configuration, buildConfiguration } from "./Configuration";
import { AuthenticationParameters, validateClaimsRequest } from "./AuthenticationParameters";
import { StringDict } from "./MsalTypes";
import { ClientConfigurationError } from "./error/ClientConfigurationError";
import { AuthError } from "./error/AuthError";
import { ClientAuthError, ClientAuthErrorMessage } from "./error/ClientAuthError";
import { ServerError } from "./error/ServerError";
import { InteractionRequiredAuthError } from "./error/InteractionRequiredAuthError";
import { AuthResponse, buildResponseStateOnly } from "./AuthResponse";
// default authority
const DEFAULT_AUTHORITY = "https://login.microsoftonline.com/common";
/**
* Interface to handle iFrame generation, Popup Window creation and redirect handling
*/
declare global {
interface Window {
msal: Object;
CustomEvent: CustomEvent;
Event: Event;
activeRenewals: {};
renewStates: Array<string>;
callbackMappedToRenewStates : {};
promiseMappedToRenewStates: {};
openedWindows: Array<Window>;
requestType: string;
}
}
/**
* @hidden
* @ignore
* response_type from OpenIDConnect
* References: https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html & https://tools.ietf.org/html/rfc6749#section-4.2.1
* Since we support only implicit flow in this library, we restrict the response_type support to only 'token' and 'id_token'
*
*/
const ResponseTypes = {
id_token: "id_token",
token: "token",
id_token_token: "id_token token"
};
/**
* @hidden
* @ignore
*/
export interface CacheResult {
errorDesc: string;
token: string;
error: string;
}
/**
* @hidden
* @ignore
* Data type to hold information about state returned from the server
*/
export type ResponseStateInfo = {
state: string;
stateMatch: boolean;
requestType: string;
};
/**
* A type alias for an authResponseCallback function.
* {@link (authResponseCallback:type)}
* @param authErr error created for failure cases
* @param response response containing token strings in success cases, or just state value in error cases
*/
export type authResponseCallback = (authErr: AuthError, response?: AuthResponse) => void;
/**
* A type alias for a tokenReceivedCallback function.
* {@link (tokenReceivedCallback:type)}
* @returns response of type {@link (AuthResponse:type)}
* The function that will get the call back once this API is completed (either successfully or with a failure).
*/
export type tokenReceivedCallback = (response: AuthResponse) => void;
/**
* A type alias for a errorReceivedCallback function.
* {@link (errorReceivedCallback:type)}
* @returns response of type {@link (AuthError:class)}
* @returns {string} account state
*/
export type errorReceivedCallback = (authErr: AuthError, accountState: string) => void;
/**
* @hidden
* @ignore
* A wrapper to handle the token response/error within the iFrame always
*
* @param target
* @param propertyKey
* @param descriptor
*/
const resolveTokenOnlyIfOutOfIframe = (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
const tokenAcquisitionMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
return this.isInIframe()
? new Promise(() => {
return;
})
: tokenAcquisitionMethod.apply(this, args);
};
return descriptor;
};
/**
* UserAgentApplication class
*
* Object Instance that the developer can use to make loginXX OR acquireTokenXX functions
*/
export class UserAgentApplication {
// input Configuration by the developer/user
private config: Configuration;
// callbacks for token/error
private authResponseCallback: authResponseCallback = null;
private tokenReceivedCallback: tokenReceivedCallback = null;
private errorReceivedCallback: errorReceivedCallback = null;
// Added for readability as these params are very frequently used
private logger: Logger;
private clientId: string;
private inCookie: boolean;
// Cache and Account info referred across token grant flow
protected cacheStorage: Storage;
private account: Account;
// state variables
private loginInProgress: boolean;
private acquireTokenInProgress: boolean;
private silentAuthenticationState: string;
private silentLogin: boolean;
private redirectCallbacksSet: boolean;
// Authority Functionality
protected authorityInstance: Authority;
/**
* setter for the authority URL
* @param {string} authority
*/
// If the developer passes an authority, create an instance
public set authority(val) {
this.authorityInstance = AuthorityFactory.CreateInstance(val, this.config.auth.validateAuthority);
}
/**
* Method to manage the authority URL.
*
* @returns {string} authority
*/
public get authority(): string {
return this.authorityInstance.CanonicalAuthority;
}
/**
* Get the current authority instance from the MSAL configuration object
*
* @returns {@link Authority} authority instance
*/
public getAuthorityInstance(): Authority {
return this.authorityInstance;
}
/**
* @constructor
* Constructor for the UserAgentApplication used to instantiate the UserAgentApplication object
*
* Important attributes in the Configuration object for auth are:
* - clientID: the application ID of your application.
* You can obtain one by registering your application with our Application registration portal : https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredAppsPreview
* - authority: the authority URL for your application.
*
* In Azure AD, authority is a URL indicating the Azure active directory that MSAL uses to obtain tokens.
* It is of the form https://login.microsoftonline.com/<Enter_the_Tenant_Info_Here>.
* If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
* If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
* If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
* To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
*
*
* In Azure B2C, authority is of the form https://<instance>/tfp/<tenant>/<policyName>/
* @param {@link (Configuration:type)} configuration object for the MSAL UserAgentApplication instance
*/
constructor(configuration: Configuration) {
// Set the Configuration
this.config = buildConfiguration(configuration);
// Set the callback boolean
this.redirectCallbacksSet = false;
this.logger = this.config.system.logger;
this.clientId = this.config.auth.clientId;
this.inCookie = this.config.cache.storeAuthStateInCookie;
// if no authority is passed, set the default: "https://login.microsoftonline.com/common"
this.authority = this.config.auth.authority || DEFAULT_AUTHORITY;
// track login and acquireToken in progress
this.loginInProgress = false;
this.acquireTokenInProgress = false;
// cache keys msal - typescript throws an error if any value other than "localStorage" or "sessionStorage" is passed
try {
this.cacheStorage = new Storage(this.config.cache.cacheLocation);
} catch (e) {
throw ClientConfigurationError.createInvalidCacheLocationConfigError(this.config.cache.cacheLocation);
}
// Initialize window handling code
window.openedWindows = [];
window.activeRenewals = {};
window.renewStates = [];
window.callbackMappedToRenewStates = { };
window.promiseMappedToRenewStates = { };
window.msal = this;
const urlHash = window.location.hash;
const isCallback = this.isCallback(urlHash);
// On the server 302 - Redirect, handle this
if (!this.config.framework.isAngular) {
if (isCallback) {
this.handleAuthenticationResponse(urlHash);
}
}
}
//#region Redirect Callbacks
/**
* @hidden
* @ignore
* Set the callback functions for the redirect flow to send back the success or error object.
* @param {@link (tokenReceivedCallback:type)} successCallback - Callback which contains the AuthResponse object, containing data from the server.
* @param {@link (errorReceivedCallback:type)} errorCallback - Callback which contains a AuthError object, containing error data from either the server
* or the library, depending on the origin of the error.
*/
handleRedirectCallback(tokenReceivedCallback: tokenReceivedCallback, errorReceivedCallback: errorReceivedCallback): void;
handleRedirectCallback(authCallback: authResponseCallback): void;
handleRedirectCallback(authOrTokenCallback: authResponseCallback | tokenReceivedCallback, errorReceivedCallback?: errorReceivedCallback): void {
if (!authOrTokenCallback) {
this.redirectCallbacksSet = false;
throw ClientConfigurationError.createInvalidCallbackObjectError(authOrTokenCallback);
}
// Set callbacks
if (errorReceivedCallback) {
this.tokenReceivedCallback = authOrTokenCallback as tokenReceivedCallback;
this.errorReceivedCallback = errorReceivedCallback;
this.logger.warning("This overload for callback is deprecated - please change the format of the callbacks to a single callback as shown: (err: AuthError, response: AuthResponse).");
} else {
this.authResponseCallback = authOrTokenCallback as authResponseCallback;
}
this.redirectCallbacksSet = true;
// On the server 302 - Redirect, handle this
if (!this.config.framework.isAngular) {
const cachedHash = this.cacheStorage.getItem(Constants.urlHash);
if (cachedHash) {
this.processCallBack(cachedHash, null);
}
}
}
private redirectSuccessHandler(response: AuthResponse) : void {
if (this.errorReceivedCallback) {
this.tokenReceivedCallback(response);
} else if (this.authResponseCallback) {
this.authResponseCallback(null, response);
}
}
private redirectErrorHandler(authErr: AuthError, response: AuthResponse) : void {
if (this.errorReceivedCallback) {
this.errorReceivedCallback(authErr, response.accountState);
} else {
this.authResponseCallback(authErr, response);
}
}
//#endregion
//#region Redirect Flow
/**
* Use when initiating the login process by redirecting the user's browser to the authorization endpoint.
* @param {@link (AuthenticationParameters:type)}
*/
loginRedirect(request?: AuthenticationParameters): void {
// Throw error if callbacks are not set before redirect
if (!this.redirectCallbacksSet) {
throw ClientConfigurationError.createRedirectCallbacksNotSetError();
}
// Creates navigate url; saves value in cache; redirect user to AAD
if (this.loginInProgress) {
this.redirectErrorHandler(ClientAuthError.createLoginInProgressError(), buildResponseStateOnly(request && request.state));
return;
}
// if extraScopesToConsent is passed, append them to the login request
let scopes: Array<string> = this.appendScopes(request);
// Validate and filter scopes (the validate function will throw if validation fails)
this.validateInputScope(scopes, false);
const account: Account = this.getAccount();
// defer queryParameters generation to Helper if developer passes account/sid/login_hint
if (Utils.isSSOParam(request)) {
// if account is not provided, we pass null
this.loginRedirectHelper(account, request, scopes);
}
// else handle the library data
else {
// extract ADAL id_token if exists
let adalIdToken = this.extractADALIdToken();
// silent login if ADAL id_token is retrieved successfully - SSO
if (adalIdToken && !scopes) {
this.logger.info("ADAL's idToken exists. Extracting login information from ADAL's idToken ");
let tokenRequest: AuthenticationParameters = this.buildIDTokenRequest(request);
this.silentLogin = true;
this.acquireTokenSilent(tokenRequest).then(response => {
this.silentLogin = false;
this.logger.info("Unified cache call is successful");
if (this.redirectCallbacksSet) {
this.redirectSuccessHandler(response);
}
return;
}, (error) => {
this.silentLogin = false;
this.logger.error("Error occurred during unified cache ATS");
// call the loginRedirectHelper later with no user account context
this.loginRedirectHelper(null, request, scopes);
});
}
// else proceed to login
else {
// call the loginRedirectHelper later with no user account context
this.loginRedirectHelper(null, request, scopes);
}
}
}
/**
* @hidden
* @ignore
* Helper function to loginRedirect
*
* @param account
* @param AuthenticationParameters
* @param scopes
*/
private loginRedirectHelper(account: Account, request?: AuthenticationParameters, scopes?: Array<string>) {
// Track login in progress
this.loginInProgress = true;
this.authorityInstance.resolveEndpointsAsync().then(() => {
// create the Request to be sent to the Server
let serverAuthenticationRequest = new ServerRequestParameters(
this.authorityInstance,
this.clientId, scopes,
ResponseTypes.id_token,
this.getRedirectUri(),
request && request.state
);
// populate QueryParameters (sid/login_hint/domain_hint) and any other extraQueryParameters set by the developer
serverAuthenticationRequest = this.populateQueryParams(account, request, serverAuthenticationRequest);
// if the user sets the login start page - angular only??
let loginStartPage = this.cacheStorage.getItem(Constants.angularLoginRequest);
if (!loginStartPage || loginStartPage === "") {
loginStartPage = window.location.href;
} else {
this.cacheStorage.setItem(Constants.angularLoginRequest, "");
}
this.updateCacheEntries(serverAuthenticationRequest, account, loginStartPage);
// build URL to navigate to proceed with the login
let urlNavigate = serverAuthenticationRequest.createNavigateUrl(scopes) + Constants.response_mode_fragment;
// Redirect user to login URL
this.promptUser(urlNavigate);
}).catch((err) => {
this.logger.warning("could not resolve endpoints");
this.redirectErrorHandler(ClientAuthError.createEndpointResolutionError(err.toString), buildResponseStateOnly(request && request.state));
});
}
/**
* Use when you want to obtain an access_token for your API by redirecting the user's browser window to the authorization endpoint.
* @param {@link (AuthenticationParameters:type)}
*
* To renew idToken, please pass clientId as the only scope in the Authentication Parameters
*/
acquireTokenRedirect(request: AuthenticationParameters): void {
if (!request) {
throw ClientConfigurationError.createEmptyRequestError();
}
// Throw error if callbacks are not set before redirect
if (!this.redirectCallbacksSet) {
throw ClientConfigurationError.createRedirectCallbacksNotSetError();
}
// Validate and filter scopes (the validate function will throw if validation fails)
this.validateInputScope(request.scopes, true);
// Get the account object if a session exists
const account: Account = request.account || this.getAccount();
// If already in progress, do not proceed
if (this.acquireTokenInProgress) {
this.redirectErrorHandler(ClientAuthError.createAcquireTokenInProgressError(), buildResponseStateOnly(this.getAccountState(request.state)));
return;
}
// If no session exists, prompt the user to login.
if (!account && !(request.sid || request.loginHint)) {
this.logger.info("User login is required");
throw ClientAuthError.createUserLoginRequiredError();
}
let serverAuthenticationRequest: ServerRequestParameters;
const acquireTokenAuthority = request.authority ? AuthorityFactory.CreateInstance(request.authority, this.config.auth.validateAuthority) : this.authorityInstance;
// Track the acquireToken progress
this.acquireTokenInProgress = true;
acquireTokenAuthority.resolveEndpointsAsync().then(() => {
// On Fulfillment
const responseType = this.getTokenType(account, request.scopes, false);
serverAuthenticationRequest = new ServerRequestParameters(
acquireTokenAuthority,
this.clientId,
request.scopes,
responseType,
this.getRedirectUri(),
request.state
);
this.updateCacheEntries(serverAuthenticationRequest, account);
// populate QueryParameters (sid/login_hint/domain_hint) and any other extraQueryParameters set by the developer
serverAuthenticationRequest = this.populateQueryParams(account, request, serverAuthenticationRequest);
// Construct urlNavigate
let urlNavigate = serverAuthenticationRequest.createNavigateUrl(request.scopes) + Constants.response_mode_fragment;
// set state in cache and redirect to urlNavigate
if (urlNavigate) {
this.cacheStorage.setItem(Constants.stateAcquireToken, serverAuthenticationRequest.state, this.inCookie);
window.location.replace(urlNavigate);
}
}).catch((err) => {
this.logger.warning("could not resolve endpoints");
this.redirectErrorHandler(ClientAuthError.createEndpointResolutionError(err.toString), buildResponseStateOnly(request.state));
});
}
/**
* @hidden
* @ignore
* Checks if the redirect response is received from the STS. In case of redirect, the url fragment has either id_token, access_token or error.
* @param {string} hash - Hash passed from redirect page.
* @returns {Boolean} - true if response contains id_token, access_token or error, false otherwise.
*/
// TODO - rename this, the name is confusing
isCallback(hash: string): boolean {
hash = this.getHash(hash);
const parameters = Utils.deserialize(hash);
return (
parameters.hasOwnProperty(Constants.errorDescription) ||
parameters.hasOwnProperty(Constants.error) ||
parameters.hasOwnProperty(Constants.accessToken) ||
parameters.hasOwnProperty(Constants.idToken)
);
}
//#endregion
//#region Popup Flow
/**
* Use when initiating the login process via opening a popup window in the user's browser
*
* @param {@link (AuthenticationParameters:type)}
*
* @returns {Promise.<AuthResponse>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object
*/
loginPopup(request?: AuthenticationParameters): Promise<AuthResponse> {
// Creates navigate url; saves value in cache; redirect user to AAD
return new Promise<AuthResponse>((resolve, reject) => {
// Fail if login is already in progress
if (this.loginInProgress) {
return reject(ClientAuthError.createLoginInProgressError());
}
// if extraScopesToConsent is passed, append them to the login request
let scopes: Array<string> = this.appendScopes(request);
// Validate and filter scopes (the validate function will throw if validation fails)
this.validateInputScope(scopes, false);
let account = this.getAccount();
// add the prompt parameter to the 'extraQueryParameters' if passed
if (Utils.isSSOParam(request)) {
// if account is not provided, we pass null
this.loginPopupHelper(account, resolve, reject, request, scopes);
}
// else handle the library data
else {
// Extract ADAL id_token if it exists
let adalIdToken = this.extractADALIdToken();
// silent login if ADAL id_token is retrieved successfully - SSO
if (adalIdToken && !scopes) {
this.logger.info("ADAL's idToken exists. Extracting login information from ADAL's idToken ");
let tokenRequest: AuthenticationParameters = this.buildIDTokenRequest(request);
this.silentLogin = true;
this.acquireTokenSilent(tokenRequest)
.then(response => {
this.silentLogin = false;
this.logger.info("Unified cache call is successful");
resolve(response);
}, (error) => {
this.silentLogin = false;
this.logger.error("Error occurred during unified cache ATS");
this.loginPopupHelper(null, resolve, reject, request, scopes);
});
}
// else proceed with login
else {
this.loginPopupHelper(null, resolve, reject, request, scopes);
}
}
});
}
/**
* @hidden
* Helper function to loginPopup
*
* @param account
* @param request
* @param resolve
* @param reject
* @param scopes
*/
private loginPopupHelper(account: Account, resolve: any, reject: any, request?: AuthenticationParameters, scopes?: Array<string>) {
if (!scopes) {
scopes = [this.clientId];
}
const scope = scopes.join(" ").toLowerCase();
// Generate a popup window
const popUpWindow = this.openWindow("about:blank", "_blank", 1, this, resolve, reject);
if (!popUpWindow) {
// We pass reject in openWindow, we reject there during an error
return;
}
// Track login progress
this.loginInProgress = true;
// Resolve endpoint
this.authorityInstance.resolveEndpointsAsync().then(() => {
let serverAuthenticationRequest = new ServerRequestParameters(this.authorityInstance, this.clientId, scopes, ResponseTypes.id_token, this.getRedirectUri(), request && request.state);
// populate QueryParameters (sid/login_hint/domain_hint) and any other extraQueryParameters set by the developer;
serverAuthenticationRequest = this.populateQueryParams(account, request, serverAuthenticationRequest);
this.updateCacheEntries(serverAuthenticationRequest, account, window.location.href);
// Cache the state, nonce, and login request data
this.cacheStorage.setItem(Constants.loginRequest, window.location.href, this.inCookie);
this.cacheStorage.setItem(Constants.loginError, "");
this.cacheStorage.setItem(Constants.nonceIdToken, serverAuthenticationRequest.nonce, this.inCookie);
this.cacheStorage.setItem(Constants.msalError, "");
this.cacheStorage.setItem(Constants.msalErrorDescription, "");
// cache authorityKey
this.setAuthorityCache(serverAuthenticationRequest.state, this.authority);
// Build the URL to navigate to in the popup window
let urlNavigate = serverAuthenticationRequest.createNavigateUrl(scopes) + Constants.response_mode_fragment;
window.renewStates.push(serverAuthenticationRequest.state);
window.requestType = Constants.login;
// Register callback to capture results from server
this.registerCallback(serverAuthenticationRequest.state, scope, resolve, reject);
// Navigate url in popupWindow
if (popUpWindow) {
this.logger.infoPii("Navigated Popup window to:" + urlNavigate);
popUpWindow.location.href = urlNavigate;
}
}, () => {
// Endpoint resolution failure error
this.logger.info(ClientAuthErrorMessage.endpointResolutionError.code + ":" + ClientAuthErrorMessage.endpointResolutionError.desc);
this.cacheStorage.setItem(Constants.msalError, ClientAuthErrorMessage.endpointResolutionError.code);
this.cacheStorage.setItem(Constants.msalErrorDescription, ClientAuthErrorMessage.endpointResolutionError.desc);
// reject that is passed in - REDO this in the subsequent refactor, passing reject is confusing
if (reject) {
reject(ClientAuthError.createEndpointResolutionError());
}
// Close the popup window
if (popUpWindow) {
popUpWindow.close();
}
// this is an all catch for any failure for the above code except the specific 'reject' call
}).catch((err) => {
this.logger.warning("could not resolve endpoints");
reject(ClientAuthError.createEndpointResolutionError(err.toString));
});
}
/**
* Use when you want to obtain an access_token for your API via opening a popup window in the user's browser
* @param {@link AuthenticationParameters}
*
* To renew idToken, please pass clientId as the only scope in the Authentication Parameters
* @returns {Promise.<AuthResponse>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object
*/
acquireTokenPopup(request: AuthenticationParameters): Promise<AuthResponse> {
if (!request) {
throw ClientConfigurationError.createEmptyRequestError();
}
return new Promise<AuthResponse>((resolve, reject) => {
// Validate and filter scopes (the validate function will throw if validation fails)
this.validateInputScope(request.scopes, true);
const scope = request.scopes.join(" ").toLowerCase();
// Get the account object if a session exists
const account: Account = request.account || this.getAccount();
// If already in progress, throw an error and reject the request
if (this.acquireTokenInProgress) {
return reject(ClientAuthError.createAcquireTokenInProgressError());
}
// If no session exists, prompt the user to login.
if (!account && !(request.sid || request.loginHint)) {
this.logger.info("User login is required");
return reject(ClientAuthError.createUserLoginRequiredError());
}
// track the acquireToken progress
this.acquireTokenInProgress = true;
let serverAuthenticationRequest: ServerRequestParameters;
const acquireTokenAuthority = request.authority ? AuthorityFactory.CreateInstance(request.authority, this.config.auth.validateAuthority) : this.authorityInstance;
// Open the popup window
const popUpWindow = this.openWindow("about:blank", "_blank", 1, this, resolve, reject);
if (!popUpWindow) {
// We pass reject to openWindow, so we are rejecting there.
return;
}
acquireTokenAuthority.resolveEndpointsAsync().then(() => {
// On fullfillment
const responseType = this.getTokenType(account, request.scopes, false);
serverAuthenticationRequest = new ServerRequestParameters(
acquireTokenAuthority,
this.clientId,
request.scopes,
responseType,
this.getRedirectUri(),
request.state
);
// populate QueryParameters (sid/login_hint/domain_hint) and any other extraQueryParameters set by the developer
serverAuthenticationRequest = this.populateQueryParams(account, request, serverAuthenticationRequest);
this.updateCacheEntries(serverAuthenticationRequest, account);
// Construct the urlNavigate
let urlNavigate = serverAuthenticationRequest.createNavigateUrl(request.scopes) + Constants.response_mode_fragment;
window.renewStates.push(serverAuthenticationRequest.state);
window.requestType = Constants.renewToken;
this.registerCallback(serverAuthenticationRequest.state, scope, resolve, reject);
// open popup window to urlNavigate
if (popUpWindow) {
popUpWindow.location.href = urlNavigate;
}
}, () => {
// Endpoint resolution failure error
this.logger.info(ClientAuthErrorMessage.endpointResolutionError.code + ":" + ClientAuthErrorMessage.endpointResolutionError.desc);
this.cacheStorage.setItem(Constants.msalError, ClientAuthErrorMessage.endpointResolutionError.code);
this.cacheStorage.setItem(Constants.msalErrorDescription, ClientAuthErrorMessage.endpointResolutionError.desc);
// reject that is passed in - REDO this in the subsequent refactor, passing reject is confusing
if (reject) {
reject(ClientAuthError.createEndpointResolutionError());
}
if (popUpWindow) {
popUpWindow.close();
}
// this is an all catch for any failure for the above code except the specific 'reject' call
}).catch((err) => {
this.logger.warning("could not resolve endpoints");
reject(ClientAuthError.createEndpointResolutionError(err.toString()));
});
});
}
/**
* @hidden
*
* 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.
*
* @param urlNavigate
* @param title
* @param interval
* @param instance
* @param resolve
* @param reject
* @ignore
*/
private openWindow(urlNavigate: string, title: string, interval: number, instance: this, resolve?: Function, reject?: Function): Window {
// Generate a popup window
var popupWindow: Window;
try {
popupWindow = this.openPopup(urlNavigate, title, Constants.popUpWidth, Constants.popUpHeight);
} catch (e) {
instance.loginInProgress = false;
instance.acquireTokenInProgress = false;
this.logger.info(ClientAuthErrorMessage.popUpWindowError.code + ":" + ClientAuthErrorMessage.popUpWindowError.desc);
this.cacheStorage.setItem(Constants.msalError, ClientAuthErrorMessage.popUpWindowError.code);
this.cacheStorage.setItem(Constants.msalErrorDescription, ClientAuthErrorMessage.popUpWindowError.desc);
if (reject) {
reject(ClientAuthError.createPopupWindowError());
}
return null;
}
// Push popup window handle onto stack for tracking
window.openedWindows.push(popupWindow);
const pollTimer = window.setInterval(() => {
// If popup closed or login in progress, cancel login
if (popupWindow && popupWindow.closed && (instance.loginInProgress || instance.acquireTokenInProgress)) {
if (reject) {
reject(ClientAuthError.createUserCancelledError());
}
window.clearInterval(pollTimer);
if (this.config.framework.isAngular) {
this.broadcast("msal:popUpClosed", ClientAuthErrorMessage.userCancelledError.code + Constants.resourceDelimiter + ClientAuthErrorMessage.userCancelledError.desc);
return;
}
instance.loginInProgress = false;
instance.acquireTokenInProgress = false;
}
try {
const popUpWindowLocation = popupWindow.location;
// If the popup hash changes, close the popup window
if (popUpWindowLocation.href.indexOf(this.getRedirectUri()) !== -1) {
window.clearInterval(pollTimer);
instance.loginInProgress = false;
instance.acquireTokenInProgress = false;
this.logger.info("Closing popup window");
// TODO: Check how this can be extracted for any framework specific code?
if (this.config.framework.isAngular) {
this.broadcast("msal:popUpHashChanged", popUpWindowLocation.hash);
for (let 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;
}
/**
* @hidden
*
* Configures popup window for login.
*
* @param urlNavigate
* @param title
* @param popUpWidth
* @param popUpHeight
* @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;
// open the window
const popupWindow = window.open(urlNavigate, title, "width=" + popUpWidth + ", height=" + popUpHeight + ", top=" + top + ", left=" + left);
if (!popupWindow) {
throw ClientAuthError.createPopupWindowError();
}
if (popupWindow.focus) {
popupWindow.focus();
}
return popupWindow;
} catch (e) {
this.logger.error("error opening popup " + e.message);
this.loginInProgress = false;
this.acquireTokenInProgress = false;
throw ClientAuthError.createPopupWindowError(e.toString());
}
}
//#endregion
//#region Silent Flow
/**
* Use this function to obtain a token before every call to the API / resource provider
*
* MSAL return's a cached token when available
* Or it send's a request to the STS to obtain a new token using a hidden iframe.
*
* @param {@link AuthenticationParameters}
*
* To renew idToken, please pass clientId as the only scope in the Authentication Parameters
* @returns {Promise.<AuthResponse>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object
*
*/
@resolveTokenOnlyIfOutOfIframe
acquireTokenSilent(request: AuthenticationParameters): Promise<AuthResponse> {
if (!request) {
throw ClientConfigurationError.createEmptyRequestError();
}
return new Promise<AuthResponse>((resolve, reject) => {
// Validate and filter scopes (the validate function will throw if validation fails)
this.validateInputScope(request.scopes, true);
const scope = request.scopes.join(" ").toLowerCase();
// if the developer passes an account give him the priority
const account: Account = request.account || this.getAccount();
// extract if there is an adalIdToken stashed in the cache
const adalIdToken = this.cacheStorage.getItem(Constants.adalIdToken);
//if there is no account logged in and no login_hint/sid is passed in the request
if (!account && !(request.sid || request.loginHint) && Utils.isEmpty(adalIdToken) ) {
this.logger.info("User login is required");
return reject(ClientAuthError.createUserLoginRequiredError());
}
const responseType = this.getTokenType(account, request.scopes, true);
let serverAuthenticationRequest = new ServerRequestParameters(
AuthorityFactory.CreateInstance(request.authority, this.config.auth.validateAuthority),
this.clientId,
request.scopes,
responseType,
this.getRedirectUri(),
request && request.state
);
// populate QueryParameters (sid/login_hint/domain_hint) and any other extraQueryParameters set by the developer
if (Utils.isSSOParam(request) || account) {
serverAuthenticationRequest = this.populateQueryParams(account, request, serverAuthenticationRequest);
}
//if user didn't pass login_hint/sid and adal's idtoken is present, extract the login_hint from the adalIdToken
else if (!account && !Utils.isEmpty(adalIdToken)) {
// if adalIdToken exists, extract the SSO info from the same
const adalIdTokenObject = Utils.extractIdToken(adalIdToken);
this.logger.verbose("ADAL's idToken exists. Extracting login information from ADAL's idToken ");
serverAuthenticationRequest = this.populateQueryParams(account, null, serverAuthenticationRequest, adalIdTokenObject);
}
let userContainedClaims = request.claimsRequest || serverAuthenticationRequest.claimsValue;
let authErr: AuthError;
let cacheResultResponse;
if (!userContainedClaims && !request.forceRefresh) {
try {
cacheResultResponse = this.getCachedToken(serverAuthenticationRequest, account);
} catch (e) {
authErr = e;
}
}
// resolve/reject based on cacheResult
if (cacheResultResponse) {
this.logger.info("Token is already in cache for scope:" + scope);
resolve(cacheResultResponse);
return null;
}
else if (authErr) {
this.logger.infoPii(authErr.errorCode + ":" + authErr.errorMessage);
reject(authErr);
return null;
}
// else proceed with login
else {
if (userContainedClaims) {
this.logger.verbose("Skipped cache lookup since claims were given.");
} else if (request.forceRefresh) {
this.logger.verbose("Skipped cache lookup since request.forceRefresh option was set to true");
} else {
this.logger.verbose("Token is not in cache for scope:" + scope);
}
// Cache result can return null if cache is empty. In that case, set authority to default value if no authority is passed to the api.
if (!serverAuthenticationRequest.authorityInstance) {
serverAuthenticationRequest.authorityInstance = request.authority ? AuthorityFactory.CreateInstance(request.authority, this.config.auth.validateAuthority) : this.authorityInstance;
}
// cache miss
return serverAuthenticationRequest.authorityInstance.resolveEndpointsAsync()
.then(() => {
// refresh attempt with iframe
// Already renewing for this scope, callback when we get the token.
if (window.activeRenewals[scope]) {
this.logger.verbose("Renew token for scope: " + scope + " is in progress. Registering callback");
// Active renewals contains the state for each renewal.
this.registerCallback(window.activeRenewals[scope], scope, resolve, reject);
}
else {
if (request.scopes && request.scopes.indexOf(this.clientId) > -1 && request.scopes.length === 1) {
// App uses idToken to send to api endpoints
// Default scope is tracked as clientId to store this token
this.logger.verbose("renewing idToken");
this.renewIdToken(request.scopes, resolve, reject, account, serverAuthenticationRequest);
} else {
// renew access token
this.logger.verbose("renewing accesstoken");
this.renewToken(request.scopes, resolve, reject, account, serverAuthenticationRequest);
}