Implement refresh token functionality and enhance error handling in authentication

This commit is contained in:
liosha84
2025-08-07 13:31:46 +03:00
parent 2e6f4bb870
commit c4c67e1ef1
12 changed files with 325 additions and 13 deletions
@@ -3,10 +3,11 @@ import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { TokenStorageService } from '../services/token-storage.service';
import {catchError, Observable, throwError} from 'rxjs';
import {catchError, Observable, switchMap, throwError} from 'rxjs';
import {EventBusService} from '../_shared/event-bus.service';
import {EventData} from '../_shared/event.class';
import {environment} from '../../environments/environment';
import {AuthService} from '../services/auth.service';
const TOKEN_HEADER_KEY = 'Authorization'; // for Spring Boot back-end
@@ -15,7 +16,11 @@ export class AuthInterceptor implements HttpInterceptor {
private isRefreshing = false;
enviorment = environment;
constructor(private tokenStorageService: TokenStorageService, private eventBusService: EventBusService) { }
constructor(
private tokenStorageService: TokenStorageService,
private eventBusService: EventBusService,
private authService:AuthService
) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
@@ -43,7 +48,22 @@ export class AuthInterceptor implements HttpInterceptor {
this.isRefreshing = true;
if (this.tokenStorageService.isLoggedIn()) {
this.eventBusService.emit(new EventData('logout', null));
return this.authService.refreshToken().pipe(
switchMap(() => {
this.isRefreshing = false;
console.log("refresh token");
return next.handle(request);
}),
catchError((error) => {
this.isRefreshing = false;
if (error.status == '403') {
this.eventBusService.emit(new EventData('logout', null));
}
return throwError(() => error);
})
);
}
}
@@ -36,4 +36,7 @@ export class AuthService {
logout(): Observable<any> {
return this.http.post(AUTH_API + 'signout', { }, httpOptions);
}
refreshToken() {
return this.http.post(AUTH_API + 'refreshtoken', { }, httpOptions);
}
}