fixed login loop

This commit is contained in:
idittrich-valueon 2025-05-16 15:38:31 +02:00
parent 9e8d34a7ac
commit 6136c4fa1b
5 changed files with 32 additions and 42 deletions

4
.env
View file

@ -1,5 +1,5 @@
VITE_API_URL="https://gateway.poweron-center.net" #VITE_API_URL="https://gateway.poweron-center.net"
VITE_API_URL="http://127.0.0.1:8000"
VITE_MICROSOFT_CLIENT_ID="24cd6c8a-b592-4905-a5ba-d5fa9f911154" VITE_MICROSOFT_CLIENT_ID="24cd6c8a-b592-4905-a5ba-d5fa9f911154"
VITE_MICROSOFT_TENANT_ID="6a51aaeb-2467-4186-9504-2a05aedc591f" VITE_MICROSOFT_TENANT_ID="6a51aaeb-2467-4186-9504-2a05aedc591f"
VITE_ENTRA_CLIENT_SECRET="2iw8Q~jwqG1iacxHopBt5pstu6R45UC1gIQabcbD" VITE_ENTRA_CLIENT_SECRET="2iw8Q~jwqG1iacxHopBt5pstu6R45UC1gIQabcbD"

View file

@ -2,7 +2,8 @@
import axios from 'axios'; import axios from 'axios';
const api = axios.create({ const api = axios.create({
baseURL: 'https://gateway.poweron-center.net', /*baseURL: 'https://gateway.poweron-center.net',*/
baseURL: 'http://localhost:8000',
withCredentials: true withCredentials: true
}); });

View file

@ -65,39 +65,6 @@ import {
initializeMsal(); initializeMsal();
}, []); }, []);
// Separate login effect with protection against loops
useEffect(() => {
if (!isInitialized || !msalInstance || loginAttempted) return;
const accounts = msalInstance.getAllAccounts();
if (accounts.length === 0) {
// Set a flag to avoid repeated login attempts
setLoginAttempted(true);
// Check local/session storage for redirect in progress
const inProgress = sessionStorage.getItem("msal.interaction.status");
if (inProgress === "login" || inProgress === "handleRedirect") {
console.log("Login already in progress according to session storage");
return;
}
console.log("No accounts found, triggering login...");
// Use a small timeout to ensure everything is ready
const loginTimer = setTimeout(() => {
msalInstance.loginRedirect({
scopes: ["openid", "profile", "email"]
}).catch(error => {
console.error("Login redirect failed:", error);
// Reset the flag if login fails
setLoginAttempted(false);
});
}, 500);
return () => clearTimeout(loginTimer);
}
}, [isInitialized, msalInstance, loginAttempted]);
if (!isInitialized || !msalInstance) { if (!isInitialized || !msalInstance) {
return <div>Loading authentication...</div>; return <div>Loading authentication...</div>;
} }

View file

@ -30,9 +30,11 @@ export function useMsalAuth(): UseMsalAuthReturn {
try { try {
let msalToken; let msalToken;
console.log("Starting MSAL auth process");
// If we have an account, try to get the token silently // If we have an account, try to get the token silently
if (accounts.length > 0) { if (accounts.length > 0) {
console.log("Account found, trying silent token acquisition");
const silentRequest = { const silentRequest = {
scopes: ['user.read'], scopes: ['user.read'],
account: accounts[0] account: accounts[0]
@ -41,28 +43,36 @@ export function useMsalAuth(): UseMsalAuthReturn {
try { try {
const response = await instance.acquireTokenSilent(silentRequest); const response = await instance.acquireTokenSilent(silentRequest);
msalToken = response.accessToken; msalToken = response.accessToken;
console.log("Silent token acquisition successful");
} catch (e) { } catch (e) {
// If silent token acquisition fails, fall back to popup // If silent token acquisition fails, fall back to popup
console.log("Silent token acquisition failed, trying popup", e);
const response = await instance.acquireTokenPopup(silentRequest); const response = await instance.acquireTokenPopup(silentRequest);
msalToken = response.accessToken; msalToken = response.accessToken;
console.log("Popup token acquisition successful");
} }
} else { } else {
// No account, do popup login // No account, do popup login
console.log("No account found, doing popup login");
const response = await instance.loginPopup({ const response = await instance.loginPopup({
scopes: ['user.read'] scopes: ['user.read']
}); });
if (response.account) { if (response.account) {
console.log("Login successful, acquiring token");
const tokenResponse = await instance.acquireTokenSilent({ const tokenResponse = await instance.acquireTokenSilent({
scopes: ['user.read'], scopes: ['user.read'],
account: response.account account: response.account
}); });
msalToken = tokenResponse.accessToken; msalToken = tokenResponse.accessToken;
console.log("Token acquisition successful");
} else { } else {
throw new Error('Failed to get account after login'); throw new Error('Failed to get account after login');
} }
} }
console.log("MSAL token acquired, exchanging with backend");
// Exchange MSAL token for backend token // Exchange MSAL token for backend token
const response = await api.post('/api/msft/token', null, { const response = await api.post('/api/msft/token', null, {
headers: { headers: {
@ -70,6 +80,8 @@ export function useMsalAuth(): UseMsalAuthReturn {
} }
}); });
console.log("Backend token exchange successful", response.data);
// Store the backend token // Store the backend token
if (response.data.accessToken) { if (response.data.accessToken) {
localStorage.setItem('auth_data', JSON.stringify(response.data)); localStorage.setItem('auth_data', JSON.stringify(response.data));
@ -80,10 +92,13 @@ export function useMsalAuth(): UseMsalAuthReturn {
let errorMessage = 'MSAL Login fehlgeschlagen'; let errorMessage = 'MSAL Login fehlgeschlagen';
if (error.response) { if (error.response) {
console.error("Backend response error:", error.response.status, error.response.data);
errorMessage = error.response.data?.detail || error.response.data?.message || errorMessage; errorMessage = error.response.data?.detail || error.response.data?.message || errorMessage;
} else if (error.request) { } else if (error.request) {
console.error("No response received:", error.request);
errorMessage = 'Keine Antwort vom Server erhalten'; errorMessage = 'Keine Antwort vom Server erhalten';
} else { } else {
console.error("Error during MSAL auth:", error.message);
errorMessage = error.message || errorMessage; errorMessage = error.message || errorMessage;
} }

View file

@ -20,17 +20,24 @@ function Login() {
// Get the page the user was trying to visit // Get the page the user was trying to visit
const from = location.state?.from?.pathname || "/"; const from = location.state?.from?.pathname || "/";
// Debug information about accounts
useEffect(() => { useEffect(() => {
if (accounts.length > 0 && inProgress === "none") { if (accounts.length > 0) {
handleMsalLogin(); console.log("MSAL accounts found:", accounts.map(acc => ({
username: acc.username,
name: acc.name,
idTokenClaims: acc.idTokenClaims
})));
} else { } else {
console.log("User not logged in or auth in progress:", inProgress); console.log("No MSAL accounts found");
} }
}, [accounts, inProgress]); }, [accounts]);
const handleMsalLogin = async () => { const handleMsalLogin = async () => {
try { try {
await loginWithMsal(); console.log("Attempting MSAL login...");
const response = await loginWithMsal();
console.log("MSAL login successful:", response);
navigate(from, { replace: true }); navigate(from, { replace: true });
} catch (error) { } catch (error) {
console.error("MSAL login failed:", error); console.error("MSAL login failed:", error);
@ -87,7 +94,7 @@ function Login() {
<button <button
className={`${styles.button} ${styles.microsoftButton}`} className={`${styles.button} ${styles.microsoftButton}`}
onClick={() => instance.loginPopup(loginRequest)} onClick={handleMsalLogin}
disabled={isMsalLoading || inProgress !== "none"} disabled={isMsalLoading || inProgress !== "none"}
> >
{isMsalLoading ? "Signing in..." : "Sign in with Microsoft"} {isMsalLoading ? "Signing in..." : "Sign in with Microsoft"}