admin管理员组文章数量:1336289
My team is using @azure/msal-react to authenticate a user. When the user logs out, we call logoutRedirect()
:
import { useMsal } from '@azure/msal-react';
const { instance } = useMsal();
instance.logoutRedirect({
postLogoutRedirectUri: '/'
});
When this runs, isAuthenticated
becomes false
immediately but there is a delay before the user is redirected to the Microsoft logout screen, causing a flash of our unauthenticated template.
import { useIsAuthenticated } from '@azure/msal-react';
const Layout = () => {
const isAuthenticated = useIsAuthenticated();
if(isAuthenticated) {
return <>Authenticated Template</>;
} else {
// this flashes for a second before seeing the Microsoft account logout screen
return <>Unauthenticated Template</>
}
}
Is there a way to prevent this flash from occurring?
My team is using @azure/msal-react to authenticate a user. When the user logs out, we call logoutRedirect()
:
import { useMsal } from '@azure/msal-react';
const { instance } = useMsal();
instance.logoutRedirect({
postLogoutRedirectUri: '/'
});
When this runs, isAuthenticated
becomes false
immediately but there is a delay before the user is redirected to the Microsoft logout screen, causing a flash of our unauthenticated template.
import { useIsAuthenticated } from '@azure/msal-react';
const Layout = () => {
const isAuthenticated = useIsAuthenticated();
if(isAuthenticated) {
return <>Authenticated Template</>;
} else {
// this flashes for a second before seeing the Microsoft account logout screen
return <>Unauthenticated Template</>
}
}
Is there a way to prevent this flash from occurring?
Share asked Nov 19, 2024 at 18:16 Michael LynchMichael Lynch 3,1594 gold badges39 silver badges70 bronze badges 2 |1 Answer
Reset to default 0To prevent displaying unauthenticated content while the logout request is in progress, you can use the logoutInProgress
state to track the process. Set it to true
when instance.logoutRedirect()
is called, showing a "Logging out..." message instead.
Here is the complete GitHub repository.
Layout.js :
import React, { useState, useEffect } from "react";
import { useMsal, useIsAuthenticated } from "@azure/msal-react";
import { msalInstance } from "../msalConfig";
import AuthenticatedTemplate from "./AuthenticatedTemplate";
import UnauthenticatedTemplate from "./UnauthenticatedTemplate";
function Layout() {
const { instance } = useMsal();
const isAuthenticated = useIsAuthenticated();
const [logoutInProgress, setLogoutInProgress] = useState(false);
const [error, setError] = useState(null);
const [token, setToken] = useState(null);
useEffect(() => {
if (window.location.hash.includes("id_token")) {
msalInstance.handleRedirectPromise()
.then((response) => {
if (response) {
console.log("Login successful: ", response);
setToken(response.accessToken);
}
})
.catch((error) => {
console.error("Login error:", error);
setError(`Login failed: ${error.message}`);
});
}
}, []);
useEffect(() => {
if (logoutInProgress) {
return <div>Logging out...</div>;
}
}, [logoutInProgress]);
return isAuthenticated ? (
<AuthenticatedTemplate handleLogout={handleLogout} token={token} />
) : (
<UnauthenticatedTemplate handleLogin={handleLogin} error={error} />
);
function handleLogin() {
msalInstance.loginRedirect({
scopes: ["https://graph.microsoft/user.read"],
prompt: "select_account",
}).catch((e) => {
console.error("Login error:", e);
setError(`Login failed: ${e.message}`);
});
}
function handleLogout() {
setLogoutInProgress(true);
msalInstance.logoutRedirect({
postLogoutRedirectUri: "/",
});
const cookies = document.cookie.split("; ");
cookies.forEach(cookie => {
const cookieName = cookie.split("=")[0];
document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
});
}
}
export default Layout;
msalConfig.js :
import * as msal from "@azure/msal-browser";
export const msalConfig = {
auth: {
clientId: "<clientID>",
authority: "https://login.microsoftonline/<tenantID>",
redirectUri: "http://localhost:3000",
},
system: {
loggerOptions: {
logLevel: msal.LogLevel.Verbose,
loggerCallback: (level, message, containsPii) => {
if (containsPii) {
console.log(`PII-Log: ${message}`);
} else {
console.log(`Log: ${message}`);
}
},
},
},
};
export const msalInstance = new msal.PublicClientApplication(msalConfig);
AuthenticatedTemplate.js :
import React from "react";
function AuthenticatedTemplate({ handleLogout }) {
return (
<div>
<h1>Welcome! You are logged in.</h1>
<button onClick={handleLogout}>Logout</button>
</div>
);
}
export default AuthenticatedTemplate;
Output :
The Reactjs application ran successfully, and the login page appeared as shown below:
I selected my account to log in, as below,
After successfully logging in, I was redirected to the Logout
page, as shown below,
I logged out by clicking the Logout
button and selected my account to log out without any issues, as shown below.
本文标签:
版权声明:本文标题:azure - Using MSAL in React, how do you prevent a flash of unauthenticated content before logging out? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742406903a2469006.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
logoutInProgress
state to track the logout process. Wheninstance.logoutRedirect()
is called, it should be set to true to prevent displaying the unauthenticated content prematurely, showing a 'Logging out...' message instead. – Dasari Kamali Commented Nov 22, 2024 at 4:52