【问题标题】:How to enable/fix windows authentication in Blazor Server-Side App?如何在 Blazor 服务器端应用程序中启用/修复 Windows 身份验证?
【发布时间】:2022-03-18 19:41:28
【问题描述】:

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

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

  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 总是错误的。 但是,如果我在本地运行测试网络应用程序,它会获得正确的身份名称。

有人知道我在现有网络应用中缺少什么吗?

谢谢!

【问题讨论】:

    标签: blazor-server-side


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      只需启用 Windows 身份验证按钮:项目 => 属性 => 调试 => 网络服务器设置

      【讨论】:

        【解决方案3】:

        我有一个 Blazor 服务器项目,它有两个可能的调试启动配置文件

        Web 项目本身 XX.SD 在浏览器中启动,但启动配置文件没有 Windows 身份验证选项。 然而,IIS Express lauch 配置文件在“属性”页面中确实有此选项。

        【讨论】:

        • 换句话说,您的答案是“确保使用 IIS Express 启动项目,以便进行身份验证”
        • 在我的情况下是的,我想这取决于您在您的环境中拥有的配置文件
        猜你喜欢
        • 2020-04-11
        • 2020-08-20
        • 1970-01-01
        • 2021-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-27
        • 2021-04-30
        相关资源
        最近更新 更多