@cleavelandprice/ngx-lib 4.7.3 → 4.7.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,468 @@
|
|
|
1
|
+
import * as i0 from '@angular/core';
|
|
2
|
+
import { InjectionToken, EventEmitter, Output, Optional, Inject, Injectable, SkipSelf, NgModule, inject } from '@angular/core';
|
|
3
|
+
import { NgxLibServiceBase } from '@cleavelandprice/ngx-lib';
|
|
4
|
+
import { BrowserCacheLocation, PublicClientApplication } from '@azure/msal-browser';
|
|
5
|
+
import { CommonModule } from '@angular/common';
|
|
6
|
+
import { Router } from '@angular/router';
|
|
7
|
+
import { take, map } from 'rxjs/operators';
|
|
8
|
+
|
|
9
|
+
// What is a InjectionToken?
|
|
10
|
+
// An InjectionToken is a way to create a token that can be used to inject a dependency into an Angular service or component.
|
|
11
|
+
// It allows you to define a unique identifier for a dependency, which can then be used to retrieve the dependency from the Angular dependency injection system.
|
|
12
|
+
// This is particularly useful when you want to inject a value that is not a class, such as a configuration object or a string.
|
|
13
|
+
// Great explaination of InjectionToken: https://youtu.be/GvA7xnBmEto?si=_Nc2DTzdsb0jdvuk
|
|
14
|
+
const AuthenticationSSOServiceOptionsToken = new InjectionToken('AuthenticationSSOServiceOptions');
|
|
15
|
+
|
|
16
|
+
// This service implements authentication using Microsoft Entra ID (formerly Azure AD) via the Microsoft Authentication Library (MSAL).
|
|
17
|
+
// It provides methods for logging in, logging out, and validating the authenticated user, while managing token storage and refresh.
|
|
18
|
+
// It also supports cross-tab synchronization of authentication state using the BroadcastChannel API.
|
|
19
|
+
// It also supports revalidating authentication state when the user returns to a tab after it has been backgrounded for a period of time.
|
|
20
|
+
// It also supports storing the token in either localStorage or sessionStorage, based on the user's preference.
|
|
21
|
+
// It also supports determining if the token is expired and refreshing it if necessary, or logging the user out if the token cannot be refreshed.
|
|
22
|
+
class AuthenticationSSOService extends NgxLibServiceBase {
|
|
23
|
+
// Microsoft Authentication Library (MSAL) instance for handling authentication
|
|
24
|
+
#msal;
|
|
25
|
+
// Tracks one-time MSAL initialize() completion.
|
|
26
|
+
#initialized;
|
|
27
|
+
// Cross-tab messaging channel (same-origin tabs only).
|
|
28
|
+
#channel;
|
|
29
|
+
// Broadcast payload sent between tabs to synchronize logout.
|
|
30
|
+
#logoutMessage;
|
|
31
|
+
// Coalescing flags used when syncing auth after tab visibility/focus resumes.
|
|
32
|
+
#resumeCheckInProgress;
|
|
33
|
+
#lastResumeCheckAt;
|
|
34
|
+
// Timer id used to refresh tokens before expiry.
|
|
35
|
+
#tokenRefreshTimeoutId;
|
|
36
|
+
//#endregion
|
|
37
|
+
//#region Properties
|
|
38
|
+
// I don't agree with these properties being required in the AbstractAuthenticationService interface
|
|
39
|
+
// I think this should be set in the options passed to the service.
|
|
40
|
+
// I know this is used in the login components under material but a developer who wants to use their own login with sessionStorage would need to know that they need to create a localStorage item called 'storeTokenInSession' and set it to true
|
|
41
|
+
// I have added a cacheLocation option to the AuthenticationSSOServiceOptions interface but if the users don't set it, they can use these properties to set the storage location
|
|
42
|
+
get useSessionStorage() {
|
|
43
|
+
return !!localStorage.getItem('storeTokenInSession');
|
|
44
|
+
}
|
|
45
|
+
get storage() {
|
|
46
|
+
return this.useSessionStorage ?
|
|
47
|
+
sessionStorage :
|
|
48
|
+
localStorage;
|
|
49
|
+
}
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region Lifecycle
|
|
52
|
+
constructor(options) {
|
|
53
|
+
super(options);
|
|
54
|
+
this.options = options;
|
|
55
|
+
//#region Fields
|
|
56
|
+
this.authenticating = false; // Flag set to true while the service is attempting to authenticate the user
|
|
57
|
+
this.authenticated = false; // Flag set to true when the user is successfully authenticated
|
|
58
|
+
// error NG8110: Unsupported call to the output function. This function can only be used as the initializer of a property on a @Component or @Directive class.
|
|
59
|
+
/*authenticatedChanged = output<boolean>();
|
|
60
|
+
authenticatingChanged = output<boolean>();
|
|
61
|
+
authenticationError = output();*/
|
|
62
|
+
this.authenticatedChanged = new EventEmitter();
|
|
63
|
+
this.authenticatingChanged = new EventEmitter();
|
|
64
|
+
this.authenticationError = new EventEmitter();
|
|
65
|
+
// Tracks one-time MSAL initialize() completion.
|
|
66
|
+
this.#initialized = false;
|
|
67
|
+
// Broadcast payload sent between tabs to synchronize logout.
|
|
68
|
+
this.#logoutMessage = 'logout';
|
|
69
|
+
// Coalescing flags used when syncing auth after tab visibility/focus resumes.
|
|
70
|
+
this.#resumeCheckInProgress = false;
|
|
71
|
+
this.#lastResumeCheckAt = 0;
|
|
72
|
+
const authenticationEndpoint = options.authenticationEndpoint ?? `https://login.microsoftonline.com/${options.tenantId}`;
|
|
73
|
+
this.options = {
|
|
74
|
+
...options,
|
|
75
|
+
tokenName: options.tokenName ?? options.clientId + '-token',
|
|
76
|
+
authenticationEndpoint
|
|
77
|
+
};
|
|
78
|
+
// if the user didn't set the cacheLocation in the options, we will set it to sessionStorage if useSessionStorage is true, otherwise we will set it to localStorage
|
|
79
|
+
this.options.cacheLocation = this.options.cacheLocation ?? (this.useSessionStorage ? 'sessionStorage' : 'localStorage');
|
|
80
|
+
// MSAL configuration for this SPA.
|
|
81
|
+
// Cache remains in sessionStorage so each tab has isolated auth cache.
|
|
82
|
+
const msalConfig = {
|
|
83
|
+
auth: {
|
|
84
|
+
clientId: this.options.clientId,
|
|
85
|
+
authority: this.options.authenticationEndpoint,
|
|
86
|
+
redirectUri: this.options.redirectUri,
|
|
87
|
+
postLogoutRedirectUri: this.options.postLogoutRedirectUri
|
|
88
|
+
},
|
|
89
|
+
cache: {
|
|
90
|
+
cacheLocation: this.options.cacheLocation === 'sessionStorage' ? BrowserCacheLocation.SessionStorage : BrowserCacheLocation.LocalStorage
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
// Create MSAL client based on the configuration.
|
|
94
|
+
// We still need to call initialize() before using it, but this ensures that we only create one instance of the client.
|
|
95
|
+
this.#msal = new PublicClientApplication(msalConfig);
|
|
96
|
+
// Initialize the BroadcastChannel for cross-tab communication
|
|
97
|
+
this.#initializeBroadcastChannel();
|
|
98
|
+
// Register resume listeners so returning to a tab revalidates auth state.
|
|
99
|
+
this.#registerResumeListeners();
|
|
100
|
+
// Attempt to restore authenticated state from any existing Microsoft session.
|
|
101
|
+
this.checkForExistingToken();
|
|
102
|
+
}
|
|
103
|
+
//#endregion
|
|
104
|
+
//#region Utilities
|
|
105
|
+
//Authenticate the user and store the token in Local Storage or Session Storage
|
|
106
|
+
login() {
|
|
107
|
+
this.authenticating = true;
|
|
108
|
+
this.authenticatingChanged.emit(this.authenticating);
|
|
109
|
+
console.log('AuthenticationSSOService: login() called. Authenticating user...');
|
|
110
|
+
// Initialize MSAL and then perform login via popup, followed by user validation.
|
|
111
|
+
this.#initializeMsal()
|
|
112
|
+
.then(() => this.#msal.loginPopup({
|
|
113
|
+
scopes: this.options.scopes,
|
|
114
|
+
authority: this.options.authenticationEndpoint,
|
|
115
|
+
prompt: 'select_account'
|
|
116
|
+
}))
|
|
117
|
+
.then((result) => this.validateUser(result))
|
|
118
|
+
.catch((error) => {
|
|
119
|
+
this.authenticating = false;
|
|
120
|
+
this.authenticatingChanged.emit(this.authenticating);
|
|
121
|
+
this.authenticationError.emit(error);
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
// Primary logout flow:
|
|
125
|
+
// 1) clear local state in this tab,
|
|
126
|
+
// 2) notify other tabs to clear their local state,
|
|
127
|
+
// 3) initiate Entra sign-out redirect from this initiating tab.
|
|
128
|
+
logout() {
|
|
129
|
+
this.#logoutLocalOnly(false);
|
|
130
|
+
this.#publishLogout();
|
|
131
|
+
// Only the initiating tab should call identity-provider logout.
|
|
132
|
+
this.#clearTokenRefreshTimer();
|
|
133
|
+
this.#initializeMsal()
|
|
134
|
+
.then(() => this.#msal.logoutRedirect({
|
|
135
|
+
postLogoutRedirectUri: this.options.postLogoutRedirectUri
|
|
136
|
+
}))
|
|
137
|
+
.catch((error) => {
|
|
138
|
+
console.log('ERROR: Microsoft logout failed.', error);
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
tokenExists() {
|
|
142
|
+
const token = this.storage.getItem(this.options.tokenName ?? '');
|
|
143
|
+
return !!token;
|
|
144
|
+
}
|
|
145
|
+
// validateUser() = setAuthenticatedUser()
|
|
146
|
+
// Resolves current user and token claims into the app's authenticated model.
|
|
147
|
+
// Also validates/refreshes token when needed and schedules proactive refresh.
|
|
148
|
+
async validateUser(result, account) {
|
|
149
|
+
// Resolve account from auth result or fallback account.
|
|
150
|
+
let resolvedAccount = result?.account ?? account;
|
|
151
|
+
// No account means app should be considered logged out.
|
|
152
|
+
if (!resolvedAccount) {
|
|
153
|
+
this.logout();
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
// Keep MSAL active account in sync with resolved account context.
|
|
157
|
+
this.#msal.setActiveAccount(resolvedAccount);
|
|
158
|
+
let resolvedResult = result;
|
|
159
|
+
let claims = (resolvedResult?.idTokenClaims ?? resolvedAccount.idTokenClaims ?? {});
|
|
160
|
+
// If token appears expired, attempt silent refresh before setting user state.
|
|
161
|
+
if (this.#isTokenExpired(claims.exp)) {
|
|
162
|
+
const refreshedResult = await this.#refreshToken(resolvedAccount);
|
|
163
|
+
// Refresh failure means we should end the session.
|
|
164
|
+
if (!refreshedResult?.account) {
|
|
165
|
+
this.logout();
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
resolvedResult = refreshedResult;
|
|
169
|
+
resolvedAccount = refreshedResult.account;
|
|
170
|
+
claims = (resolvedResult.idTokenClaims ?? resolvedAccount.idTokenClaims ?? {});
|
|
171
|
+
// Still expired after refresh; terminate session to avoid stale auth.
|
|
172
|
+
if (this.#isTokenExpired(claims.exp)) {
|
|
173
|
+
this.logout();
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
// Derive a stable account name from available claims.
|
|
178
|
+
const preferredUsername = String(claims.preferred_username ?? resolvedAccount.username ?? claims.upn ?? claims.email ?? '');
|
|
179
|
+
const accountName = preferredUsername.includes('@') ? preferredUsername.split('@')[0] : preferredUsername;
|
|
180
|
+
// Map Entra claims to the app's authenticated user shape.
|
|
181
|
+
this.authenticatedUser = {
|
|
182
|
+
admin: false,
|
|
183
|
+
accountName: claims.accountName ?? accountName,
|
|
184
|
+
department: claims.department ?? '',
|
|
185
|
+
displayName: claims.displayName ?? '',
|
|
186
|
+
distinguishedName: claims.distinguishedName ?? '',
|
|
187
|
+
email: claims.mail,
|
|
188
|
+
employeeNumber: claims.employeeNumber,
|
|
189
|
+
firstName: claims.firstName ?? '',
|
|
190
|
+
hireDate: claims.hireDate ?? '',
|
|
191
|
+
lastName: claims.lastName ?? '',
|
|
192
|
+
manager: claims.manager,
|
|
193
|
+
memberOf: claims.memberOf,
|
|
194
|
+
phone: claims.phone,
|
|
195
|
+
photoUrl: claims.photoUrl,
|
|
196
|
+
sid: claims.securityIdentifier ?? '',
|
|
197
|
+
title: claims.title,
|
|
198
|
+
workShift: claims.workShift
|
|
199
|
+
};
|
|
200
|
+
// Persist id token into shared auth storage key when configured.
|
|
201
|
+
if (this.options.tokenName) {
|
|
202
|
+
const token = resolvedAccount?.idToken;
|
|
203
|
+
if (token) {
|
|
204
|
+
this.storage.setItem(this.options.tokenName, token);
|
|
205
|
+
}
|
|
206
|
+
else {
|
|
207
|
+
this.storage.removeItem(this.options.tokenName);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
// Schedule refresh before expiration to keep session uninterrupted.
|
|
211
|
+
this.#scheduleTokenRefresh(claims.exp, resolvedAccount);
|
|
212
|
+
// Publish authenticated state changes for the rest of the app.
|
|
213
|
+
this.authenticated = true;
|
|
214
|
+
this.authenticatedChanged.emit(this.authenticated);
|
|
215
|
+
this.authenticating = false;
|
|
216
|
+
this.authenticatingChanged.emit(this.authenticating);
|
|
217
|
+
}
|
|
218
|
+
// Rehydrates auth state from existing cached account on startup.
|
|
219
|
+
// We intentionally avoid handleRedirectPromise() because this service uses popup login.
|
|
220
|
+
checkForExistingToken() {
|
|
221
|
+
this.#initializeMsal()
|
|
222
|
+
.then(() => {
|
|
223
|
+
const account = this.#msal.getActiveAccount() ?? this.#msal.getAllAccounts()[0];
|
|
224
|
+
if (account)
|
|
225
|
+
return this.validateUser(undefined, account);
|
|
226
|
+
return undefined;
|
|
227
|
+
})
|
|
228
|
+
.catch((error) => {
|
|
229
|
+
console.log('ERROR: Failed to hydrate Microsoft auth state.', error);
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
// Initialize MSAL if it hasn't been initialized yet
|
|
233
|
+
// This ensures that we only initialize MSAL once, even if multiple login attempts are made
|
|
234
|
+
// This is important because there is startup work that must be completed by MSAL before it can be used, and we don't want to repeat that work unnecessarily
|
|
235
|
+
async #initializeMsal() {
|
|
236
|
+
if (this.#initialized) {
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
await this.#msal.initialize();
|
|
240
|
+
this.#initialized = true;
|
|
241
|
+
}
|
|
242
|
+
// Sets up same-origin cross-tab messaging used to fan out logout events.
|
|
243
|
+
#initializeBroadcastChannel() {
|
|
244
|
+
if (typeof BroadcastChannel === 'undefined') {
|
|
245
|
+
// Some runtimes may not support BroadcastChannel.
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
// Create a new BroadcastChannel for cross-tab communication
|
|
249
|
+
this.#channel = new BroadcastChannel('sso-authentication-channel');
|
|
250
|
+
// Listen for messages from other tabs for logout events.
|
|
251
|
+
// When a logout message is received, the current tab will clear its local state and reload the page.
|
|
252
|
+
this.#channel.onmessage = (event) => {
|
|
253
|
+
if (event.data === this.#logoutMessage) {
|
|
254
|
+
console.log('Received logout message from another tab.');
|
|
255
|
+
// Receiving tabs clear local state and reload so route guards re-evaluate immediately.
|
|
256
|
+
this.#logoutLocalOnly(true);
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
// Registers visibility/focus listeners to re-check auth when user returns to the tab.
|
|
261
|
+
// Tabs can be backgrounded for long periods, and the user may have logged out in another tab or session.
|
|
262
|
+
#registerResumeListeners() {
|
|
263
|
+
const handleResume = () => {
|
|
264
|
+
void this.#syncAuthOnResume();
|
|
265
|
+
};
|
|
266
|
+
if (typeof document !== 'undefined') {
|
|
267
|
+
document.addEventListener('visibilitychange', () => {
|
|
268
|
+
if (document.visibilityState === 'visible') {
|
|
269
|
+
handleResume();
|
|
270
|
+
}
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
if (typeof window !== 'undefined') {
|
|
274
|
+
window.addEventListener('focus', handleResume);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
// Syncs auth state after resume while preventing duplicate checks from rapid events.
|
|
278
|
+
async #syncAuthOnResume() {
|
|
279
|
+
const now = Date.now();
|
|
280
|
+
// visibilitychange and focus often fire back-to-back; coalesce to one check.
|
|
281
|
+
// if now was less than 1 second since last check, skip this one.
|
|
282
|
+
if (this.#resumeCheckInProgress || now - this.#lastResumeCheckAt < 1000) {
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
this.#resumeCheckInProgress = true;
|
|
286
|
+
this.#lastResumeCheckAt = now;
|
|
287
|
+
try {
|
|
288
|
+
await this.#initializeMsal();
|
|
289
|
+
const account = this.#msal.getActiveAccount() ?? this.#msal.getAllAccounts()[0];
|
|
290
|
+
if (!account)
|
|
291
|
+
return;
|
|
292
|
+
await this.validateUser(undefined, account);
|
|
293
|
+
}
|
|
294
|
+
catch (error) {
|
|
295
|
+
console.log('Error: Resume auth sync failed.', error);
|
|
296
|
+
}
|
|
297
|
+
finally {
|
|
298
|
+
this.#resumeCheckInProgress = false;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
// Sends logout signal to other open tabs.
|
|
302
|
+
#publishLogout() {
|
|
303
|
+
this.#channel?.postMessage(this.#logoutMessage);
|
|
304
|
+
}
|
|
305
|
+
// Clears app/MSAL state in current tab without invoking provider-side logout.
|
|
306
|
+
// reloadAfterLogout is intended for non-initiating tabs to force UI reset to auth route.
|
|
307
|
+
async #logoutLocalOnly(reloadAfterLogout) {
|
|
308
|
+
this.#clearTokenRefreshTimer();
|
|
309
|
+
if (this.options.tokenName && this.storage.getItem(this.options.tokenName)) {
|
|
310
|
+
this.storage.removeItem(this.options.tokenName);
|
|
311
|
+
}
|
|
312
|
+
this.authenticatedUser = undefined;
|
|
313
|
+
this.authenticated = false;
|
|
314
|
+
this.authenticatedChanged.emit(false);
|
|
315
|
+
try {
|
|
316
|
+
await this.#initializeMsal();
|
|
317
|
+
await this.#msal.clearCache();
|
|
318
|
+
this.#msal.setActiveAccount(null);
|
|
319
|
+
// Secondary tabs should hard-refresh to guarantee route guards and app state reset.
|
|
320
|
+
if (reloadAfterLogout && typeof window !== 'undefined') {
|
|
321
|
+
window.location.reload();
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
catch (error) {
|
|
325
|
+
console.log('WARN: Local MSAL cache clear failed.', error);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
// Returns true when token expiration is absent or in the past.
|
|
329
|
+
#isTokenExpired(expirationEpochSeconds) {
|
|
330
|
+
if (!expirationEpochSeconds) {
|
|
331
|
+
return true;
|
|
332
|
+
}
|
|
333
|
+
return Date.now() >= expirationEpochSeconds * 1000;
|
|
334
|
+
}
|
|
335
|
+
// Attempts silent token acquisition for the current account.
|
|
336
|
+
async #refreshToken(account) {
|
|
337
|
+
try {
|
|
338
|
+
return await this.#msal.acquireTokenSilent({
|
|
339
|
+
account,
|
|
340
|
+
scopes: this.options.scopes
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
catch (error) {
|
|
344
|
+
console.log('Error: Silent token refresh failed.', error);
|
|
345
|
+
return undefined;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
// Schedules token refresh shortly before expiration.
|
|
349
|
+
// If refresh fails, session is terminated to avoid inconsistent auth state.
|
|
350
|
+
#scheduleTokenRefresh(expirationEpochSeconds, account) {
|
|
351
|
+
this.#clearTokenRefreshTimer();
|
|
352
|
+
if (!expirationEpochSeconds) {
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
const refreshLeadTimeMs = 60_000;
|
|
356
|
+
const millisecondsUntilRefresh = expirationEpochSeconds * 1000 - Date.now() - refreshLeadTimeMs;
|
|
357
|
+
const delay = Math.max(millisecondsUntilRefresh, 0);
|
|
358
|
+
this.#tokenRefreshTimeoutId = setTimeout(() => {
|
|
359
|
+
this.#refreshToken(account)
|
|
360
|
+
.then((result) => {
|
|
361
|
+
if (result?.account) {
|
|
362
|
+
return this.validateUser(result, result.account);
|
|
363
|
+
}
|
|
364
|
+
// No account after refresh implies invalid session.
|
|
365
|
+
this.logout();
|
|
366
|
+
return undefined;
|
|
367
|
+
})
|
|
368
|
+
.catch(() => {
|
|
369
|
+
// Any refresh exception falls back to logout for safety.
|
|
370
|
+
this.logout();
|
|
371
|
+
});
|
|
372
|
+
}, delay);
|
|
373
|
+
}
|
|
374
|
+
// Cancels any pending token refresh timer.
|
|
375
|
+
#clearTokenRefreshTimer() {
|
|
376
|
+
if (!this.#tokenRefreshTimeoutId) {
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
clearTimeout(this.#tokenRefreshTimeoutId);
|
|
380
|
+
this.#tokenRefreshTimeoutId = undefined;
|
|
381
|
+
}
|
|
382
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.0.0", ngImport: i0, type: AuthenticationSSOService, deps: [{ token: AuthenticationSSOServiceOptionsToken, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
383
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.0.0", ngImport: i0, type: AuthenticationSSOService, providedIn: 'root' }); }
|
|
384
|
+
}
|
|
385
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.0.0", ngImport: i0, type: AuthenticationSSOService, decorators: [{
|
|
386
|
+
type: Injectable,
|
|
387
|
+
args: [{
|
|
388
|
+
providedIn: 'root'
|
|
389
|
+
}]
|
|
390
|
+
}], ctorParameters: () => [{ type: undefined, decorators: [{
|
|
391
|
+
type: Optional
|
|
392
|
+
}, {
|
|
393
|
+
type: Inject,
|
|
394
|
+
args: [AuthenticationSSOServiceOptionsToken]
|
|
395
|
+
}] }], propDecorators: { authenticatedChanged: [{
|
|
396
|
+
type: Output
|
|
397
|
+
}], authenticatingChanged: [{
|
|
398
|
+
type: Output
|
|
399
|
+
}], authenticationError: [{
|
|
400
|
+
type: Output
|
|
401
|
+
}] } });
|
|
402
|
+
|
|
403
|
+
class AuthenticationSSOModule {
|
|
404
|
+
static forRoot(options) {
|
|
405
|
+
return {
|
|
406
|
+
ngModule: AuthenticationSSOModule,
|
|
407
|
+
providers: [
|
|
408
|
+
{
|
|
409
|
+
provide: AuthenticationSSOServiceOptionsToken,
|
|
410
|
+
useValue: options
|
|
411
|
+
}
|
|
412
|
+
]
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
constructor(parentModule) {
|
|
416
|
+
if (parentModule) {
|
|
417
|
+
throw new Error('AuthenticationSSOModule is already loaded. Import it in the AppModule only');
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.0.0", ngImport: i0, type: AuthenticationSSOModule, deps: [{ token: AuthenticationSSOModule, optional: true, skipSelf: true }], target: i0.ɵɵFactoryTarget.NgModule }); }
|
|
421
|
+
static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "21.0.0", ngImport: i0, type: AuthenticationSSOModule, imports: [CommonModule] }); }
|
|
422
|
+
static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "21.0.0", ngImport: i0, type: AuthenticationSSOModule, imports: [CommonModule] }); }
|
|
423
|
+
}
|
|
424
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.0.0", ngImport: i0, type: AuthenticationSSOModule, decorators: [{
|
|
425
|
+
type: NgModule,
|
|
426
|
+
args: [{
|
|
427
|
+
declarations: [],
|
|
428
|
+
imports: [
|
|
429
|
+
CommonModule
|
|
430
|
+
],
|
|
431
|
+
exports: []
|
|
432
|
+
}]
|
|
433
|
+
}], ctorParameters: () => [{ type: AuthenticationSSOModule, decorators: [{
|
|
434
|
+
type: Optional
|
|
435
|
+
}, {
|
|
436
|
+
type: SkipSelf
|
|
437
|
+
}] }] });
|
|
438
|
+
|
|
439
|
+
const authenticationSSOGuard = (_route, _state) => {
|
|
440
|
+
const authenticationService = inject(AuthenticationSSOService);
|
|
441
|
+
const router = inject(Router);
|
|
442
|
+
// if the user is already authenticated, allow access to the route
|
|
443
|
+
if (authenticationService.authenticated) {
|
|
444
|
+
return true;
|
|
445
|
+
}
|
|
446
|
+
if (authenticationService.tokenExists()) {
|
|
447
|
+
// we're doing this because we could've opened a new tab and the user is already logged in, so we need to check for an existing token
|
|
448
|
+
authenticationService.checkForExistingToken();
|
|
449
|
+
return authenticationService.authenticatedChanged.pipe(take(1), map(() => {
|
|
450
|
+
if (!authenticationService.authenticated) {
|
|
451
|
+
router.navigate(['']);
|
|
452
|
+
return false;
|
|
453
|
+
}
|
|
454
|
+
return true;
|
|
455
|
+
}));
|
|
456
|
+
}
|
|
457
|
+
else {
|
|
458
|
+
router.navigate(['']);
|
|
459
|
+
return false;
|
|
460
|
+
}
|
|
461
|
+
};
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* Generated bundle index. Do not edit.
|
|
465
|
+
*/
|
|
466
|
+
|
|
467
|
+
export { AuthenticationSSOModule, AuthenticationSSOService, AuthenticationSSOServiceOptionsToken, authenticationSSOGuard };
|
|
468
|
+
//# sourceMappingURL=cleavelandprice-ngx-lib-authentication-sso.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cleavelandprice-ngx-lib-authentication-sso.mjs","sources":["../../../../projects/cleavelandprice/ngx-lib/authentication/sso/src/model/authentication-sso-service-options-token.ts","../../../../projects/cleavelandprice/ngx-lib/authentication/sso/src/services/authentication-sso.service.ts","../../../../projects/cleavelandprice/ngx-lib/authentication/sso/src/authentication-sso.module.ts","../../../../projects/cleavelandprice/ngx-lib/authentication/sso/src/guards/authentication-sso.guard.ts","../../../../projects/cleavelandprice/ngx-lib/authentication/sso/src/cleavelandprice-ngx-lib-authentication-sso.ts"],"sourcesContent":["import { InjectionToken } from \"@angular/core\";\r\nimport { AuthenticationSSOServiceOptions } from \"./authentication-sso-service-options\";\r\n\r\n// What is a InjectionToken?\r\n// An InjectionToken is a way to create a token that can be used to inject a dependency into an Angular service or component.\r\n// It allows you to define a unique identifier for a dependency, which can then be used to retrieve the dependency from the Angular dependency injection system.\r\n// This is particularly useful when you want to inject a value that is not a class, such as a configuration object or a string.\r\n// Great explaination of InjectionToken: https://youtu.be/GvA7xnBmEto?si=_Nc2DTzdsb0jdvuk\r\nexport const AuthenticationSSOServiceOptionsToken = new InjectionToken<AuthenticationSSOServiceOptions>('AuthenticationSSOServiceOptions');\r\n","import { EventEmitter, Inject, Injectable, Optional, Output } from '@angular/core';\r\n\r\nimport { AbstractAuthenticationService, AuthenticatedUser } from '@cleavelandprice/ngx-lib/authentication';\r\n\r\nimport { NgxLibServiceBase } from '@cleavelandprice/ngx-lib';\r\n\r\nimport { AuthenticationSSOServiceOptions } from '../model/authentication-sso-service-options';\r\nimport { AuthenticationSSOServiceOptionsToken } from './../model/authentication-sso-service-options-token';\r\nimport { AuthenticationSSOClaims } from '../model/authentication-sso-claims';\r\n\r\nimport {\r\n AccountInfo,\r\n AuthenticationResult,\r\n BrowserCacheLocation,\r\n PublicClientApplication,\r\n type Configuration\r\n} from '@azure/msal-browser';\r\n\r\n// This service implements authentication using Microsoft Entra ID (formerly Azure AD) via the Microsoft Authentication Library (MSAL).\r\n// It provides methods for logging in, logging out, and validating the authenticated user, while managing token storage and refresh.\r\n// It also supports cross-tab synchronization of authentication state using the BroadcastChannel API.\r\n// It also supports revalidating authentication state when the user returns to a tab after it has been backgrounded for a period of time.\r\n// It also supports storing the token in either localStorage or sessionStorage, based on the user's preference.\r\n// It also supports determining if the token is expired and refreshing it if necessary, or logging the user out if the token cannot be refreshed.\r\n@Injectable({\r\n providedIn: 'root'\r\n})\r\nexport class AuthenticationSSOService extends NgxLibServiceBase implements AbstractAuthenticationService {\r\n //#region Fields\r\n authenticating = false; // Flag set to true while the service is attempting to authenticate the user\r\n authenticated = false; // Flag set to true when the user is successfully authenticated\r\n authenticatedUser?: AuthenticatedUser; // Object representing the authenticated user\r\n\r\n // error NG8110: Unsupported call to the output function. This function can only be used as the initializer of a property on a @Component or @Directive class.\r\n /*authenticatedChanged = output<boolean>();\r\n authenticatingChanged = output<boolean>();\r\n authenticationError = output();*/\r\n @Output() authenticatedChanged = new EventEmitter<boolean>();\r\n @Output() authenticatingChanged = new EventEmitter<boolean>();\r\n @Output() authenticationError = new EventEmitter();\r\n\r\n // Microsoft Authentication Library (MSAL) instance for handling authentication\r\n #msal: PublicClientApplication;\r\n // Tracks one-time MSAL initialize() completion.\r\n #initialized = false;\r\n\r\n // Cross-tab messaging channel (same-origin tabs only).\r\n #channel?: BroadcastChannel;\r\n // Broadcast payload sent between tabs to synchronize logout.\r\n #logoutMessage = 'logout';\r\n\r\n // Coalescing flags used when syncing auth after tab visibility/focus resumes.\r\n #resumeCheckInProgress = false;\r\n #lastResumeCheckAt = 0;\r\n\r\n // Timer id used to refresh tokens before expiry.\r\n #tokenRefreshTimeoutId?: ReturnType<typeof setTimeout>;\r\n //#endregion\r\n\r\n //#region Properties\r\n\r\n // I don't agree with these properties being required in the AbstractAuthenticationService interface\r\n // I think this should be set in the options passed to the service.\r\n // I know this is used in the login components under material but a developer who wants to use their own login with sessionStorage would need to know that they need to create a localStorage item called 'storeTokenInSession' and set it to true\r\n // I have added a cacheLocation option to the AuthenticationSSOServiceOptions interface but if the users don't set it, they can use these properties to set the storage location\r\n\r\n get useSessionStorage(): boolean {\r\n return !!localStorage.getItem('storeTokenInSession');\r\n }\r\n\r\n get storage(): Storage {\r\n return this.useSessionStorage ?\r\n sessionStorage:\r\n localStorage;\r\n }\r\n\r\n //#endregion\r\n\r\n //#region Lifecycle\r\n constructor(@Optional() @Inject(AuthenticationSSOServiceOptionsToken) protected options: AuthenticationSSOServiceOptions) {\r\n super(options);\r\n\r\n const authenticationEndpoint = options.authenticationEndpoint ?? `https://login.microsoftonline.com/${options.tenantId}`;\r\n\r\n this.options = {\r\n ...options,\r\n\r\n tokenName: options.tokenName ?? options.clientId + '-token',\r\n authenticationEndpoint\r\n };\r\n\r\n // if the user didn't set the cacheLocation in the options, we will set it to sessionStorage if useSessionStorage is true, otherwise we will set it to localStorage\r\n this.options.cacheLocation = this.options.cacheLocation ?? (this.useSessionStorage ? 'sessionStorage' : 'localStorage');\r\n\r\n // MSAL configuration for this SPA.\r\n // Cache remains in sessionStorage so each tab has isolated auth cache.\r\n const msalConfig: Configuration = {\r\n auth: {\r\n clientId: this.options.clientId,\r\n authority: this.options.authenticationEndpoint,\r\n redirectUri: this.options.redirectUri,\r\n postLogoutRedirectUri: this.options.postLogoutRedirectUri\r\n },\r\n cache: {\r\n cacheLocation: this.options.cacheLocation === 'sessionStorage' ? BrowserCacheLocation.SessionStorage : BrowserCacheLocation.LocalStorage\r\n }\r\n };\r\n\r\n // Create MSAL client based on the configuration.\r\n // We still need to call initialize() before using it, but this ensures that we only create one instance of the client.\r\n this.#msal = new PublicClientApplication(msalConfig);\r\n\r\n // Initialize the BroadcastChannel for cross-tab communication\r\n this.#initializeBroadcastChannel();\r\n\r\n // Register resume listeners so returning to a tab revalidates auth state.\r\n this.#registerResumeListeners();\r\n\r\n // Attempt to restore authenticated state from any existing Microsoft session.\r\n this.checkForExistingToken();\r\n }\r\n //#endregion\r\n\r\n //#region Utilities\r\n\r\n //Authenticate the user and store the token in Local Storage or Session Storage\r\n login(): void {\r\n this.authenticating = true;\r\n this.authenticatingChanged.emit(this.authenticating);\r\n\r\n console.log('AuthenticationSSOService: login() called. Authenticating user...');\r\n\r\n // Initialize MSAL and then perform login via popup, followed by user validation.\r\n this.#initializeMsal()\r\n .then(() => this.#msal.loginPopup({\r\n scopes: this.options.scopes,\r\n authority: this.options.authenticationEndpoint,\r\n prompt: 'select_account'\r\n }))\r\n .then((result) => this.validateUser(result))\r\n .catch((error: unknown) => {\r\n this.authenticating = false;\r\n this.authenticatingChanged.emit(this.authenticating);\r\n this.authenticationError.emit(error);\r\n });\r\n }\r\n\r\n // Primary logout flow:\r\n // 1) clear local state in this tab,\r\n // 2) notify other tabs to clear their local state,\r\n // 3) initiate Entra sign-out redirect from this initiating tab.\r\n logout(): void {\r\n this.#logoutLocalOnly(false);\r\n this.#publishLogout();\r\n\r\n // Only the initiating tab should call identity-provider logout.\r\n this.#clearTokenRefreshTimer();\r\n\r\n this.#initializeMsal()\r\n .then(() => this.#msal.logoutRedirect({\r\n postLogoutRedirectUri: this.options.postLogoutRedirectUri\r\n }))\r\n .catch((error) => {\r\n console.log('ERROR: Microsoft logout failed.', error);\r\n });\r\n }\r\n\r\n tokenExists(): boolean {\r\n const token = this.storage.getItem(this.options.tokenName ?? '');\r\n return !!token;\r\n }\r\n\r\n // validateUser() = setAuthenticatedUser()\r\n // Resolves current user and token claims into the app's authenticated model.\r\n // Also validates/refreshes token when needed and schedules proactive refresh.\r\n async validateUser(result?: AuthenticationResult, account?: AccountInfo): Promise<void> {\r\n // Resolve account from auth result or fallback account.\r\n let resolvedAccount = result?.account ?? account;\r\n\r\n // No account means app should be considered logged out.\r\n if (!resolvedAccount) {\r\n this.logout();\r\n return;\r\n }\r\n\r\n // Keep MSAL active account in sync with resolved account context.\r\n this.#msal.setActiveAccount(resolvedAccount);\r\n\r\n let resolvedResult = result;\r\n let claims = (resolvedResult?.idTokenClaims ?? resolvedAccount.idTokenClaims ?? {}) as AuthenticationSSOClaims;\r\n\r\n // If token appears expired, attempt silent refresh before setting user state.\r\n if (this.#isTokenExpired(claims.exp)) {\r\n const refreshedResult = await this.#refreshToken(resolvedAccount);\r\n\r\n // Refresh failure means we should end the session.\r\n if (!refreshedResult?.account) {\r\n this.logout();\r\n return;\r\n }\r\n\r\n resolvedResult = refreshedResult;\r\n resolvedAccount = refreshedResult.account;\r\n claims = (resolvedResult.idTokenClaims ?? resolvedAccount.idTokenClaims ?? {}) as AuthenticationSSOClaims;\r\n\r\n // Still expired after refresh; terminate session to avoid stale auth.\r\n if (this.#isTokenExpired(claims.exp)) {\r\n this.logout();\r\n return;\r\n }\r\n }\r\n\r\n // Derive a stable account name from available claims.\r\n const preferredUsername = String(claims.preferred_username ?? resolvedAccount.username ?? claims.upn ?? claims.email ?? '');\r\n const accountName = preferredUsername.includes('@') ? preferredUsername.split('@')[0] : preferredUsername;\r\n\r\n // Map Entra claims to the app's authenticated user shape.\r\n this.authenticatedUser = {\r\n admin: false,\r\n accountName: claims.accountName ?? accountName,\r\n department: claims.department ?? '',\r\n displayName: claims.displayName ?? '',\r\n distinguishedName: claims.distinguishedName ?? '',\r\n email: claims.mail,\r\n employeeNumber: claims.employeeNumber,\r\n firstName: claims.firstName ?? '',\r\n hireDate: claims.hireDate ?? '',\r\n lastName: claims.lastName ?? '',\r\n manager: claims.manager,\r\n memberOf: claims.memberOf,\r\n phone: claims.phone,\r\n photoUrl: claims.photoUrl,\r\n sid: claims.securityIdentifier ?? '',\r\n title: claims.title,\r\n workShift: claims.workShift\r\n } as AuthenticatedUser;\r\n\r\n // Persist id token into shared auth storage key when configured.\r\n if (this.options.tokenName) {\r\n const token = resolvedAccount?.idToken;\r\n if (token) {\r\n this.storage.setItem(this.options.tokenName, token);\r\n } else {\r\n this.storage.removeItem(this.options.tokenName);\r\n }\r\n }\r\n\r\n // Schedule refresh before expiration to keep session uninterrupted.\r\n this.#scheduleTokenRefresh(claims.exp, resolvedAccount);\r\n\r\n // Publish authenticated state changes for the rest of the app.\r\n this.authenticated = true;\r\n this.authenticatedChanged.emit(this.authenticated);\r\n\r\n this.authenticating = false;\r\n this.authenticatingChanged.emit(this.authenticating);\r\n }\r\n\r\n // Rehydrates auth state from existing cached account on startup.\r\n // We intentionally avoid handleRedirectPromise() because this service uses popup login.\r\n checkForExistingToken(): void {\r\n this.#initializeMsal()\r\n .then(() => {\r\n const account = this.#msal.getActiveAccount() ?? this.#msal.getAllAccounts()[0];\r\n if (account)\r\n return this.validateUser(undefined, account);\r\n\r\n return undefined;\r\n })\r\n .catch((error: unknown) => {\r\n console.log('ERROR: Failed to hydrate Microsoft auth state.', error);\r\n });\r\n }\r\n\r\n // Initialize MSAL if it hasn't been initialized yet\r\n // This ensures that we only initialize MSAL once, even if multiple login attempts are made\r\n // This is important because there is startup work that must be completed by MSAL before it can be used, and we don't want to repeat that work unnecessarily\r\n async #initializeMsal(): Promise<void> {\r\n if (this.#initialized) {\r\n return;\r\n }\r\n\r\n\r\n await this.#msal.initialize();\r\n this.#initialized = true;\r\n }\r\n\r\n // Sets up same-origin cross-tab messaging used to fan out logout events.\r\n #initializeBroadcastChannel(): void {\r\n if (typeof BroadcastChannel === 'undefined') {\r\n // Some runtimes may not support BroadcastChannel.\r\n return;\r\n }\r\n\r\n // Create a new BroadcastChannel for cross-tab communication\r\n this.#channel = new BroadcastChannel('sso-authentication-channel');\r\n\r\n // Listen for messages from other tabs for logout events.\r\n // When a logout message is received, the current tab will clear its local state and reload the page.\r\n this.#channel.onmessage = (event) => {\r\n if (event.data === this.#logoutMessage) {\r\n console.log('Received logout message from another tab.');\r\n // Receiving tabs clear local state and reload so route guards re-evaluate immediately.\r\n this.#logoutLocalOnly(true);\r\n }\r\n };\r\n }\r\n\r\n // Registers visibility/focus listeners to re-check auth when user returns to the tab.\r\n // Tabs can be backgrounded for long periods, and the user may have logged out in another tab or session.\r\n #registerResumeListeners(): void {\r\n const handleResume = () => {\r\n void this.#syncAuthOnResume();\r\n };\r\n\r\n if (typeof document !== 'undefined') {\r\n document.addEventListener('visibilitychange', () => {\r\n if (document.visibilityState === 'visible') {\r\n handleResume();\r\n }\r\n });\r\n }\r\n\r\n if (typeof window !== 'undefined') {\r\n window.addEventListener('focus', handleResume);\r\n }\r\n }\r\n\r\n // Syncs auth state after resume while preventing duplicate checks from rapid events.\r\n async #syncAuthOnResume(): Promise<void> {\r\n const now = Date.now();\r\n\r\n // visibilitychange and focus often fire back-to-back; coalesce to one check.\r\n // if now was less than 1 second since last check, skip this one.\r\n if (this.#resumeCheckInProgress || now - this.#lastResumeCheckAt < 1000) {\r\n return;\r\n }\r\n\r\n this.#resumeCheckInProgress = true;\r\n this.#lastResumeCheckAt = now;\r\n\r\n try {\r\n await this.#initializeMsal();\r\n\r\n const account = this.#msal.getActiveAccount() ?? this.#msal.getAllAccounts()[0];\r\n\r\n if (!account)\r\n return;\r\n\r\n await this.validateUser(undefined, account);\r\n }\r\n catch (error) {\r\n console.log('Error: Resume auth sync failed.', error);\r\n }\r\n finally {\r\n this.#resumeCheckInProgress = false;\r\n }\r\n }\r\n\r\n // Sends logout signal to other open tabs.\r\n #publishLogout(): void {\r\n this.#channel?.postMessage(this.#logoutMessage);\r\n }\r\n\r\n // Clears app/MSAL state in current tab without invoking provider-side logout.\r\n // reloadAfterLogout is intended for non-initiating tabs to force UI reset to auth route.\r\n async #logoutLocalOnly(reloadAfterLogout: boolean): Promise<void> {\r\n this.#clearTokenRefreshTimer();\r\n\r\n if (this.options.tokenName && this.storage.getItem(this.options.tokenName)) {\r\n this.storage.removeItem(this.options.tokenName);\r\n }\r\n\r\n this.authenticatedUser = undefined;\r\n this.authenticated = false;\r\n this.authenticatedChanged.emit(false);\r\n\r\n try {\r\n await this.#initializeMsal();\r\n await this.#msal.clearCache();\r\n this.#msal.setActiveAccount(null);\r\n\r\n // Secondary tabs should hard-refresh to guarantee route guards and app state reset.\r\n if (reloadAfterLogout && typeof window !== 'undefined') {\r\n window.location.reload();\r\n }\r\n } catch (error) {\r\n console.log('WARN: Local MSAL cache clear failed.', error);\r\n }\r\n }\r\n\r\n // Returns true when token expiration is absent or in the past.\r\n #isTokenExpired(expirationEpochSeconds?: number): boolean {\r\n if (!expirationEpochSeconds) {\r\n return true;\r\n }\r\n\r\n return Date.now() >= expirationEpochSeconds * 1000;\r\n }\r\n\r\n // Attempts silent token acquisition for the current account.\r\n async #refreshToken(account: AccountInfo): Promise<AuthenticationResult | undefined> {\r\n try {\r\n return await this.#msal.acquireTokenSilent({\r\n account,\r\n scopes: this.options.scopes\r\n });\r\n }\r\n catch (error) {\r\n console.log('Error: Silent token refresh failed.', error);\r\n return undefined;\r\n }\r\n }\r\n\r\n // Schedules token refresh shortly before expiration.\r\n // If refresh fails, session is terminated to avoid inconsistent auth state.\r\n #scheduleTokenRefresh(expirationEpochSeconds: number | undefined, account: AccountInfo): void {\r\n this.#clearTokenRefreshTimer();\r\n\r\n if (!expirationEpochSeconds) {\r\n return;\r\n }\r\n\r\n const refreshLeadTimeMs = 60_000;\r\n const millisecondsUntilRefresh = expirationEpochSeconds * 1000 - Date.now() - refreshLeadTimeMs;\r\n const delay = Math.max(millisecondsUntilRefresh, 0);\r\n\r\n this.#tokenRefreshTimeoutId = setTimeout(() => {\r\n this.#refreshToken(account)\r\n .then((result) => {\r\n if (result?.account) {\r\n return this.validateUser(result, result.account);\r\n }\r\n\r\n // No account after refresh implies invalid session.\r\n this.logout();\r\n return undefined;\r\n })\r\n .catch(() => {\r\n // Any refresh exception falls back to logout for safety.\r\n this.logout();\r\n });\r\n }, delay);\r\n }\r\n\r\n // Cancels any pending token refresh timer.\r\n #clearTokenRefreshTimer(): void {\r\n if (!this.#tokenRefreshTimeoutId) {\r\n return;\r\n }\r\n\r\n clearTimeout(this.#tokenRefreshTimeoutId);\r\n this.#tokenRefreshTimeoutId = undefined;\r\n }\r\n //#endregion\r\n}\r\n","import { CommonModule } from '@angular/common';\r\nimport { ModuleWithProviders, NgModule, Optional, SkipSelf } from '@angular/core';\r\n\r\nimport { AuthenticationSSOServiceOptions } from './model/authentication-sso-service-options';\r\nimport { AuthenticationSSOServiceOptionsToken } from './model/authentication-sso-service-options-token';\r\n\r\n@NgModule({\r\n declarations: [],\r\n imports: [\r\n CommonModule\r\n ],\r\n exports: []\r\n})\r\nexport class AuthenticationSSOModule {\r\n static forRoot(options: AuthenticationSSOServiceOptions): ModuleWithProviders<AuthenticationSSOModule> {\r\n return {\r\n ngModule: AuthenticationSSOModule,\r\n providers: [\r\n {\r\n provide: AuthenticationSSOServiceOptionsToken,\r\n useValue: options\r\n }\r\n ]\r\n };\r\n }\r\n\r\n constructor(@Optional() @SkipSelf() parentModule: AuthenticationSSOModule) {\r\n if (parentModule) {\r\n throw new Error(\r\n 'AuthenticationSSOModule is already loaded. Import it in the AppModule only');\r\n }\r\n }\r\n}\r\n","import { inject } from '@angular/core';\r\nimport { CanActivateFn, Router } from '@angular/router';\r\nimport { map, take } from 'rxjs/operators';\r\nimport { AuthenticationSSOService } from '../authentication-sso.api';\r\n\r\nexport const authenticationSSOGuard: CanActivateFn = (_route, _state) => {\r\n const authenticationService = inject(AuthenticationSSOService);\r\n const router = inject(Router);\r\n\r\n // if the user is already authenticated, allow access to the route\r\n if (authenticationService.authenticated) {\r\n return true;\r\n }\r\n\r\n if (authenticationService.tokenExists()) {\r\n // we're doing this because we could've opened a new tab and the user is already logged in, so we need to check for an existing token\r\n authenticationService.checkForExistingToken();\r\n\r\n return authenticationService.authenticatedChanged.pipe(\r\n take(1),\r\n map(() => {\r\n if (!authenticationService.authenticated) {\r\n router.navigate(['']);\r\n return false;\r\n }\r\n\r\n return true;\r\n })\r\n );\r\n }\r\n else {\r\n router.navigate(['']);\r\n return false;\r\n }\r\n};\r\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './authentication-sso.api';\n"],"names":[],"mappings":";;;;;;;;AAGA;AACA;AACA;AACA;AACA;MACa,oCAAoC,GAAG,IAAI,cAAc,CAAkC,iCAAiC;;ACUzI;AACA;AACA;AACA;AACA;AACA;AAIM,MAAO,wBAAyB,SAAQ,iBAAiB,CAAA;;AAe7D,I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a,EAAE;AACvC,QAAA,OAAO,IAAI;;AAGb,IAAA,IAAI,qBAAqB,CAAC,WAAW,EAAE,EAAE;;QAEvC,qBAAqB,CAAC,qBAAqB,EAAE;AAE7C,QAAA,OAAO,qBAAqB,CAAC,oBAAoB,CAAC,IAAI,CACpD,IAAI,CAAC,CAAC,CAAC,EACP,GAAG,CAAC,MAAK;AACP,YAAA,IAAI,CAAC,qBAAqB,CAAC,aAAa,EAAE;AACxC,gBAAA,MAAM,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC;AACrB,gBAAA,OAAO,KAAK;;AAGd,YAAA,OAAO,IAAI;SACZ,CAAC,CACH;;SAEE;AACH,QAAA,MAAM,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC;AACrB,QAAA,OAAO,KAAK;;AAEhB;;AClCA;;AAEG;;;;"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"comment": "NGX-LIB primary entry point package.json",
|
|
3
3
|
"name": "@cleavelandprice/ngx-lib",
|
|
4
|
-
"version": "4.7.
|
|
4
|
+
"version": "4.7.4",
|
|
5
5
|
"description": "Angular library providing foundational functionality to Cleaveland-Price applications",
|
|
6
6
|
"peerDependencies": {
|
|
7
7
|
"@angular/common": "^21.0.0",
|
|
@@ -53,6 +53,10 @@
|
|
|
53
53
|
"types": "./types/cleavelandprice-ngx-lib-authentication-object.d.ts",
|
|
54
54
|
"default": "./fesm2022/cleavelandprice-ngx-lib-authentication-object.mjs"
|
|
55
55
|
},
|
|
56
|
+
"./authentication/sso": {
|
|
57
|
+
"types": "./types/cleavelandprice-ngx-lib-authentication-sso.d.ts",
|
|
58
|
+
"default": "./fesm2022/cleavelandprice-ngx-lib-authentication-sso.mjs"
|
|
59
|
+
},
|
|
56
60
|
"./authentication/token": {
|
|
57
61
|
"types": "./types/cleavelandprice-ngx-lib-authentication-token.d.ts",
|
|
58
62
|
"default": "./fesm2022/cleavelandprice-ngx-lib-authentication-token.mjs"
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { AuthenticationServiceOptions, AbstractAuthenticationService, AuthenticatedUser } from '@cleavelandprice/ngx-lib/authentication';
|
|
2
|
+
import * as i0 from '@angular/core';
|
|
3
|
+
import { InjectionToken, EventEmitter, ModuleWithProviders } from '@angular/core';
|
|
4
|
+
import { NgxLibServiceBase } from '@cleavelandprice/ngx-lib';
|
|
5
|
+
import { AuthenticationResult, AccountInfo } from '@azure/msal-browser';
|
|
6
|
+
import * as i1 from '@angular/common';
|
|
7
|
+
import { CanActivateFn } from '@angular/router';
|
|
8
|
+
|
|
9
|
+
interface AuthenticationSSOServiceOptions extends AuthenticationServiceOptions {
|
|
10
|
+
clientId: string;
|
|
11
|
+
tenantId: string;
|
|
12
|
+
redirectUri: string;
|
|
13
|
+
postLogoutRedirectUri: string;
|
|
14
|
+
scopes: string[];
|
|
15
|
+
cacheLocation?: 'localStorage' | 'sessionStorage';
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
declare const AuthenticationSSOServiceOptionsToken: InjectionToken<AuthenticationSSOServiceOptions>;
|
|
19
|
+
|
|
20
|
+
interface AuthenticationSSOClaims {
|
|
21
|
+
accountName?: string;
|
|
22
|
+
aud?: string;
|
|
23
|
+
department?: string;
|
|
24
|
+
displayName?: string;
|
|
25
|
+
distinguishedName?: string;
|
|
26
|
+
employeeNumber?: string;
|
|
27
|
+
exp?: number;
|
|
28
|
+
firstName?: string;
|
|
29
|
+
hireDate?: string;
|
|
30
|
+
iat?: number;
|
|
31
|
+
iss?: string;
|
|
32
|
+
lastName?: string;
|
|
33
|
+
mail?: string;
|
|
34
|
+
manager?: string;
|
|
35
|
+
memberOf?: string;
|
|
36
|
+
sid?: string;
|
|
37
|
+
oid?: string;
|
|
38
|
+
sub?: string;
|
|
39
|
+
name?: string;
|
|
40
|
+
nbf?: number;
|
|
41
|
+
nonce?: string;
|
|
42
|
+
phone?: string;
|
|
43
|
+
photoUrl?: string;
|
|
44
|
+
preferred_username?: string;
|
|
45
|
+
rh?: string;
|
|
46
|
+
securityIdentifier?: string;
|
|
47
|
+
title?: string;
|
|
48
|
+
given_name?: string;
|
|
49
|
+
family_name?: string;
|
|
50
|
+
email?: string;
|
|
51
|
+
upn?: string;
|
|
52
|
+
tid?: string;
|
|
53
|
+
uti?: string;
|
|
54
|
+
ver?: string;
|
|
55
|
+
workShift?: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
declare class AuthenticationSSOService extends NgxLibServiceBase implements AbstractAuthenticationService {
|
|
59
|
+
#private;
|
|
60
|
+
protected options: AuthenticationSSOServiceOptions;
|
|
61
|
+
authenticating: boolean;
|
|
62
|
+
authenticated: boolean;
|
|
63
|
+
authenticatedUser?: AuthenticatedUser;
|
|
64
|
+
authenticatedChanged: EventEmitter<boolean>;
|
|
65
|
+
authenticatingChanged: EventEmitter<boolean>;
|
|
66
|
+
authenticationError: EventEmitter<any>;
|
|
67
|
+
get useSessionStorage(): boolean;
|
|
68
|
+
get storage(): Storage;
|
|
69
|
+
constructor(options: AuthenticationSSOServiceOptions);
|
|
70
|
+
login(): void;
|
|
71
|
+
logout(): void;
|
|
72
|
+
tokenExists(): boolean;
|
|
73
|
+
validateUser(result?: AuthenticationResult, account?: AccountInfo): Promise<void>;
|
|
74
|
+
checkForExistingToken(): void;
|
|
75
|
+
static ɵfac: i0.ɵɵFactoryDeclaration<AuthenticationSSOService, [{ optional: true; }]>;
|
|
76
|
+
static ɵprov: i0.ɵɵInjectableDeclaration<AuthenticationSSOService>;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
declare class AuthenticationSSOModule {
|
|
80
|
+
static forRoot(options: AuthenticationSSOServiceOptions): ModuleWithProviders<AuthenticationSSOModule>;
|
|
81
|
+
constructor(parentModule: AuthenticationSSOModule);
|
|
82
|
+
static ɵfac: i0.ɵɵFactoryDeclaration<AuthenticationSSOModule, [{ optional: true; skipSelf: true; }]>;
|
|
83
|
+
static ɵmod: i0.ɵɵNgModuleDeclaration<AuthenticationSSOModule, never, [typeof i1.CommonModule], never>;
|
|
84
|
+
static ɵinj: i0.ɵɵInjectorDeclaration<AuthenticationSSOModule>;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
declare const authenticationSSOGuard: CanActivateFn;
|
|
88
|
+
|
|
89
|
+
export { AuthenticationSSOModule, AuthenticationSSOService, AuthenticationSSOServiceOptionsToken, authenticationSSOGuard };
|
|
90
|
+
export type { AuthenticationSSOClaims, AuthenticationSSOServiceOptions };
|