3
How to make the token be created at the same time the method gets:
The way I implemented it, it checks that the token was created, but the token used for the request is the expired token. Only after it runs the Intercept method, it creates the new token.
export class JwtInterceptorService implements HttpInterceptor {
constructor(
private authService: AuthService
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const header = request.urlWithParams.indexOf('/oauth/token');
let token = this.authService.getToken();
console.log('TOKEN', token);
if (header === -1 && this.authService.isAccessTokenInvalid()) {
this.authService.obterNovoAccessToken();
token = localStorage.getItem('token');
console.log('NOVO TOKEN', token);
}
if (token && header === -1 && request.url.match(environment.apiUrl)) {
const cloned = request.clone({
headers: request.headers.set('Authorization', `Bearer ${token}`)
});
return next.handle(cloned);
} else {
return next.handle(request);
}
}
}
obterNovoAccessToken(): Promise<void> {
const headers = new HttpHeaders()
.append('Content-Type', 'application/x-www-form-urlencoded')
.append('Authorization', 'Basic YW5ndWxhcjpAbmd1bGFyMA==');
const body = 'grant_type=refresh_token';
return this.http.post<any>(this.oauthTokenUrl, body, { headers, withCredentials: true })
.toPromise()
.then(response => {
this.armazenarToken(response.access_token);
return Promise.resolve(null);
})
.catch(response => {
return Promise.resolve(null);
});
}
The problem with your code is that you’re treating something asynchronously
– Eduardo Vargas