Commits

Marie Verdonck authored b23522d39fd
79700: Auto-refreshing the token & Needed config
No tags

src/app/core/auth/auth.interceptor.ts

Modified
21 21 import { hasValue, isNotEmpty, isNotNull, isUndefined } from '../../shared/empty.util';
22 22 import { RedirectWhenTokenExpiredAction, RefreshTokenAction } from './auth.actions';
23 23 import { Store } from '@ngrx/store';
24 24 import { Router } from '@angular/router';
25 25 import { AuthMethod } from './models/auth.method';
26 26 import { AuthMethodType } from './models/auth.method-type';
27 27
28 28 @Injectable()
29 29 export class AuthInterceptor implements HttpInterceptor {
30 30
31 - // Intercetor is called twice per request,
31 + // Interceptor is called twice per request,
32 32 // so to prevent RefreshTokenAction is dispatched twice
33 33 // we're creating a refresh token request list
34 34 protected refreshTokenRequestUrls = [];
35 35
36 36 constructor(private inj: Injector, private router: Router, private store: Store<AppState>) {
37 37 }
38 38
39 39 /**
40 40 * Check if response status code is 401
41 41 *
209 209 */
210 210 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
211 211
212 212 const authService = this.inj.get(AuthService);
213 213
214 214 const token: AuthTokenInfo = authService.getToken();
215 215 let newReq: HttpRequest<any>;
216 216 let authorization: string;
217 217
218 218 if (authService.isTokenExpired()) {
219 - authService.setRedirectUrl(this.router.url);
220 - // The access token is expired
221 - // Redirect to the login route
222 - this.store.dispatch(new RedirectWhenTokenExpiredAction('auth.messages.expired'));
223 219 return observableOf(null);
224 220 } else if ((!this.isAuthRequest(req) || this.isLogoutResponse(req)) && isNotEmpty(token)) {
225 - // Intercept a request that is not to the authentication endpoint
226 - authService.isTokenExpiring().pipe(
227 - filter((isExpiring) => isExpiring))
228 - .subscribe(() => {
229 - // If the current request url is already in the refresh token request list, skip it
230 - if (isUndefined(find(this.refreshTokenRequestUrls, req.url))) {
231 - // When a token is about to expire, refresh it
232 - this.store.dispatch(new RefreshTokenAction(token));
233 - this.refreshTokenRequestUrls.push(req.url);
234 - }
235 - });
236 221 // Get the auth header from the service.
237 222 authorization = authService.buildAuthHeader(token);
238 223 let newHeaders = req.headers.set('authorization', authorization);
239 224
240 225 // When present, add the ID of the EPerson we're impersonating to the headers
241 226 const impersonatingID = authService.getImpersonateID();
242 227 if (hasValue(impersonatingID)) {
243 228 newHeaders = newHeaders.set('X-On-Behalf-Of', impersonatingID);
244 229 }
245 230

Everything looks good. We'll let you know here if there's anything you should know about.

Add shortcut