-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAxiosmsal.tsx
39 lines (33 loc) · 1.14 KB
/
Axiosmsal.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// api.ts
import axios, { AxiosInstance } from 'axios';
import { useMsal } from '@azure/msal-react';
import { apiEndpoint } from './authConfig';
const instance: AxiosInstance = axios.create({
baseURL: apiEndpoint, // Replace with your API endpoint
timeout: 5000,
});
export const useAxiosWithAuth = () => {
const { accounts, instance } = useMsal();
// Add event callback to handle login success event
instance.addEventCallback((response) => {
if (response.eventType === 'loginSuccess') {
const account = response.payload.account;
const accessToken = response.payload.idTokenClaims?.accessToken;
if (account && accessToken) {
instance.setActiveAccount(account);
instance.setAccessToken(accessToken);
}
}
});
// Add interceptor to include bearer token in request headers
instance.interceptors.request.use((config) => {
const activeAccount = accounts[0] || null;
const accessToken = activeAccount?.idTokenClaims?.accessToken;
if (accessToken) {
config.headers.Authorization = `Bearer ${accessToken}`;
}
return config;
});
return instance;
};
export default instance;