I am currently developing an authentication system using Angular with a Django backend that utilizes JWT. Within my Angular interceptor, I have implemented a check in each request to validate the access token's status. If the token is deemed invalid, a refreshtoken function is called to refresh the access token.
Below is the code for the interceptor:
constructor(private authService:AuthService) {}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
let access_token = localStorage.getItem("access_token");
if(access_token){
// Verify validity of access token and refresh it using the refresh token if needed
if(this.authService.isLoggedOut()){
this.authService.refreshToken();
access_token = localStorage.getItem("access_token");
}
const cloned = request.clone({
headers: request.headers.set("Authorization", "Bearer " + access_token)
});
return next.handle(cloned);
}
else{
return next.handle(request);
}
This process extracts the access_token and validates it through the auth service. However, if it is found to be invalid, the refreshToken() function is invoked:
refreshToken(){
let refresh_token = localStorage.getItem("refresh_token");
console.log("BEFORE REFRESH: " + localStorage.getItem("access_token"));
return this.http.post(`${apiUrl}token/refresh/`, {"refresh" : refresh_token}).subscribe(res => {
let access_token = res["access"]
const expiresAt = this.tokenExpiresAt(access_token);
localStorage.setItem("access_token", access_token);
localStorage.setItem("expires_at", JSON.stringify(expiresAt.valueOf()));
console.log("AFTER REFRESH: " + localStorage.getItem("access_token"));
});
}
The issue arises when the interceptor fails to wait for the completion of the refreshToken() function, causing errors in the initial request with an invalid token. Subsequent requests are unaffected. How can I modify this to ensure that the refreshToken() function finishes before proceeding?
Thank you for your help!