I’m trying to authenticate to an API first and then "attach" the token to each one of my requests, but the one including ‘connect’.
I have the following:
Interceptor
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (!request.url.includes('/connect/token?grant_type=client_credentials')) {
this.authService.isTokenExist()
.pipe(
catchError((error) => {
return error;
})
)
.subscribe((token: any) => {
if (token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
},
});
}
return next.handle(request);
});
}
return next.handle(request); // here I'm hitting the point without token and I think this is the problem
}
}
Service
import { Injectable } from '@angular/core';
import {
HttpClient,
HttpHeaderResponse,
HttpHeaders,
} from '@angular/common/http';
import { environment } from '../../../environment';
import { urlString } from '../../utils/helpers';
import { Observable, catchError, of } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
export class AuthService {
constructor(private http: HttpClient) {}
getToken(): Observable<string | null> {
const requestBody: Request = {
client_id: environment.client_id,
client_secret: environment.client_secret,
grant_type: environment.grant_type,
scope: environment.scope,
};
const headers = new HttpHeaders().set(
'Content-Type',
'application/x-www-form-urlencoded'
);
const options = { headers };
return this.http
.post<Response>(
`${environment.api_url}/connect/token?grant_type=client_credentials`,
urlString(requestBody),
options
)
.pipe(
catchError((error) => {
throw error;
}),
map((response: Response) => {
this.setToken(response.access_token);
return response.access_token;
})
);
}
getFileMetadata(fileId: number): Observable<any> {
return this.http.get(
`${environment.api_url}/api/v1.4/items/${fileId}/_metadata`
);
}
isTokenExist(): Observable<string | null> {
const tokenTime = localStorage.getItem('token_time');
if (tokenTime) {
const currentTime = new Date().getTime();
const tokenTimeInt = parseInt(tokenTime, 10);
if (currentTime - tokenTimeInt > 86400000) {
return this.getToken();
}
} else {
this.getToken().subscribe({
next: (token) => {
if (token) {
this.setToken(token);
}
return of(token);
},
error: (error) => {
throw error;
}
});
}
return of(localStorage.getItem('token'));
}
setToken(token: string): void {
localStorage.setItem('token_', token);
localStorage.setItem('token_time', new Date().getTime().toString());
}
}
interface Request {
grant_type: string;
client_secret: string;
client_id: string;
scope: string;
}
interface Response {
access_token: string;
token_type: string;
expires_in: number;
}
The result is that on the first-page load, I get 401, as the interceptor is just passing the request. The service returns the token on refresh, and the request passes as expected.
My question is, how can we hold the Interceptor until the token is available and then intercept all other calls?
2
Answers
I did this refactoring in the interceptor:
...and in service, I changed methods like this:
One advice would be to take the token from local storage since your already set it there. Most probably you save it on login and should be available for every call you will do afterwards. You should not call an endpoint in interceptor. Interceptors are primarily designed to inspect and manipulate HTTP requests and responses globally, such as adding headers, logging, or handling errors.
Then in interceptor you can get your token and attach it to header
And then pass the new ‘req’ as your request.