C# 从 Active Directory, IIS 中的登录用户获取登录用户电子邮件地址



我正在开发一个MVC应用程序,我想通过从Active Directory检索用户的电子邮件地址来自动登录系统,使用该电子邮件地址在我的数据库中查找用户,如果找到,请登录系统。这个想法是让系统在已经登录到在工作域/Active Directory上设置的工作站后不强制用户输入登录详细信息。

请帮助我提供这方面的指示,因为我已经尝试了许多线程中描述的大多数方法。

  • 我已将 IIS 应用池设置为"网络服务">
  • ASP.NET 模拟已禁用。
  • 我已在应用程序池中启用加载用户配置文件 ->高级设置

当我使用以下代码时,搜索失败:

using ( System.Web.Hosting.HostingEnvironment.Impersonate() )
{
PrincipalContext ctx = new PrincipalContext( ContextType.Domain );
UserPrincipal user = UserPrincipal.FindByIdentity( ctx, User.Identity.Name );
Response.Write( "User: " + User.Identity.Name );
Response.Write( user.EmailAddress );
Response.Flush();
Response.End();
}

错误:The (&(objectCategory=user)(objectClass=user)(|(userPrincipalName=)(distinguishedName=)(name=))) search filter is invalid.

有人可以指出我想要实现的正确方向吗?我是否错误地接近了我的要求?

提前谢谢。

要使用户自动登录,您需要使用 Windows 身份验证。要使其正常工作,有几个先决条件:

  1. 用户必须使用他们将用于对您的网站进行身份验证的帐户登录到 Windows。
  2. 您的网站必须添加到 Windows 的"Internet 选项"中的"受信任的站点"(或被视为"Intranet 站点"(,以便 IE 和 Chrome 自动发送凭据。火狐有自己的设置,称为network.negotiate-auth.trusted-uris.
  3. 您的服务器必须加入到信任用户域的域(通常是同一域(的域。

如果所有这些情况都属实,则可以按照此处的说明在IIS中安装Windows身份验证功能(取决于您的版本(。如果使用 IIS Express 在本地运行它,则可以在开发计算机上跳过此步骤。

然后,通过修改 web.config 文件在您的网站中启用 Windows 身份验证。在<system.web>标记下添加以下内容:

<authentication mode="Windows" />

并在<system.webServer>下添加以下内容:

<security>
<authentication>
<windowsAuthentication enabled="true" />
<anonymousAuthentication enabled="false" />
</authentication>
</security>

然后,只要您的网站受到浏览器的信任(上面的步骤2(,您就会自动登录。登录用户的用户名将为User.Identity.Name。您显示的所有代码都可以工作,但是您无需调用System.Web.Hosting.HostingEnvironment.Impersonate()

public bool CheckUserInGroup(string group)
{
string serverName = ConfigurationManager.AppSettings["ADServer"];
string userName = ConfigurationManager.AppSettings["ADUserName"];
string password = ConfigurationManager.AppSettings["ADPassword"];
bool result = false;
SecureString securePwd = null;
if (password != null)
{
securePwd = new SecureString();
foreach (char chr in password.ToCharArray())
{
securePwd.AppendChar(chr);
}
}
try
{  
ActiveDirectory adConnectGroup = new ActiveDirectory(serverName, userName, securePwd);
SearchResultEntry groupResult = adConnectGroup.GetEntryByCommonName(group);
Group grp = new Group(adConnectGroup, groupResult);
SecurityPrincipal userPrincipal = grp.Members.Find(sp => sp.SAMAccountName.ToLower() == User.Identity.Name.ToLower());
if (userPrincipal != null)
{
result = true;
}
}
catch
{
result = false;
}
return result;
}

我相信有很多方法可以从C# MVC中检索AD用户。 http://www.codedigest.com/posts/5/get-user-details-from-active-directory-in-aspnet-mvc 请看一下这个使用银河API(免费和开源包(的好例子。

最新更新