It may be the answer if your token is follow JWT standard jwt.io
. If you check the link you'll know that the token has sperate into 3 parts and the payload part is just encoded not encrypted, so you can check the payload for token expiration on the client side.
*.interceptor.ts
export class AuthInterceptorService implements HttpInterceptor {
constructor(private authService: AuthService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = this.authService.getAuthToken();
if (token) {
const payload = parseJwt(token); // decode JWT payload part.
if (Date.now() >= payload.exp * 1000) { // Check token exp.
// redirect user to login page or auto refresh user's token and then replace the expired one and continue the process.
return NEVER;
}
// If we have a token, we set it to the header
request = request.clone({
setHeaders: {Authorization: `Authorization token ${token}`}
});
}
return next.handle(request).pipe(
catchError((err) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
// redirect user to the logout page
}
}
return throwError(err);
})
);
}
}
export function parseJwt(token): any {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(window.atob(base64).split('').map((c) => {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
}