dotnet / dotnet/aspnetcore

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

Open
#28,951 3 comments 0 reactions 0 assignees View on GitHub
affected-medium area-blazor enhancement feature-blazor-wasm feature-blazor-wasm-auth severity-minor
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### 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 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("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);
}
}`

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.