From 972feb2d8c6d1dc8051ec74da81dd986f002ccb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Zieli=C5=84ski?= Date: Fri, 12 Dec 2025 07:51:25 +0100 Subject: [PATCH] unauthirozed login fix :) --- .../Handlers/UnauthorizedResponseHandler.cs | 43 +++++++++++++++---- 1 file changed, 35 insertions(+), 8 deletions(-) diff --git a/DiunaBI.UI.Shared/Handlers/UnauthorizedResponseHandler.cs b/DiunaBI.UI.Shared/Handlers/UnauthorizedResponseHandler.cs index 563586d..892168a 100644 --- a/DiunaBI.UI.Shared/Handlers/UnauthorizedResponseHandler.cs +++ b/DiunaBI.UI.Shared/Handlers/UnauthorizedResponseHandler.cs @@ -24,16 +24,43 @@ public class UnauthorizedResponseHandler : DelegatingHandler { Console.WriteLine("⚠️ 401 Unauthorized response detected - clearing credentials and redirecting to login"); - // Create a scope to get scoped services - using var scope = _serviceProvider.CreateScope(); - var authService = scope.ServiceProvider.GetRequiredService(); - var navigationManager = scope.ServiceProvider.GetRequiredService(); + try + { + // Create a scope to get scoped services + using var scope = _serviceProvider.CreateScope(); + var authService = scope.ServiceProvider.GetRequiredService(); + var navigationManager = scope.ServiceProvider.GetRequiredService(); - // Clear authentication - await authService.ClearAuthenticationAsync(); + // Clear authentication + await authService.ClearAuthenticationAsync(); - // Navigate to login page with session expired message - navigationManager.NavigateTo("/login?sessionExpired=true", forceLoad: true); + // Navigate to login page with session expired message + navigationManager.NavigateTo("/login?sessionExpired=true", forceLoad: true); + } + catch (InvalidOperationException ex) + { + // NavigationManager may not be initialized in all contexts (e.g., during initial load) + // Log the error and allow the 401 response to propagate to the caller + Console.WriteLine($"⚠️ Cannot navigate to login - NavigationManager not initialized: {ex.Message}"); + Console.WriteLine("⚠️ 401 response will be handled by the calling component"); + + // Still try to clear authentication if we can get the AuthService + try + { + using var scope = _serviceProvider.CreateScope(); + var authService = scope.ServiceProvider.GetRequiredService(); + await authService.ClearAuthenticationAsync(); + } + catch (Exception clearEx) + { + Console.WriteLine($"⚠️ Could not clear authentication: {clearEx.Message}"); + } + } + catch (Exception ex) + { + // Log any other unexpected errors + Console.WriteLine($"❌ Error handling 401 response: {ex.Message}"); + } } return response;