簡體   English   中英

Blazor WASM - 盡管 User.Identity.IsAuthenticated 返回 true,但得到“授權失敗”

[英]Blazor WASM - getting "Authorization failed" although User.Identity.IsAuthenticated returns true

我有一個實現AuthenticationStateProvider的帳戶服務。 在構造函數中,我通過查看訪問令牌的本地存儲來初始化當前用戶的 state。 如果我找到一個有效的初始 state 將被登錄,用戶將能夠使用該應用程序。 否則AuthorizeRouteView會將用戶重定向到登錄頁面:

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    @if (context.User.Identity?.IsAuthenticated != true)
                    {
                        <RedirectToLogin />
                    }
                    else
                    {
                        <Forbidden />
                    }
                </NotAuthorized>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <PageTitle>Not found</PageTitle>
            <LayoutView Layout="@typeof(MainLayout)">
                <p role="alert">Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

登錄頁面注入了一個實現AuthenticationStateProviderAccountService 登錄頁面還訂閱AuthenticationStateChanged事件以將用戶重定向到主頁。 成功登錄后,應用程序的 state 將被更新,並且將調用重定向回調:

protected override async Task OnInitializedAsync()
{
    // ...

    AccountService.AuthenticationStateChanged += Redirect;
}

async void Redirect(Task<AuthenticationState> authTask)
{
    var state = await authTask;
    if (state.User.Identity?.IsAuthenticated == true)
    {
        Console.WriteLine("Going in...");
        Navigation.NavigateTo("/");
    }
}

在控制台中,我看到“Going in...”消息,但出現以下錯誤:

授權失敗。 未滿足這些要求:
DenyAnonymousAuthorizationRequirement:需要經過身份驗證的用戶。

控制台日志

現在奇怪的是,當我刷新瀏覽器時,我已經登錄了。我不知道這是一個錯誤還是我遺漏了什么。 登錄后,我使用 NotifyAuthenticationStateChanged 更新NotifyAuthenticationStateChanged

void UpdateState(ClaimsPrincipal user)
{
    // For debugging
    Console.WriteLine("Updating state: ");
    foreach (var c in user.Claims)
    {
        Console.WriteLine("  " + c.Type + ": " + c.Value);
    }
    var authState = Task.FromResult(new AuthenticationState(user));
    NotifyAuthenticationStateChanged(authState);
}

我的 DI:

builder.Services.AddSingleton<AccountService>();
builder.Services.AddSingleton<AuthenticationStateProvider, AccountService>();

我也從這個答案中嘗試NotifyAuthenticationStateChanged(GetAuthenticationStateAsync())但它沒有用。

這解決了問題(來自這個答案):

NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());

builder.Services.AddScoped<AccountService>();
builder.Services.AddScoped<AuthenticationStateProvider>(provider => provider.GetRequiredService<AccountService>());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM