Skip to content

Reduce boiler plate code for getting the current user in a Blazor component #55327

@danroth27

Description

@danroth27

In a Blazor component if you want to get the current user you typically have to do something like this:

protected override async Task OnInitializedAsync()
{
    var authenticationState = await AuthenticationStateTask;
    CurrentUser = authenticationState.User;
}

[CascadingParameter]
public Task<AuthenticationState> AuthenticationStateTask { get; set; } = default!;

public ClaimsPrincipal CurrentUser { get; set; } = default!

There are several things going on here: a special cascading parameter, overriding a component lifecycle event, and async logic to get the auth state. It's quite a bit more complicated than the convenient User property we have in MVC & Razor Pages. And you need this code wherever you want access to the current user. Is there something we could do to cut down on the amount of boiler plate code to get the current user?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Pillar: Dev Experiencearea-blazorIncludes: Blazor, Razor ComponentsenhancementThis issue represents an ask for new feature or an enhancement to an existing one

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions