Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Microsoft Authentication Library (MSAL) for JS
import { UserAgentApplication, Logger, LogLevel } from "msal";
export const isIE = () => {
const ua = window.navigator.userAgent;
const msie = ua.indexOf("MSIE ") > -1;
const msie11 = ua.indexOf("Trident/") > -1;
// If you as a developer are testing using Edge InPrivate mode, please add "isEdge" to the if check
// const isEdge = ua.indexOf("Edge/") > -1;
return msie || msie11;
};
const msalApp = new UserAgentApplication({
auth: {
clientId: "245e9392-c666-4d51-8f8a-bfd9e55b2456",
authority: "https://login.microsoftonline.com/common",
redirectUri: "http://localhost:3000/auth.html",
validateAuthority: true,
postLogoutRedirectUri: "http://localhost:3000",
navigateToLoginRequestUrl: false
},
cache: {
cacheLocation: "sessionStorage",
storeAuthStateInCookie: isIE()
},
system: {
navigateFrameWait: 500,
logger: new Logger((logLevel, message) => {
console.log(message);
}, {
level: LogLevel.Verbose,
piiLoggingEnabled: true
}),
telemetry: {
applicationName: "react-sample-app",
applicationVersion: "1.0.0",
telemetryEmitter: (events) => {
console.log('Telemetry Events:', events);
}
}
}
});
export interface MSALRequest {
scopes: string[]
}
export class AzureADAuthProvider {
requiresInteraction(errorMessage) {
if (!errorMessage || !errorMessage.length) {
return false;
}
return (
errorMessage.indexOf("consent_required") > -1 ||
errorMessage.indexOf("interaction_required") > -1 ||
errorMessage.indexOf("login_required") > -1
);
};
acquireToken(request: MSALRequest, redirect?: boolean) {
return msalApp.acquireTokenSilent(request).catch(error => {
// Call acquireTokenPopup (popup window) in case of acquireTokenSilent failure
// due to consent or interaction required ONLY
if (this.requiresInteraction(error.errorCode)) {
return redirect
? msalApp.acquireTokenRedirect({
...request,
redirectUri: "http://localhost:3000"
})
: msalApp.acquireTokenPopup(request);
} else {
console.error('Non-interactive error:', error)
}
});
}
async signIn(request: MSALRequest, redirect?: boolean) {
if (redirect) {
return msalApp.loginRedirect({
...request,
redirectUri: "http://localhost:3000"
});
}
const loginResponse = await msalApp.loginPopup(request);
if (loginResponse) {
const tokenResponse = await this.acquireToken(request);
if (tokenResponse) {
return {
account: loginResponse.account,
accessToken: tokenResponse.accessToken
}
}
}
return null;
}
signOut() {
msalApp.logout();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment