feat(client): add AuthRedirectHandler for global 401 redirect
Add HTTP message handler that intercepts 401 Unauthorized responses and redirects to the login page with return URL preserved.
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
using System.Net;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
|
||||
namespace JdeScoping.Client.Http;
|
||||
|
||||
/// <summary>
|
||||
/// HTTP message handler that intercepts 401 Unauthorized responses
|
||||
/// and redirects to the login page with return URL.
|
||||
/// </summary>
|
||||
public class AuthRedirectHandler : DelegatingHandler
|
||||
{
|
||||
private readonly NavigationManager _navigationManager;
|
||||
|
||||
public AuthRedirectHandler(NavigationManager navigationManager)
|
||||
{
|
||||
_navigationManager = navigationManager;
|
||||
}
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var response = await base.SendAsync(request, cancellationToken);
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
||||
{
|
||||
var returnUrl = Uri.EscapeDataString(_navigationManager.Uri);
|
||||
_navigationManager.NavigateTo($"/login?returnUrl={returnUrl}", forceLoad: true);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user