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_TENANT_ID="6a51aaeb-2467-4186-9504-2a05aedc591f"
VITE_ENTRA_CLIENT_SECRET="2iw8Q~jwqG1iacxHopBt5pstu6R45UC1gIQabcbD"

View file

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

View file

@ -65,39 +65,6 @@ import {
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) {
return <div>Loading authentication...</div>;
}

View file

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

View file

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