piral-adal
Version:
Plugin to integrate AAD authentication in Piral.
62 lines • 2.08 kB
JavaScript
import { UserAgentApplication } from 'msal';
function retrieveToken(msalInstance, auth) {
if (msalInstance.getAccount()) {
return msalInstance
.acquireTokenSilent(auth)
.then((response) => response.accessToken)
.catch((err) => {
if (err.name === 'InteractionRequiredAuthError') {
return msalInstance
.acquireTokenPopup(auth)
.then((response) => response.accessToken)
.catch((err) => Promise.reject(err && err.message));
}
console.error(err);
return Promise.reject('Could not fetch token');
});
}
return Promise.reject('Not logged in');
}
/**
* Sets up a new client wrapping the MSAL API.
* @param config The configuration for the client.
*/
export function setupAdalClient(config) {
const { redirectUri = `${location.origin}/auth`, restrict = false, scopes = ['User.Read'], storeAuthStateInCookie, cacheLocation = 'sessionStorage', framework, system, ...remainingOptions } = config;
const msalInstance = new UserAgentApplication({
auth: {
redirectUri,
...remainingOptions,
},
cache: {
storeAuthStateInCookie,
cacheLocation,
},
system,
framework,
});
const tokenRequest = { scopes };
msalInstance.handleRedirectCallback(() => { });
return {
login() {
msalInstance.loginRedirect(tokenRequest);
},
logout() {
msalInstance.logout();
},
account() {
return msalInstance.getAccount();
},
extendHeaders(req) {
if (!restrict) {
req.setHeaders(retrieveToken(msalInstance, tokenRequest).then((token) => token && {
Authorization: `Bearer ${token}`,
}, () => undefined));
}
},
token() {
return retrieveToken(msalInstance, tokenRequest);
},
};
}
//# sourceMappingURL=setup.js.map