picolino
picolino

Reputation: 5459

Blazor navigation with authorization header and bearer token

I want to create HealthChecks portal via HealthChecksUI but with limited access with authorization.
Also I using Blazor to accomplish authorization dialog creation and receiving access token.

So I configuring HealthChecksUI:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    //...
    app.UseEndpoints(endpointsBuilder =>
    {
        //...
        endpointsBuilder.MapHealthChecksUI(setup =>
        {
            setup.UIPath = "/portal";
            setup.ApiPath = "/portal/api";
            setup.WebhookPath = "/portal/webhooks";
            setup.ResourcesPath = "/portal/resources";
        }).RequireAuthorization(); // This means access to '/portal' route will be limited by authorization.
        //...
    }
    //...
}

I using bearer token in HTTP Authorization header for authorization while performing any request.

Next let's check authorization work:
GET request from POSTMAN with valid bearer token to '/portal' route passing successfully. Also, if I change token then I recieve 401 Unauthorized error. So it's seems authorization system working correctly.

Next step will be using authorization dialog to perform token receiving and redirecting to portal page.
Code below it's just a simple authorize function using in .razor page

private async Task SubmitAsync()
{
    var (authorizationSuccessful, accessToken) = await authorizationService.AuthorizeAsync(authorizationData).ConfigureAwait(false);

    if (authorizationSuccessful)
    {
        navigationManager.NavigateTo("/portal", true);
    }
    else
    {
        throw new UnauthorizedAccessException("Incorrect login or password");
    }
}

So problem is:
When authorization passing (authorizationSuccessful is true) and navigation performing, I get to '/portal' page without any authorization data, so I get 401 Unauthorized error.

The question is:

How can I pass received bearer token (accessToken) through NavigateTo method in Authorization HTTP Header to accomplish authorized access to '/portal' page? Is it even possible?

Upvotes: 2

Views: 3254

Answers (1)

picolino
picolino

Reputation: 5459

Unfortunately, it's not possible to accomplish this task that way.

According to tries to do something like this using JS only (this and this), it can't be done with plain JS.

So we have just few options here:

Share authorization token through cookies

Cookies are browser-based shared storage, so check access token from here possible right after navigation.

Send authorization token through query

NavigateTo method can be used with query parameters like this:

navigationManager.NavigateTo($"/portal?token={accessToken}", true);

So we can check access token from query parameters directly.

Upvotes: 2

Related Questions