add refresh token

This commit is contained in:
Roland Schneider
2025-11-14 15:28:38 +01:00
parent f4c0bb0b76
commit 42158d1fd4
5 changed files with 36 additions and 23 deletions

View File

@@ -9,14 +9,13 @@ import {
import { Observable, throwError, BehaviorSubject } from 'rxjs';
import { catchError, switchMap, filter, take } from 'rxjs/operators';
import { AuthService } from './auth.service';
import { Router } from '@angular/router';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
private isRefreshing = false;
private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null);
constructor(private authService: AuthService, private router: Router) {}
constructor(private authService: AuthService) {}
intercept(
request: HttpRequest<any>,
@@ -42,9 +41,6 @@ export class JwtInterceptor implements HttpInterceptor {
private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
if (!this.isRefreshing) {
this.isRefreshing = true;
// The subject is now single-use. Re-create it for each refresh cycle.
// The initial `null` value is what makes followers wait.
this.refreshTokenSubject = new BehaviorSubject<any>(null);
return this.authService.refreshToken().pipe(
@@ -55,16 +51,12 @@ export class JwtInterceptor implements HttpInterceptor {
}),
catchError((err) => {
this.isRefreshing = false;
// Propagate the error to all waiting followers and kill the subject.
this.refreshTokenSubject.error(err);
// Perform the logout and redirect
this.authService.logout().subscribe(() => {
this.router.navigate(['/login']);
});
// In a refresh failure, the user MUST be logged out.
// Call the synchronous client-side logout to avoid re-intercepting.
this.authService.clientSideLogout();
// Also ensure the original caller gets the error
return throwError(() => err);
})
);