首页 > 解决方案 > 如何在 Blazor 服务器端应用程序中启用/修复 Windows 身份验证?

问题描述

当我们最初创建服务器端 Blazor 应用程序(ASP.NET Core Web 应用程序)时,我们没有启用身份验证。我们现在想启用 Windows 身份验证。

我创建了一个带有 Windows 身份验证的测试 Web 应用程序,并尝试将缺失的位添加到我们现有的 Web 应用程序中。以下是我所做的更改:

  1. 修改 app.razor 以包含 cascadingauthenticationstate
<Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        </Found>
        <NotFound>
            <CascadingAuthenticationState>
                <LayoutView Layout="@typeof(MainLayout)">
                    <p>Sorry, there's nothing at this address.</p>
                </LayoutView>
            </CascadingAuthenticationState>
        </NotFound>
    </Router>
  1. 在 _imports.razor 中添加了缺失的导入
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
  1. 尝试使用剃须刀组件中的以下代码块获取当前 Windows 身份:
@code {
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    private async Task LogUsername()
    {
        var authState = await authenticationStateTask;
        var user = authState.User;

        if (user.Identity.IsAuthenticated)
        {
            Console.WriteLine($"{user.Identity.Name} is authenticated.");
        }
        else
        {
            Console.WriteLine("The user is NOT authenticated.");
        }
    }
}

当我在 Visual Studio 2019 预览版中本地运行 Web 应用程序时,我总是以一个空的身份名称结束。而且,IsAuthenticated 总是错误的。但是,如果我在本地运行测试 Web 应用程序,它会获得正确的身份名称。

有谁知道我在现有的网络应用程序中缺少什么?

谢谢!

标签: blazor-server-side

解决方案


显然,我错过了在“项目属性”>“调试”选项卡下选中 Windows 身份验证框。


推荐阅读