feat(auth): prepare MSAL browser integration
This commit is contained in:
@@ -0,0 +1,105 @@
|
||||
import {
|
||||
InteractionRequiredAuthError,
|
||||
PublicClientApplication,
|
||||
} from "@azure/msal-browser";
|
||||
|
||||
let msalInstance = null;
|
||||
let apiScope = "";
|
||||
|
||||
function requireInstance() {
|
||||
if (!msalInstance) {
|
||||
throw new Error("MSAL n'est pas initialise.");
|
||||
}
|
||||
|
||||
return msalInstance;
|
||||
}
|
||||
|
||||
function activeAccount() {
|
||||
const instance = requireInstance();
|
||||
return instance.getActiveAccount() ?? instance.getAllAccounts()[0] ?? null;
|
||||
}
|
||||
|
||||
async function initialize(tenantId, clientId, scope, redirectUri) {
|
||||
if (msalInstance) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!tenantId || !clientId || !scope || !redirectUri) {
|
||||
throw new Error("La configuration Azure du frontend est incomplete.");
|
||||
}
|
||||
|
||||
apiScope = scope;
|
||||
msalInstance = await PublicClientApplication.createPublicClientApplication({
|
||||
auth: {
|
||||
clientId,
|
||||
authority: `https://login.microsoftonline.com/${tenantId}`,
|
||||
redirectUri,
|
||||
postLogoutRedirectUri: redirectUri,
|
||||
},
|
||||
cache: {
|
||||
cacheLocation: "sessionStorage",
|
||||
},
|
||||
});
|
||||
|
||||
const account = activeAccount();
|
||||
if (account) {
|
||||
msalInstance.setActiveAccount(account);
|
||||
}
|
||||
}
|
||||
|
||||
async function signIn() {
|
||||
const instance = requireInstance();
|
||||
const result = await instance.loginPopup({
|
||||
scopes: ["openid", "profile", "email", apiScope],
|
||||
});
|
||||
|
||||
instance.setActiveAccount(result.account);
|
||||
}
|
||||
|
||||
async function getAccessToken() {
|
||||
const instance = requireInstance();
|
||||
const account = activeAccount();
|
||||
if (!account) {
|
||||
throw new Error("Aucun compte Microsoft connecte.");
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await instance.acquireTokenSilent({
|
||||
account,
|
||||
scopes: [apiScope],
|
||||
});
|
||||
return result.accessToken;
|
||||
} catch (error) {
|
||||
if (!(error instanceof InteractionRequiredAuthError)) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
const result = await instance.acquireTokenPopup({
|
||||
account,
|
||||
scopes: [apiScope],
|
||||
});
|
||||
return result.accessToken;
|
||||
}
|
||||
}
|
||||
|
||||
function hasAccount() {
|
||||
return activeAccount() !== null;
|
||||
}
|
||||
|
||||
async function signOut() {
|
||||
const instance = requireInstance();
|
||||
const account = activeAccount();
|
||||
if (!account) {
|
||||
return;
|
||||
}
|
||||
|
||||
await instance.logoutPopup({ account });
|
||||
}
|
||||
|
||||
globalThis.emeMsal = {
|
||||
getAccessToken,
|
||||
hasAccount,
|
||||
initialize,
|
||||
signIn,
|
||||
signOut,
|
||||
};
|
||||
Reference in New Issue
Block a user