add refresh token
This commit is contained in:
@@ -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);
|
||||
})
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user