Skip to content

[Blazor Wasm Auth] Single httpclient for both authenticated and non authenticated users #28951

@andersson09

Description

@andersson09

Is your feature request related to a problem? Please describe.

I do not think it is necessary to have separate http clients for authenticated and non authenticated users (see https://docs.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/additional-scenarios?view=aspnetcore-5.0). The developer has to create a lot of additional code, especially for typed clients.

Describe the solution you'd like

Before sending the request can we check to see if the user is authenticated or not and determine whether to apply the handler logic.

`
Here is a hack to get this working with the current AuthorizationMessageHandler

public class ApiAuthorizationHandler : AuthorizationMessageHandler
{
    private readonly NavigationManager navigation;
    private readonly IConfiguration config;
    private readonly AuthenticationStateProvider authStateProvider;

    //https://github.com/dotnet/aspnetcore/blob/master/src/Components/WebAssembly/WebAssembly.Authentication/src/Services/AuthorizationMessageHandler.cs
    public ApiAuthorizationHandler(IAccessTokenProvider provider, 
        NavigationManager navigation, 
        IConfiguration config,
        AuthenticationStateProvider authStateProvider) : base(provider, navigation)
    {
        this.navigation = navigation;
        this.config = config;
        this.authStateProvider = authStateProvider;
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        //Hack to bypass handler already configured exception
        var field = this.GetType().BaseType.GetField("_authorizedUris", BindingFlags.Instance | BindingFlags.NonPublic);
        field.SetValue(this, null);

        var authState = await authStateProvider.GetAuthenticationStateAsync();

        if (authState.User.Identity.IsAuthenticated)
        {
            ConfigureHandler(new[]{config.GetValue<string>("ServerUri")});
        }
        else
        {
            //Satisfy validation so that we can call api without needing to be logged in
            ConfigureHandler(new[]{navigation.BaseUri});
        }

        return await base.SendAsync(request, cancellationToken);    
    }
}`

Metadata

Metadata

Assignees

No one assigned

    Labels

    affected-mediumThis issue impacts approximately half of our customersarea-blazorIncludes: Blazor, Razor ComponentsenhancementThis issue represents an ask for new feature or an enhancement to an existing onefeature-blazor-wasmThis issue is related to and / or impacts Blazor WebAssemblyfeature-blazor-wasm-authseverity-minorThis label is used by an internal tool

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions