I have to fix an issue related to the Microsoft azure authentication. Right now, when the user clicks on the sign out button, the user logs out, but he/she is directly logged in into the web.
I want the user to be redirect to the web and only if the user clicks on the sign in button, he/she is logged in in the web.
I don’t know how to prevent the fact that the user is signed is automatically.
I have this file:
const branchUrl = new RegExp(/\/BUY-\d{4}/).exec(window.location.pathname)?.[0] ?? '';
const msalConfig: Configuration = {
auth: {
authority: `https://login.microsoftonline.com/${process.env.REACT_APP_AZURE_TENANT_ID}`,
clientId: `${process.env.REACT_APP_AZURE_CLIENT_ID}`,
redirectUri: `${window.location.origin}${branchUrl}`,
postLogoutRedirectUri: `${window.location.origin}${branchUrl}`,
navigateToLoginRequestUrl: false,
},
cache: {
cacheLocation: 'localStorage',
},
};
const msalLoginRequest: PopupRequest = {
scopes: [
'User.Read',
],
};
const msalInstance = new PublicClientApplication(msalConfig);
const accounts = msalInstance.getAllAccounts();
if (accounts.length > 0) {
msalInstance.setActiveAccount(accounts[0]);
}
msalInstance.addEventCallback((event: EventMessage) => {
if (event.eventType === EventType.LOGIN_SUCCESS && event.payload) {
const payload = event.payload as AuthenticationResult;
const account = payload.account;
msalInstance.setActiveAccount(account);
}
});
export const msalService = {
msalInstance,
msalLoginRequest,
};
Any solution?
this is the component that has the buttons and the logic.
export const Header = ({ styleNumber, setStyleNumber, generalQuery, setGeneralQuery }: HeaderProps): ReactElement => {
const { login } = useContext(AuthorizationContext);
const { instance, accounts } = useMsal();
const isAuthenticated = useIsAuthenticated();
const account = useAccount(accounts[0] || {});
const handleOnSignIn = (): void =>{
login();
};
const handleSignOut = (): void => {
instance.logoutRedirect({
account,
}).then(() => {
})
.catch((error) => {
// Handle logout error if needed
console.error('Logout error:', error);
});
};
return (
<Box
sx={{
height: '24px',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
paddingLeft: 10,
flex: 1,
}}
>
{isAuthenticated ? (
<Box
sx={{
display: 'flex',
alignItems: 'center',
}}
>
<UserInfo />
<Button key="signOut-button" size="large" sx={{ marginLeft: 2 }} onClick=
{handleSignOut}>
Sign Out
</Button>
<Button component="label" variant="contained" startIcon={<PlusIcon />} sx={{
marginLeft: 2 }} onClick={handleCreateCertificate}>
Create a new certificate
</Button>
</Box>
) : (
<Button key="signIn-button" size="large" sx={{ marginLeft: 2 }} onClick=
{handleOnSignIn}>
Sign In
</Button>
)}
</Box>
);
};