-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathauth-provider-iam.tsx
More file actions
423 lines (387 loc) · 13 KB
/
Copy pathauth-provider-iam.tsx
File metadata and controls
423 lines (387 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
/**
* Copyright 2025 Cisco Systems, Inc. and its affiliates
* SPDX-License-Identifier: Apache-2.0
*/
import React, {useMemo} from 'react';
import OktaAuth, {SignoutOptions, TokenResponse} from '@okta/okta-auth-js';
import {createOktaInstance, getRelativeUrl, getSearchParams} from '@/utils/okta';
import {AuthConfigIAM, AuthInfo, Tenant, User} from '@/types/okta';
import {Loading} from '@/components/ui/loading';
import {AuthError} from '@/components/router/auth-error';
import {getAuthConfig} from '@/utils/get-auth-config';
import AuthContextIAM from './auth-context-iam';
import {ACCESS_TOKEN_EXPIRED_EVENT, ACCESS_TOKEN_NAME, defaultAuthConfigOptions} from '@/constants/okta';
const AuthProviderIAM: React.FC<React.PropsWithChildren> = ({children}) => {
const [loading, setLoading] = React.useState<boolean>(true);
const [authInfo, setAuthInfo] = React.useState<AuthInfo | undefined>(undefined);
const [handleError, setHandleError] = React.useState<Error | null>(null);
const [controller, setController] = React.useState<boolean | undefined>(undefined);
const authConfig: AuthConfigIAM = useMemo(() => {
return {
...(getAuthConfig() as AuthConfigIAM)
};
}, []);
const newAuthConfig: AuthConfigIAM = React.useMemo(() => {
return {
...authConfig,
iamUI: authConfig?.iamUI?.trim().replace(/\/+$/g, ''),
productId: authConfig?.productId?.trim(),
oktaClient: authConfig.oktaClient?.trim(),
oktaIssuer: authConfig.oktaIssuer?.trim(),
configOptions: {...defaultAuthConfigOptions, ...authConfig?.configOptions}
};
}, [authConfig]);
const isValidOktaConfig: boolean = React.useMemo(() => {
if (
!newAuthConfig?.oktaIssuer ||
newAuthConfig?.oktaIssuer === '' ||
!newAuthConfig?.oktaClient ||
newAuthConfig?.oktaClient === ''
) {
return false;
}
return true;
}, [newAuthConfig]);
const isValidConfig: boolean = React.useMemo(() => {
if (
!newAuthConfig?.iamApi ||
newAuthConfig?.iamApi === '' ||
!newAuthConfig?.iamUI ||
newAuthConfig?.iamUI === '' ||
!newAuthConfig?.productId ||
newAuthConfig?.productId === ''
) {
return false;
}
return true;
}, [newAuthConfig]);
const oktaInstance: OktaAuth | null = React.useMemo(() => {
if (!isValidOktaConfig) {
return null;
}
return createOktaInstance({
issuer: newAuthConfig?.oktaIssuer,
clientId: newAuthConfig?.oktaClient,
config: newAuthConfig.configOptions
});
}, [newAuthConfig, isValidOktaConfig]);
const isAutoRenew = newAuthConfig?.configOptions?.renew === 'auto';
const searchParams = getSearchParams();
const setCredentials = (newAuthInfo: AuthInfo) => {
return new Promise((resolve, reject) => {
try {
if (newAuthInfo?.accessToken && newAuthInfo?.idToken && newAuthInfo?.userAuthInfo) {
const {accessToken, idToken, refreshToken, userAuthInfo, isAuthenticated} = newAuthInfo;
const user: User = {};
const tenant: Tenant = {};
if (userAuthInfo?.first_name && userAuthInfo?.last_name) {
user.name = `${userAuthInfo.first_name} ${userAuthInfo.last_name}`;
}
if (accessToken?.claims?.sub) {
user.username = accessToken?.claims?.sub;
}
if (accessToken?.claims?.tenant_name) {
tenant.id = accessToken.claims.tenant as string;
tenant.name = accessToken.claims.tenant_name as string;
} else if (idToken?.claims?.tenant_name) {
tenant.id = idToken.claims.tenant as string;
tenant.name = idToken.claims.tenant_name as string;
}
user.tenant = tenant;
if (accessToken?.claims?.product_roles) {
if (typeof accessToken.claims.product_roles === 'string') {
user.productRole = accessToken.claims.product_roles;
} else if (Array.isArray(accessToken.claims.product_roles)) {
user.allProductRoles = accessToken.claims.product_roles as string[];
}
} else if (idToken.claims.product_roles) {
if (typeof idToken.claims.product_roles === 'string') {
user.productRole = idToken.claims.product_roles;
} else if (Array.isArray(idToken.claims.product_roles)) {
user.allProductRoles = idToken.claims.product_roles as string[];
}
}
const isCustomerSupport =
(accessToken?.claims?.customer_support as boolean | undefined) ||
(idToken?.claims?.customer_support as boolean | undefined);
if (isCustomerSupport) {
oktaInstance?.tokenManager.removeRefreshToken();
}
user.isCustomerSupport = isCustomerSupport;
setAuthInfo({
accessToken,
idToken,
refreshToken: isCustomerSupport ? undefined : refreshToken,
isAuthenticated,
user,
userAuthInfo: undefined
});
setController(true);
resolve({});
}
reject(new Error('No accessToken, idToken or userAuthInfo found in newAuthInfo.'));
} catch (error) {
console.debug(error);
reject(new Error('Error on setCredentials.'));
}
});
};
const cleanCredentials = () => {
try {
setController(false);
setAuthInfo(undefined);
} catch (error) {
console.error(error);
}
};
const logout = async (logoutOptions: void | SignoutOptions = {}) => {
try {
if (isAutoRenew) {
await oktaInstance?.stop();
}
await oktaInstance?.signOut(logoutOptions || {});
oktaInstance?.tokenManager.clear();
} catch (error) {
console.error(error);
}
};
const login = () => {
try {
const queryParams = new URLSearchParams({
...(newAuthConfig?.configOptions?.redirectUri
? {redirectUri: newAuthConfig?.configOptions?.redirectUri?.trim()}
: {})
});
window.location.href = `${newAuthConfig?.iamUI}/${newAuthConfig?.productId}/login?${queryParams.toString()}`;
} catch (error) {
console.error(error);
setHandleError(new Error('login.'));
}
};
const register = () => {
try {
const queryParams = new URLSearchParams({
...(newAuthConfig?.configOptions?.redirectUri
? {redirectUri: newAuthConfig?.configOptions?.redirectUri?.trim()}
: {})
});
window.location.href = `${newAuthConfig?.iamUI}/${newAuthConfig?.productId}/register?${queryParams.toString()}`;
} catch (error) {
console.error(error);
setHandleError(new Error('register.'));
}
};
const getAndSetTokens = () => {
// eslint-disable-next-line no-async-promise-executor
return new Promise<TokenResponse>(async (resolve, reject) => {
try {
if (oktaInstance?.isLoginRedirect()) {
const tokenResponse = await oktaInstance?.token?.parseFromUrl();
if (tokenResponse?.tokens) {
oktaInstance?.tokenManager?.setTokens(tokenResponse.tokens);
resolve(tokenResponse);
}
}
reject(new Error('No tokens found in getAndSetTokens.'));
} catch (error) {
console.debug(error);
reject(new Error('Error on getAndSetTokens.'));
}
});
};
const onAccessTokenExpired = () => {
return oktaInstance?.tokenManager.on(ACCESS_TOKEN_EXPIRED_EVENT, async (key) => {
if (key === ACCESS_TOKEN_NAME) {
const accessToken = await oktaInstance?.getOrRenewAccessToken();
if (accessToken) {
void updateAuthState();
} else {
void logout();
}
}
});
};
const addTokenExpiredHandler = () => {
onAccessTokenExpired();
};
const tokenExpiredHttpHandler = async () => {
try {
const accessToken = await oktaInstance?.getOrRenewAccessToken();
if (accessToken) {
const newAuthInfo = (await oktaInstance?.authStateManager?.updateAuthState()) as AuthInfo;
if (newAuthInfo?.isAuthenticated) {
await setCredentials(newAuthInfo);
return newAuthInfo;
} else {
cleanCredentials();
return;
}
} else {
cleanCredentials();
return;
}
} catch (error) {
console.debug(error);
cleanCredentials();
return;
}
};
const switchTenant = (tenant?: string | void) => {
try {
const queryParams = new URLSearchParams({
...(tenant ? {tenant} : {}),
...(newAuthConfig?.configOptions?.redirectUri
? {redirectUri: newAuthConfig?.configOptions?.redirectUri?.trim()}
: {})
});
if (tenant) {
window.location.href = `${newAuthConfig?.iamUI}/${newAuthConfig?.productId}/tenants?${queryParams.toString()}`;
} else {
window.location.href = `${newAuthConfig?.iamUI}/${newAuthConfig?.productId}/tenants?${queryParams.toString()}`;
}
} catch (error) {
console.debug(error);
}
};
const signIn = (state: any) => {
try {
void oktaInstance?.token.getWithRedirect({
scopes: newAuthConfig?.configOptions?.scopes,
state: JSON.stringify(state ?? {url: getRelativeUrl()})
});
} catch (error) {
console.debug(error);
}
};
const updateAuthState = async () => {
try {
const newAuthInfo = (await oktaInstance?.authStateManager?.updateAuthState()) as AuthInfo;
if (newAuthInfo?.isAuthenticated) {
await setCredentials(newAuthInfo);
}
} catch (error) {
console.debug(error);
cleanCredentials();
}
};
const authStart = async () => {
try {
await getAndSetTokens();
if (!isAutoRenew) {
void updateAuthState();
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (error) {
try {
if (!isAutoRenew) {
void updateAuthState();
if (!authInfo?.accessToken) {
cleanCredentials();
} else if (oktaInstance?.tokenManager.hasExpired(authInfo.accessToken)) {
return switchTenant(authInfo.accessToken.claims.tenant as string);
}
} else {
const isAuth = await oktaInstance?.isAuthenticated();
if (!isAuth) {
cleanCredentials();
}
}
} catch (error) {
console.debug(error);
cleanCredentials();
}
}
};
const startOktaService = async () => {
try {
oktaInstance?.authStateManager?.subscribe(async (newAuthInfo: AuthInfo) => {
try {
if (newAuthInfo?.isAuthenticated) {
await setCredentials(newAuthInfo);
}
} catch (error) {
console.debug(error);
cleanCredentials();
}
});
void updateAuthState();
await oktaInstance?.start();
} catch (error) {
console.debug(error);
cleanCredentials();
}
};
React.useEffect(() => {
if (controller === undefined) {
return;
}
setLoading(false);
}, [controller]);
React.useEffect(() => {
const main = () => {
try {
const sessionRequest = searchParams.get('request');
if (sessionRequest) {
signIn({sessionRequest});
} else {
if (!isAutoRenew) {
addTokenExpiredHandler();
}
void authStart();
if (isAutoRenew) {
void startOktaService();
}
}
} catch (error) {
console.debug(error);
}
};
void main();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
if (loading) {
return <Loading />;
}
if (!isValidConfig || !isValidOktaConfig) {
return (
<AuthError
error={
new Error('No authConfig passed to <AuthProvider> component or invalid config passed to <AuthProvider> component.')
}
/>
);
}
if (isAutoRenew && !newAuthConfig?.configOptions?.scopes?.includes('offline_access')) {
return <AuthError error={new Error('Error on renew options.')} />;
}
if (!isAutoRenew && newAuthConfig.configOptions?.renewOnTabActivation) {
return <AuthError error={new Error('Error on renewOnTabActivation options (renew needs to be set to "auto").')} />;
}
if (!oktaInstance) {
return <AuthError error={new Error('No oktaInstance created in <AuthProvider> component.')} />;
}
if (handleError) {
return <AuthError error={handleError} />;
}
if (!oktaInstance._oktaUserAgent) {
console.warn('_oktaUserAgent is not available on auth SDK instance. Please use okta-auth-js@^5.3.1.');
}
if (newAuthConfig?.configOptions?.expireEarlySeconds) {
console.warn(
"expireEarlySeconds option it's only to be used in local development, in production it's disabled by default."
);
}
const values = {
authConfig: {...newAuthConfig},
oktaInstance,
authInfo,
loading,
login,
register,
logout,
tokenExpiredHttpHandler,
switchTenant
};
return <AuthContextIAM.Provider value={values}>{children}</AuthContextIAM.Provider>;
};
export default AuthProviderIAM;