-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathMsalAuthProvider.ts
412 lines (332 loc) · 14.4 KB
/
MsalAuthProvider.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
import {
AuthenticationParameters,
AuthError,
AuthResponse,
ClientAuthError,
Configuration,
InteractionRequiredAuthError,
UserAgentApplication,
} from 'msal';
import { AnyAction, Store } from 'redux';
import { AccessTokenResponse } from './AccessTokenResponse';
import { AuthenticationActionCreators } from './AuthenticationActionCreators';
import { IdTokenResponse } from './IdTokenResponse';
import { IAccountInfo, IAuthProvider, IMsalAuthProviderConfig } from './interfaces';
import { Logger } from './Logger';
import { AuthenticationState, LoginType, TokenType } from './enums';
type AuthenticationStateHandler = (state: AuthenticationState) => void;
type ErrorHandler = (error: AuthError | null) => void;
type AccountInfoHandlers = (accountInfo: IAccountInfo | null) => void;
export class MsalAuthProvider extends UserAgentApplication implements IAuthProvider {
public authenticationState: AuthenticationState;
/**
* Gives access to the MSAL functionality for advanced usage.
*
* @deprecated The MsalAuthProvider class itself extends from UserAgentApplication and has the same functionality
*/
public UserAgentApplication: UserAgentApplication;
protected _reduxStore: Store;
protected _parameters: AuthenticationParameters;
protected _options: IMsalAuthProviderConfig;
protected _accountInfo: IAccountInfo | null;
protected _error: AuthError | null;
private _onAuthenticationStateHandlers = new Set<AuthenticationStateHandler>();
private _onAccountInfoHandlers = new Set<AccountInfoHandlers>();
private _onErrorHandlers = new Set<ErrorHandler>();
private _actionQueue: AnyAction[] = [];
constructor(
config: Configuration,
parameters: AuthenticationParameters,
options: IMsalAuthProviderConfig = {
loginType: LoginType.Popup,
tokenRefreshUri: window.location.origin,
},
) {
super(config);
// Required only for backward compatibility
this.UserAgentApplication = this as UserAgentApplication;
this.setAuthenticationParameters(parameters);
this.setProviderOptions(options);
this.initializeProvider();
}
public login = async (parameters?: AuthenticationParameters) => {
const params = parameters || this.getAuthenticationParameters();
// Clear any active authentication errors unless the code is executing from within
// the token renewal iframe
const error = this.getError();
if (error && error.errorCode !== 'block_token_requests') {
this.setError(null);
}
const providerOptions = this.getProviderOptions();
if (providerOptions.loginType === LoginType.Redirect) {
this.setAuthenticationState(AuthenticationState.InProgress);
try {
this.loginRedirect(params);
} catch (error) {
Logger.ERROR(error);
this.setError(error);
this.setAuthenticationState(AuthenticationState.Unauthenticated);
}
} else if (providerOptions.loginType === LoginType.Popup) {
try {
this.setAuthenticationState(AuthenticationState.InProgress);
await this.loginPopup(params);
} catch (error) {
Logger.ERROR(error);
this.setError(error);
this.setAuthenticationState(AuthenticationState.Unauthenticated);
}
await this.processLogin();
}
};
public logout = (): void => {
super.logout();
this.dispatchAction(AuthenticationActionCreators.logoutSuccessful());
};
public getAccountInfo = (): IAccountInfo | null => {
return this._accountInfo ? { ...this._accountInfo } : null;
};
public getAccessToken = async (parameters?: AuthenticationParameters): Promise<AccessTokenResponse> => {
const providerOptions = this.getProviderOptions();
// The parameters to be used when silently refreshing the token
const refreshParams = {
...(parameters || this.getAuthenticationParameters()),
// Use the redirectUri that was passed, otherwise use the configured tokenRefreshUri
redirectUri: (parameters && parameters.redirectUri) || providerOptions.tokenRefreshUri,
};
/* In this library, acquireTokenSilent is being called only when there is an accountInfo of an expired session.
* In a scenario where user interaction is required, username from the account info is passed as 'login_hint'
* parameter which redirects user to user's organization login page. So 'domain_hint' is not required to be
* passed for silent calls. Hence, the below code is to avoid sending domain_hint. This also solves the issue
* of multiple domain_hint param being added by the MSAL.js.
*/
if (refreshParams.extraQueryParameters && refreshParams.extraQueryParameters.domain_hint) {
delete refreshParams.extraQueryParameters.domain_hint;
}
try {
const response = await this.acquireTokenSilent(refreshParams);
this.handleAcquireTokenSuccess(response);
this.setAuthenticationState(AuthenticationState.Authenticated);
return new AccessTokenResponse(response);
} catch (error) {
// The parameters to be used if silent refresh failed, and a new login needs to be initiated
const loginParams = {
...(parameters || this.getAuthenticationParameters()),
};
this.dispatchAction(AuthenticationActionCreators.acquireAccessTokenError(error));
const response = await this.loginToRefreshToken(error, loginParams);
return new AccessTokenResponse(response);
}
};
public getIdToken = async (parameters?: AuthenticationParameters): Promise<IdTokenResponse> => {
const providerOptions = this.getProviderOptions();
const config = this.getCurrentConfiguration();
const clientId = config.auth.clientId;
// The parameters to be used when silently refreshing the token
const refreshParams = {
...(parameters || this.getAuthenticationParameters()),
// Use the redirectUri that was passed, otherwise use the configured tokenRefreshUri
redirectUri: (parameters && parameters.redirectUri) || providerOptions.tokenRefreshUri,
// Pass the clientId as the only scope to get a renewed IdToken if it has expired
scopes: [clientId],
};
/* In this library, acquireTokenSilent is being called only when there is an accountInfo of an expired session.
* In a scenario where user interaction is required, username from the account info is passed as 'login_hint'
* parameter which redirects user to user's organization login page. So 'domain_hint' is not required to be
* passed for silent calls. Hence, the below code is to avoid sending domain_hint. This also solves the issue
* of multiple domain_hint param being added by the MSAL.js.
*/
if (refreshParams.extraQueryParameters && refreshParams.extraQueryParameters.domain_hint) {
delete refreshParams.extraQueryParameters.domain_hint;
}
try {
const response = await this.acquireTokenSilent(refreshParams);
this.handleAcquireTokenSuccess(response);
this.setAuthenticationState(AuthenticationState.Authenticated);
return new IdTokenResponse(response);
} catch (error) {
// The parameters to be used if silent refresh failed, and a new login needs to be initiated
const loginParams = {
...(parameters || this.getAuthenticationParameters()),
};
// If the parameters do not specify a login hint and the user already has a session cached,
// prefer the cached user name to bypass the account selection process if possible
const account = this.getAccount();
if (account && (!parameters || !parameters.loginHint)) {
loginParams.loginHint = account.userName;
}
this.dispatchAction(AuthenticationActionCreators.acquireIdTokenError(error));
const response = await this.loginToRefreshToken(error, loginParams);
return new IdTokenResponse(response);
}
};
public getAuthenticationParameters = (): AuthenticationParameters => {
return { ...this._parameters };
};
public getError = () => {
return this._error ? { ...this._error } : null;
};
public setAuthenticationParameters = (parameters: AuthenticationParameters): void => {
this._parameters = { ...parameters };
};
public getProviderOptions = (): IMsalAuthProviderConfig => {
return { ...this._options };
};
public setProviderOptions = (options: IMsalAuthProviderConfig) => {
this._options = { ...options };
if (options.loginType === LoginType.Redirect) {
this.handleRedirectCallback(this.authenticationRedirectCallback);
}
};
public registerReduxStore = (store: Store): void => {
this._reduxStore = store;
while (this._actionQueue.length) {
const action = this._actionQueue.shift();
if (action) {
this.dispatchAction(action);
}
}
};
public registerAuthenticationStateHandler = (listener: AuthenticationStateHandler) => {
this._onAuthenticationStateHandlers.add(listener);
listener(this.authenticationState);
};
public unregisterAuthenticationStateHandler = (listener: AuthenticationStateHandler) => {
this._onAuthenticationStateHandlers.delete(listener);
};
public registerAcountInfoHandler = (listener: AccountInfoHandlers) => {
this._onAccountInfoHandlers.add(listener);
listener(this._accountInfo);
};
public unregisterAccountInfoHandler = (listener: AccountInfoHandlers) => {
this._onAccountInfoHandlers.delete(listener);
};
public registerErrorHandler = (listener: ErrorHandler) => {
this._onErrorHandlers.add(listener);
listener(this._error);
};
public unregisterErrorHandler = (listener: ErrorHandler) => {
this._onErrorHandlers.delete(listener);
};
private setError = (error: AuthError | null) => {
this._error = error ? { ...error } : null;
if (error) {
this.dispatchAction(AuthenticationActionCreators.loginError(error));
}
this._onErrorHandlers.forEach(listener => listener(this._error));
return { ...this._error };
};
private loginToRefreshToken = async (
error: AuthError,
parameters?: AuthenticationParameters,
): Promise<AuthResponse> => {
const providerOptions = this.getProviderOptions();
const params = parameters || this.getAuthenticationParameters();
if (error instanceof InteractionRequiredAuthError) {
if (providerOptions.loginType === LoginType.Redirect) {
this.acquireTokenRedirect(params);
// Nothing to return, the user is redirected to the login page
return new Promise<AuthResponse>(resolve => resolve());
}
try {
const response = await this.acquireTokenPopup(params);
this.handleAcquireTokenSuccess(response);
this.setAuthenticationState(AuthenticationState.Authenticated);
return response;
} catch (error) {
Logger.ERROR(error);
this.setError(error);
this.setAuthenticationState(AuthenticationState.Unauthenticated);
throw error;
}
} else {
Logger.ERROR(error as any);
this.setError(error);
this.setAuthenticationState(AuthenticationState.Unauthenticated);
throw error;
}
};
private authenticationRedirectCallback = (error: AuthError) => {
if (error) {
this.setError(error);
}
this.processLogin();
};
private initializeProvider = async () => {
this.dispatchAction(AuthenticationActionCreators.initializing());
await this.processLogin();
this.dispatchAction(AuthenticationActionCreators.initialized());
};
private processLogin = async () => {
if (this.getError()) {
this.handleLoginFailed();
this.setAuthenticationState(AuthenticationState.Unauthenticated);
} else if (this.getAccount()) {
try {
// If the IdToken has expired, refresh it. Otherwise use the cached token
await this.getIdToken();
this.handleLoginSuccess();
} catch (error) {
// Swallow the error if the user isn't authenticated, just set to Unauthenticated
if (!(error instanceof ClientAuthError && error.errorCode === 'user_login_error')) {
Logger.ERROR(error);
this.setError(error);
}
this.setAuthenticationState(AuthenticationState.Unauthenticated);
}
} else if (this.getLoginInProgress()) {
this.setAuthenticationState(AuthenticationState.InProgress);
} else {
this.setAuthenticationState(AuthenticationState.Unauthenticated);
}
};
private setAuthenticationState = (state: AuthenticationState): AuthenticationState => {
if (this.authenticationState !== state) {
this.authenticationState = state;
this.dispatchAction(AuthenticationActionCreators.authenticatedStateChanged(state));
this._onAuthenticationStateHandlers.forEach(listener => listener(state));
}
return this.authenticationState;
};
private setAccountInfo = (response: AuthResponse): IAccountInfo => {
const accountInfo: IAccountInfo = this.getAccountInfo() || ({ account: response.account } as IAccountInfo);
// Depending on the token type of the auth response, update the correct property
if (response.tokenType === TokenType.IdToken) {
accountInfo.jwtIdToken = response.idToken.rawIdToken;
} else if (response.tokenType === TokenType.AccessToken) {
accountInfo.jwtAccessToken = response.accessToken;
}
this._accountInfo = { ...accountInfo };
this._onAccountInfoHandlers.forEach(listener => listener(this._accountInfo));
return { ...this._accountInfo };
};
private dispatchAction = (action: AnyAction): void => {
if (this._reduxStore) {
this._reduxStore.dispatch(action);
} else {
this._actionQueue.push(action);
}
};
private handleAcquireTokenSuccess = (response: AuthResponse): void => {
this.setAccountInfo(response);
if (response.tokenType === TokenType.IdToken) {
const token = new IdTokenResponse(response);
this.dispatchAction(AuthenticationActionCreators.acquireIdTokenSuccess(token));
} else if (response.tokenType === TokenType.AccessToken) {
const token = new AccessTokenResponse(response);
this.dispatchAction(AuthenticationActionCreators.acquireAccessTokenSuccess(token));
}
};
private handleLoginFailed = (): void => {
const error = this.getError();
if (error) {
this.dispatchAction(AuthenticationActionCreators.loginFailed());
}
};
private handleLoginSuccess = (): void => {
const account = this.getAccountInfo();
if (account) {
this.dispatchAction(AuthenticationActionCreators.loginSuccessful(account));
}
};
}