-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
50 lines (48 loc) · 1.74 KB
/
Copy pathauth.js
File metadata and controls
50 lines (48 loc) · 1.74 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
//MSAL configuration
const msalConfig = {
auth: {
clientId: 'dd2dc770-8400-4351-a2e1-52b2c7ae3564',
// comment out if you use a multi-tenant AAD app
authority: 'https://login.microsoftonline.com/e8ce889a-ba5e-4fbc-ae63-d095a9b60d95',
redirectUri: 'http://localhost:8080'
}
};
const msalRequest = { scopes: [] };
function ensureScope (scope) {
if (!msalRequest.scopes.some((s) => s.toLowerCase() === scope.toLowerCase())) {
msalRequest.scopes.push(scope);
}
}
//Initialize MSAL client
const msalClient = new msal.PublicClientApplication(msalConfig);
// Log the user in
async function signIn() {
const authResult = await msalClient.loginPopup(msalRequest);
sessionStorage.setItem('msalAccount', authResult.account.username);
}
//Get token from Graph
async function getToken() {
let account = sessionStorage.getItem('msalAccount');
if (!account) {
throw new Error(
'User info cleared from session. Please sign out and sign in again.');
}
try {
// First, attempt to get the token silently
const silentRequest = {
scopes: msalRequest.scopes,
account: msalClient.getAccountByUsername(account)
};
const silentResult = await msalClient.acquireTokenSilent(silentRequest);
return silentResult.accessToken;
} catch (silentError) {
// If silent requests fails with InteractionRequiredAuthError,
// attempt to get the token interactively
if (silentError instanceof msal.InteractionRequiredAuthError) {
const interactiveResult = await msalClient.acquireTokenPopup(msalRequest);
return interactiveResult.accessToken;
} else {
throw silentError;
}
}
}