Windows 身份验证失败,显示“401 未授权”

Windows authentication fail with "401 Unauthorized"

我有一个 MVC 客户端访问受 IDS4 保护的 Web API。它们都 运行 在我的本地计算机上并由 IIS 托管。使用本地身份进行身份验证时,该应用程序运行良好。但是当我尝试使用 Windows 身份验证时,我不断从开发工具中收到“401 Unauthorized”错误,并且登录框不断返回到浏览器。

这是 Windows 身份验证 IIS 设置

和启用的提供商

这几乎就像是用户名或密码错误,但这几乎是不可能的,因为那是我一直用来登录系统的域用户名和密码。此外,根据我的阅读,Windows 身份验证应该是“自动”的,这意味着我将在没有登录框的情况下静默进行身份验证。

更新

我启用了 IIS 请求跟踪,这是来自日志的结果:

正如您从跟踪日志项 #29 中看到的那样,身份验证(使用我输入的用户 ID,“DOM\Jack.Backer”)是成功的。然而,之后一些授权项目(#48)失败了。这是失败项目的详细信息:

有趣的是,ErrorCode 表示操作(无论是什么)已成功完成,但我仍然收到 HttpStatus=401 和 HttpReason=Unauthorized 的警告。显然,这就是我的 Windows 身份验证失败的原因。但是这个授权是关于什么的,我该如何解决它?

以防万一有人感兴趣 - 我终于弄明白了。这是因为我在 2020 年底从 IndentityServer4 的快速入门站点下载的代码没有 Windows 身份验证所需的一些重要部分。这是我必须添加到 ExternalController class

的 Challenge 函数中的内容

这是 ProcessWindowsLoginAsync 函数

private async Task<IActionResult> ProcessWindowsLoginAsync(string returnUrl)
{
    var result = await HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName);
    if (result?.Principal is WindowsPrincipal wp)
    {
        var props = new AuthenticationProperties()
        {
            RedirectUri = Url.Action(nameof(Callback)),
            Items =
            {
                { "returnUrl", returnUrl },
                { "scheme", AccountOptions.WindowsAuthenticationSchemeName },
            }
        };

        var id = new ClaimsIdentity(AccountOptions.WindowsAuthenticationSchemeName);
        id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.Identity.Name));
        id.AddClaim(new Claim(JwtClaimTypes.Name, wp.Identity.Name));

        if (AccountOptions.IncludeWindowsGroups)
        {
            var wi = wp.Identity as WindowsIdentity;
            var groups = wi.Groups.Translate(typeof(NTAccount));
            var roles = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Value));
            id.AddClaims(roles);
        }

        await HttpContext.SignInAsync(IdentityConstants.ExternalScheme, new ClaimsPrincipal(id), props);

        return Redirect(props.RedirectUri);
    }
    else
    {
        return Challenge(AccountOptions.WindowsAuthenticationSchemeName);
    }
}

现在我的 windows 身份验证没有问题。