-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathauthConfig.ts
More file actions
55 lines (49 loc) · 1.46 KB
/
authConfig.ts
File metadata and controls
55 lines (49 loc) · 1.46 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import {
createStandardPublicClientApplication,
InteractionRequiredAuthError,
type IPublicClientApplication,
type RedirectRequest,
} from '@azure/msal-browser';
export const loginRequest = {
scopes: ['User.Read'],
};
export const graphConfig = {
graphMeEndpoint: 'https://graph.microsoft.com/v1.0/me',
};
export const initMsalClient = async () => {
const iPca = await createStandardPublicClientApplication({
auth: {
clientId: import.meta.env.PUBLIC_AZURE_CLIENT_ID,
authority: `https://login.microsoftonline.com/${import.meta.env.PUBLIC_AZURE_TENANT_ID}`,
navigateToLoginRequestUrl: false,
},
});
await iPca.initialize();
return iPca;
};
export const getUserAccessToken = async (
pca: IPublicClientApplication,
returnPath?: string
): Promise<string> => {
const account = pca.getActiveAccount() || pca.getAllAccounts()[0];
const request: RedirectRequest = {
...loginRequest,
account: account || undefined,
redirectUri: '/auth-redirect',
state: returnPath ?? window.location.pathname + window.location.search,
};
if (!account) {
await pca.loginRedirect(request);
throw new Error('Redirecting to login');
}
try {
const response = await pca.acquireTokenSilent(request);
return response.accessToken;
} catch (e) {
if (e instanceof InteractionRequiredAuthError) {
await pca.acquireTokenRedirect(request);
throw new Error('Redirecting to login', { cause: e });
}
throw e;
}
};