I'm so confused, after playing with my code again, I think I got it working now. And I have no idea what I did differently.
Anyways, here is my working api functions file:
import axios from 'axios';
import {msalConfig} from "../authConfig";
import {msalInstance} from '../main';
const baseURL = import.meta.env.VITE_BASE_URL;
const veryShortTimeout = 5000;
const shortTimeout = 20000;
const medTimeout = 30000;
const longTimeout = 60000;
const delayAPICall: boolean = false;
//const delayAPICall = true;
const secondsDelay = 2;
const axiosInstance = axios.create({
baseURL: baseURL + '/',
delayed: delayAPICall
});
async function getAccessToken(): Promise<string | null> {
const activeAccount = msalInstance.getActiveAccount(); // This will only return a non-null value if you have logic somewhere else that calls the setActiveAccount API
const accounts = msalInstance.getAllAccounts();
console.log({accounts});
if (!activeAccount && accounts.length === 0) {
/*
* User is not signed in. Throw error or wait for user to login.
* Do not attempt to log a user in outside of the context of MsalProvider
*/
}
if (activeAccount || accounts.length > 0) {
const currentAccount = accounts[0];
const accessTokenRequest = {
scopes: [import.meta.env.VITE_QUOTES_API_SCOPE],
account: activeAccount || accounts[0],
};
if (currentAccount && currentAccount.tenantId == msalConfig.auth.tenantId) {
const roles = (currentAccount.idTokenClaims as { [key: string]: any }).roles;
console.log({roles});
if (roles) {
// const intersection = Object.keys(appRoles).filter((role) => roles.includes(role));
// if (intersection.length > 0) {
try {
const accessTokenResponse = await msalInstance.acquireTokenSilent(accessTokenRequest);
return `Bearer ${accessTokenResponse.accessToken}`;
} catch (e) {
console.log({e});
return null;
}
}
}
return null;
}
return null;
}
// let result: { accessToken: string }, msalError: string;
axiosInstance.interceptors.request.use(async (config) => {
config.headers['request-startTime'] = new Date().getTime();
// 07-28-24 - new token code, we can even check the url path if we need to
// if (config.url.indexOf("/admin") !== 0) {
// 8-2-24 - uncomment this next line back in after circular issue is revolved
config.headers.Authorization = await getAccessToken();
// }
// return config;
if (config.delayed) {
// adding delay for now to show loading of resources...
return new Promise((resolve) =>
setTimeout(() => resolve(config), 1000 * secondsDelay)
);
}
return config;
});
axiosInstance.interceptors.response.use((response) => {
const currentTime = new Date().getTime();
const startTime = response.config.headers['request-startTime'];
response.headers['request-duration'] = currentTime - startTime;
return response;
});
export default axiosInstance;