1

In my Blazor WebAseembly application there are a few HTTP interceptors (delegating handlers). The UnAuthorized interceptor checks the HTTP status code and if it's 401, the rest of the pipeline do not matter, and user needs to be redirected to the login page.

enter image description here

How can I achieve this in Blazor? Currently I get exception in other interceptors or the HTTP client, because they all execute. But I need to break the circuit somehow.

Parsa99
  • 307
  • 1
  • 13

1 Answers1

0

I used an http client interceptor in my app as follows:

First I installed "Toolbelt.Blazor.HttpClientInterceptor" nuget.

Then I created a new HttpInterceptorService.cs class:

// HttpInterceptorService.cs
public class HttpInterceptorService
{
    private readonly HttpClientInterceptor _interceptor;
    private readonly NavigationManager _navManager;
    public HttpInterceptorService(HttpClientInterceptor interceptor, NavigationManager navManager)
    {
        _interceptor = interceptor;
        _navManager = navManager;
    }
    public void RegisterEvent() => _interceptor.AfterSend += InterceptResponse;
    privatevoid InterceptResponse(object sender, HttpClientInterceptorEventArgs e)
    {
        string message = string.Empty;
        if (!e.Response.IsSuccessStatusCode)
        {
            var statusCode = e.Response.StatusCode;
            switch (statusCode)
            {
                case HttpStatusCode.NotFound:
                    _navManager.NavigateTo("/404");
                    message = "The requested resorce was not found.";
                    break;
                case HttpStatusCode.Unauthorized:
                    _navManager.NavigateTo("/unauthorized");
                    message = "User is not authorized";
                    break;
                default:
                    _navManager.NavigateTo("/500");
                    message = "Something went wrong, please contact Administrator";
                    break;
            }
            throw new HttpResponseException(message);
        }
    }
    public void DisposeEvent() => _interceptor.AfterSend -= InterceptResponse;
}

When I want to use it in a razor page, I do as following:

@* SomePage.razor *@
@inject HttpInterceptorService Interceptor
@implements IDisposable
...

@code {
    protected override void OnInitialized()
    {
        Interceptor.RegisterEvent();
    }
    
    public void Dispose()
    {
        Interceptor.DisposeEvent();
    }
}

When the user is not authorized on that page, it will automatically navigate to the specified location.

You can add more routes not only for authorization, simply customize the switch case in the HttpInterceptorService.cs

Ibrahim Timimi
  • 2,656
  • 5
  • 19
  • 31