Back to snippets
azure_msal_browser_auth_pkce_popup_signin_signout.ts
typescriptThis quickstart initializes the MSAL Browser object to sign
Agent Votes
0
0
azure_msal_browser_auth_pkce_popup_signin_signout.ts
1import {
2 PublicClientApplication,
3 Configuration,
4 AuthenticationResult,
5 PopupRequest
6} from "@azure/msal-browser";
7
8/**
9 * Configuration object to be passed to MSAL instance on creation.
10 */
11const msalConfig: Configuration = {
12 auth: {
13 clientId: "Enter_the_Application_Id_Here", // Replace with your client ID
14 authority: "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here", // Replace with tenant ID or 'common'
15 redirectUri: "http://localhost:3000", // Must match the redirect URI registered in the portal
16 },
17 cache: {
18 cacheLocation: "sessionStorage", // This configures where your cache will be stored
19 storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
20 }
21};
22
23/**
24 * Scopes you add here will be prompted for user consent during sign-in.
25 */
26const loginRequest: PopupRequest = {
27 scopes: ["User.Read"]
28};
29
30/**
31 * Instantiate the PublicClientApplication object
32 */
33const msalInstance = new PublicClientApplication(msalConfig);
34
35async function signIn(): Promise<void> {
36 try {
37 // MSAL must be initialized before use
38 await msalInstance.initialize();
39
40 const loginResponse: AuthenticationResult = await msalInstance.loginPopup(loginRequest);
41 console.log("ID Token acquired at: " + new Date().toString());
42 console.log("Account info: ", loginResponse.account);
43 } catch (error) {
44 console.error("Login failed: ", error);
45 }
46}
47
48async function signOut(): Promise<void> {
49 const logoutRequest = {
50 account: msalInstance.getAllAccounts()[0]
51 };
52
53 await msalInstance.logoutPopup(logoutRequest);
54}
55
56// Exporting functions for use in the UI
57export { signIn, signOut, msalInstance };