You need to use an Httpinterceptor.
For that you create a service of this kind:
@Injector()
export class RequestInterceptorService implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// adiciona o token desta forma
// neste exemplo o token, quando existe, está guardado na localstorage
if (localStorage.getItem('accessToken')) {
request = request.clone({
setHeaders: {
Authorization: 'Bearer ' + localStorage.getItem('accessToken')
}
});
}
return next.handle(request).pipe(
tap(
event => { },
error => {
this.handleErrors(error);
}
),
finalize(() => { })
);
}
private handleErrors(err: HttpErrorResponse) {
let errorMessage: string;
if (err.status === 0) {
errorMessage = 'Sem ligação à internet';
} else if (err.status === 401) { // O token expirou ou nem foi enviado. Fazer novamente autenticação.
this.router.navigate(['/login']);
} else { // ocorreu outro erro. Mostrar mensagem ao utilizador
errorMessage = err.error.message;
}
if(errorMessage) {
// mostrar mensagem em modal, por exemplo
}
}
}
And you add the service to HTTP_INTERCEPTORS providers:
@NgModule({
declarations: [
// ...
],
imports: [
// ...
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: RequestInterceptorService,
multi: true,
}
],
})
export class AppModule { }
This is already what I do in my Interceptor currently, I need to make a previous http request to see if the token is still valid, and only if it is valid to put it in the next request
– veroneseComS
@Renatoveronese This will slow down the application. The best way is to let the server respond that the token has expired. Updated response code for this scenario.
– António
I know, but my boss wants it that way, I already explained that this is done in the backend through the token but he wants one more validation
– veroneseComS
@Renatoveronese And explained that for every request made, you will always have an extra to validate the token, what will make the site/webapp slower and double the load on the server? The only thing that made sense to me was validating the expiration date to token. If you’re using something like JWT, in the token itself you have that information embedded. https://gist.github.com/soulmachine/b368ce7292ddd7f91c15accccc02b8df
– António