'Blazor Authentication Fails when using OnInitializedAsync

I have the following razor component

page "/test"
@using Microsoft.AspNetCore.Components.Authorization
@inject HttpClient Http

<h3>TestAuthPage</h3>

<AuthorizeView Roles="admin">
    <Authorized>
        Hello
    </Authorized>
    <NotAuthorized>
        Not Auth
    </NotAuthorized>
</AuthorizeView>

@code {

    protected override async Task OnInitializedAsync()
    {
        var f = await Http.GetFromJsonAsync<List<string>>("api/test");
    }
}

This throws an error in the browser as it gives a 401 when calling the api

However if I do this

@page "/test"
@using Microsoft.AspNetCore.Components.Authorization
@inject HttpClient Http

<h3>TestAuthPage</h3>

<AuthorizeView Roles="admin">
    <Authorized>
        Hello
        @if(sss().Result)
        {}
    </Authorized>
    <NotAuthorized>
        Not Auth
    </NotAuthorized>
</AuthorizeView>

@code {
    public async Task<bool> sss()
    {
        var f = await Http.GetFromJsonAsync<List<string>>("api/test");
        return true;
    } 
}

The api controller is called correctly.

What on earth is going on? Surely OnInitializedAsync() is a standard way to initialise the page?



Solution 1:[1]

Okay, I seem to have solved the issue. If I add an AuthenticationState parameter and then await it in the method then the Controller is called fine and I am authenticated on the controller side. I have no idea why this works but I assume it must be a timing thing? If anyone knows why this works then please let me know...

@page "/test"
@using Microsoft.AspNetCore.Components.Authorization
@inject HttpClient Http

<h3>TestAuthPage</h3>

<AuthorizeView Roles="admin">
    <Authorized>
        Hello
        @if(sss().Result)
        {}
    </Authorized>
    <NotAuthorized>
        Not Auth
    </NotAuthorized>
</AuthorizeView>

@code {
    [CascadingParameter]
    public Task<AuthenticationState> AuthState{ get; set; }

    protected override async Task OnInitializedAsync()
    {
        var t = await AuthState;
        var f = await Http.GetFromJsonAsync<List<string>>("api/test");
    }

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 coolblue2000