c# - 在服务器上运行时获取 AD 组列表失败
问题描述
我在 IIS 上的同一台服务器上托管了一个网站和 API。在 API (.NET) 中,我需要获取正在使用该网站的用户所属的 AD 组列表。它在本地工作(邮递员调用 IIS Express 上的 API),但在我们的服务器上运行时却不能。获取 AD 组的代码是这样的:
string[] output = null;
string username = GetUserName();
using (var ctx = new PrincipalContext(ContextType.Domain))
using (var user = UserPrincipal.FindByIdentity(ctx, username))
{
if (user != null)
{
output = user.GetGroups() //this returns a collection of principal objects
.Select(x => x.SamAccountName) // select the name. you may change this to choose the display name or whatever you want
.ToArray(); // convert to string array
}
}
用户名被正确识别,并且在 localhost 和服务器上传递了相同的值,所以这不是问题。线:
using (var user = UserPrincipal.FindByIdentity(ctx, username))
返回异常:
System.DirectoryServices.AccountManagement.dll 中出现“System.DirectoryServices.DirectoryServicesCOMException”类型的异常,但未在用户代码中处理
这可能是 IIS 设置中的问题,但我不知道是什么。我尝试将 DefaultAppPool 的标识(Web 和 API 分配到的应用程序池)设置为 NetworkService,但它没有帮助。
解决方案
如果您还没有启用 Windows 身份验证,则需要启用。说明在这里: https: //support.microsoft.com/en-in/help/323176/how-to-implement-windows-authentication-and-authorization-in-asp-net
但基本的想法是你在你的 web.config 中使用它:
<system.webServer>
<security>
<authentication>
<windowsAuthentication enabled="true" />
<anonymousAuthentication enabled="false" />
</authentication>
</security>
</system.webServer>
然后您可以使用它来获取UserPrincipal
当前用户的对象:
UserPrincipal.FindByIdentity(domain, User.Identity.Name)
但是您可能仍然会遇到正在使用的帐户的问题,因为您的网站还需要使用域凭据向 AD 进行身份验证。
DefaultAppPool 使用服务器本地的帐户,AD 无法识别。您可以在构造函数中传递 AD 凭据PrincipalContext
,如下所示:
using (var ctx = new PrincipalContext(ContextType.Domain, null, "username", "password"))
我以为 NetworkService 使用 AD 计算机帐户进行身份验证,但也许您的服务器没有加入域?如果不是,那么您还需要在以下位置指定域名PrincipalContext
:
using (var ctx = new PrincipalContext(ContextType.Domain, "domain.com", "username", "password"))
当您在 IIS Express 中本地运行它时,它会起作用,因为 IIS Express 在您的凭据下运行并使用您的凭据向 AD 进行身份验证。
推荐阅读
- javascript - 剥离某些 html 标签并返回字符串的其余部分和所有其他标签
- javascript - 我如何将密钥添加到对象本身?
- python - 如何将具有非法名称的关键字参数传递给接受 **kwargs 的函数
- bash - 在 bash 字符串变量中展开花括号和通配符(没有 eval)
- mongodb - MongoDB查找匹配坐标比较的文档
- python - 如何将三个列表转换为一个字典?
- c# - C# GraphX 在点击时高亮显示顶点
- flutter - NoSuchMethodError:在 null 上调用了“评级”
- pre-commit.com - pre-commit-config.yaml 中的 args 是否会覆盖 pre-commit-hooks.yaml 中的 args?
- spring-boot - Swagger-codegen:可以保留生成模型中的手动更改吗?