Translate Blazor AuthorizeView into code behind

Viewed 29

I'm using the AutorizeView based on Roles in a blazor page to show/hide some features. But I need to do the same thing in the code behind. I don't know how to do it. In my particular case, If the logged user were admin it will see a complete list of Patients and, if it's not, it will see only the patients assigned to him.

<AuthorizeView Roles="Administrator" Context="search">
   <Authorized>
        random text
   </Authorized>
</AuthorizeView>

I found this solution, but I don't use Policies. I'm just using Roles="Administrator".

1 Answers

You can use the cascading authentication state to get the current user's claims principal.

@code {
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    protected override async Task OnInitializedAsync()
    {
        var authState = await authenticationStateTask;
        var user = authState.User;

        if (user.IsInRole("Administrator"))
        {
            // load all patients
        }
        else
        {
            // load specific patients
        }
    }
}

You have to add CascadingAuthenticationState and AuthorizeRouteView components inside App.razor:

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" 
                DefaultLayout="@typeof(MainLayout)" />
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

https://docs.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-6.0#expose-the-authentication-state-as-a-cascading-parameter

Related