Files
DiunaBI/DiunaBI.UI.Shared/Handlers/UnauthorizedResponseHandler.cs

69 lines
2.7 KiB
C#
Raw Normal View History

2025-12-05 20:34:18 +01:00
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.DependencyInjection;
using DiunaBI.UI.Shared.Services;
namespace DiunaBI.UI.Shared.Handlers;
public class UnauthorizedResponseHandler : DelegatingHandler
{
private readonly IServiceProvider _serviceProvider;
public UnauthorizedResponseHandler(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
// Check if response is 401 Unauthorized
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
Console.WriteLine("⚠️ 401 Unauthorized response detected - clearing credentials and redirecting to login");
2025-12-12 07:51:25 +01:00
try
{
// Create a scope to get scoped services
using var scope = _serviceProvider.CreateScope();
var authService = scope.ServiceProvider.GetRequiredService<AuthService>();
var navigationManager = scope.ServiceProvider.GetRequiredService<NavigationManager>();
2025-12-05 20:34:18 +01:00
2025-12-12 07:51:25 +01:00
// Clear authentication
await authService.ClearAuthenticationAsync();
2025-12-05 20:34:18 +01:00
2025-12-12 07:51:25 +01:00
// 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<AuthService>();
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}");
}
2025-12-05 20:34:18 +01:00
}
return response;
}
}