add refresh token
This commit is contained in:
@@ -16,7 +16,8 @@ export class App {
|
||||
constructor(private authService: AuthService, private router: Router) {}
|
||||
|
||||
logout(): void {
|
||||
this.authService.logout();
|
||||
this.router.navigate(['/login']);
|
||||
this.authService.logout().subscribe(() => {
|
||||
this.router.navigate(['/login']);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,36 +1,62 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { tap } from 'rxjs/operators';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class AuthService {
|
||||
private readonly TOKEN_KEY = 'access_token';
|
||||
private readonly ACCESS_TOKEN_KEY = 'accessToken';
|
||||
private readonly REFRESH_TOKEN_KEY = 'refreshToken';
|
||||
private apiUrl = 'http://localhost:4200/api/auth'; // Adjust if your server URL is different
|
||||
|
||||
constructor(private http: HttpClient) {}
|
||||
|
||||
login(credentials: { username: string; password: string }): Observable<any> {
|
||||
return this.http.post<{ access_token: string }>(`${this.apiUrl}/login`, credentials).pipe(
|
||||
tap((response) => this.setToken(response.access_token))
|
||||
return this.http.post<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/login`, credentials).pipe(
|
||||
tap((response) => this.setTokens(response.accessToken, response.refreshToken))
|
||||
);
|
||||
}
|
||||
|
||||
logout(): void {
|
||||
localStorage.removeItem(this.TOKEN_KEY);
|
||||
logout(): Observable<any> {
|
||||
return this.http.post(`${this.apiUrl}/logout`, {}).pipe(
|
||||
tap(() => this.removeTokens())
|
||||
);
|
||||
}
|
||||
|
||||
getToken(): string | null {
|
||||
return localStorage.getItem(this.TOKEN_KEY);
|
||||
refreshToken(): Observable<any> {
|
||||
const refreshToken = this.getRefreshToken();
|
||||
if (!refreshToken) {
|
||||
return of(null);
|
||||
}
|
||||
|
||||
return this.http.post<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/refresh`, {}, {
|
||||
headers: { Authorization: `Bearer ${refreshToken}` }
|
||||
}).pipe(
|
||||
tap((response) => this.setTokens(response.accessToken, response.refreshToken))
|
||||
);
|
||||
}
|
||||
|
||||
getAccessToken(): string | null {
|
||||
return localStorage.getItem(this.ACCESS_TOKEN_KEY);
|
||||
}
|
||||
|
||||
getRefreshToken(): string | null {
|
||||
return localStorage.getItem(this.REFRESH_TOKEN_KEY);
|
||||
}
|
||||
|
||||
isLoggedIn(): boolean {
|
||||
return this.getToken() !== null;
|
||||
return this.getAccessToken() !== null;
|
||||
}
|
||||
|
||||
private setToken(token: string): void {
|
||||
localStorage.setItem(this.TOKEN_KEY, token);
|
||||
private setTokens(accessToken: string, refreshToken: string): void {
|
||||
localStorage.setItem(this.ACCESS_TOKEN_KEY, accessToken);
|
||||
localStorage.setItem(this.REFRESH_TOKEN_KEY, refreshToken);
|
||||
}
|
||||
|
||||
private removeTokens(): void {
|
||||
localStorage.removeItem(this.ACCESS_TOKEN_KEY);
|
||||
localStorage.removeItem(this.REFRESH_TOKEN_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,26 +4,86 @@ import {
|
||||
HttpHandler,
|
||||
HttpInterceptor,
|
||||
HttpRequest,
|
||||
HttpErrorResponse,
|
||||
} from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
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 {
|
||||
constructor(private authService: AuthService) {}
|
||||
private isRefreshing = false;
|
||||
private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null);
|
||||
|
||||
constructor(private authService: AuthService, private router: Router) {}
|
||||
|
||||
intercept(
|
||||
request: HttpRequest<any>,
|
||||
next: HttpHandler
|
||||
): Observable<HttpEvent<any>> {
|
||||
const token = this.authService.getToken();
|
||||
if (token) {
|
||||
request = request.clone({
|
||||
setHeaders: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
const accessToken = this.authService.getAccessToken();
|
||||
|
||||
if (accessToken) {
|
||||
request = this.addToken(request, accessToken);
|
||||
}
|
||||
return next.handle(request);
|
||||
|
||||
return next.handle(request).pipe(
|
||||
catchError((error) => {
|
||||
if (error instanceof HttpErrorResponse && error.status === 401) {
|
||||
return this.handle401Error(request, next);
|
||||
} else {
|
||||
return throwError(() => error);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
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(
|
||||
switchMap((token: any) => {
|
||||
this.isRefreshing = false;
|
||||
this.refreshTokenSubject.next(token.accessToken);
|
||||
return next.handle(this.addToken(request, token.accessToken));
|
||||
}),
|
||||
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']);
|
||||
});
|
||||
|
||||
// Also ensure the original caller gets the error
|
||||
return throwError(() => err);
|
||||
})
|
||||
);
|
||||
} else {
|
||||
return this.refreshTokenSubject.pipe(
|
||||
filter((token) => token != null),
|
||||
take(1),
|
||||
switchMap((jwt) => {
|
||||
return next.handle(this.addToken(request, jwt));
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private addToken(request: HttpRequest<any>, token: string) {
|
||||
return request.clone({
|
||||
setHeaders: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user