I'm implementing msal-v1 in my angular 7 application and I would like to implement my own interceptor where I get access token by calling acquireTokenSilent and then attaching the token to the http headers.
as the acquireTokenSilent is asynchronous, the token in the http headers is always empty, I need the application to wait until retrieve token and then set the headers.
First approach:
const acquireToken = async () => {
let token = "";
const authRequest = {
scopes: ["user.read"],
};
try {
const resp = await this.authService.acquireTokenSilent(authRequest);
token = resp.accessToken;
} catch (err) {
if (err instanceof InteractionRequiredAuthError) {
await this.authService.acquireTokenRedirect(authRequest);
}
}
return token;
};
return next.handle(
httpRequest.clone({
setHeaders: {
Authorization: `Bearer ${this.token}`,
},
})
);
Second Approach:
const authRequest = {
scopes: ["clientID/.default"],
};
var token = this.getAuthenticationToken(authRequest);
return next.handle(
httpRequest.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
},
})
);
}
------------------
public getAuthenticationToken(authRequest): Promise<string> {
return this.authService
.acquireTokenSilent(authRequest)
.then((token) => {
console.log("Got silent access token: ", token);
return token.accessToken;
})
.catch((error) => {
console.log("Could not silently retrieve token from storage.", error);
return this.authService
.acquireTokenPopup(authRequest)
.then((token) => {
console.log("Got popup access token: ", token);
return token.accessToken;
})
.catch((error) => {
console.log("Could not retrieve token from popup.", error);
this.authService.acquireTokenRedirect(authRequest);
return Promise.resolve("");
});
});
}
but nothing seems to work, can anyone help me to make the acquireTokenSilent as synchronous.
The reason I'm doing this approach is because I need to make the user to stay active with silent renew token in the background.