为 .NET Core 3.1 Web 应用实施 Windows 身份验证

Implement Windows Authentication for .NET Core 3.1 Web App

我使用 .NET Core 3.1 创建了一个内部 Razor Pages Web 应用程序。我只想向属于 Active Directory 组的用户授予访问权限。我不希望他们不得不经历创建更多 username/passwords 的麻烦。但是我一直无法让它工作。

我按照 the Microsoft Documentation 创建了一个入门应用程序并添加了一个 web.config 文件,如文档中所述。当我从 Visual Studio 2019 年启动时,浏览器显示

  1. 我怎样才能让它工作?
  2. 如何设置只允许特定组中的用户访问?我现在不关心角色。我想允许完全访问,但将不在该组中的任何人拒之门外。谢谢。

我想通了。我让我的 IT 部门为应用程序的用户添加了一个特殊组并搜索该组。

    public bool IsInGroup(string groupName)
    {
        var groups = new List<string>();
        
        var wi = (WindowsIdentity)User.Identity;
        if (wi.Groups != null)
            foreach (var group in wi.Groups)
            {
                try
                {
                    groups.Add(group.Translate(typeof(NTAccount)).ToString());
                }
                catch (Exception ex)
                {
                    logger.LogInformation($"User = {User.Identity.Name}; Error = {ex.Message}");
                    throw;
                }
            }
        return groups.Contains(groupName);
    }