Our internal application requires all users to be authenticated and authorized, including for the home page. To achieve this, we use an HttpInterceptor to add a bearer token to our API requests.
Initially, when rendering the first set of data with the first API call, the token is null
. The token remains null even after receiving it from the getAccessToken()
subscription. However, subsequent API calls work fine, even if the user refreshes the page (F5
).
We are currently using angular 16.1 along with [email protected]. This issue arose when we upgraded from a previous version of angular-auth-oidc-client that did not utilize rxjs subscribe.
import { Injectable, Injector } from "@angular/core";
import { Observable } from "rxjs";
import {
HttpInterceptor,
HttpEvent,
HttpRequest,
HttpHandler,
} from "@angular/common/http";
import { OidcSecurityService } from "angular-auth-oidc-client";
import { Router } from "@angular/router";
import { TokenValidatorService } from "../../services/token-validator.service";
export const UseOidcInterceptorHeader = "X-Oidc-Interceptor";
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
token = null;
constructor(
public oidcSecurityService: OidcSecurityService,
private tokenValidatorService: TokenValidatorService,
private router: Router
) {
this.oidcSecurityService.getAccessToken().subscribe((token) => {
this.token = token
});
}
intercept(
req: HttpRequest<unknown>,
next: HttpHandler
): Observable<HttpEvent<unknown>> {
// we do not intercept authentication calls to "companyAuthServer"
if (req.url.includes("companyAuthServer")) {
return next.handle(req);
}
if (this.token !== null) {
if (!this.tokenValidatorService.checkUserIsInAdGroup(this.token)) {
this.router.navigate(["/oidc/unauthorized"]);
}
const requestForward = req.clone({
setHeaders: { Authorization: "Bearer " + this.token },
});
return next.handle(requestForward);
} else {
console.error(
"OidcSecurityService, token not fetched: NO authorize header!",
req.urlWithParams
);
}
return next.handle(req);
}
}