我在MVC中使用LDAP进行用户身份验证。我的代码如下所示:
public ActionResult Login(LoginViewModel model, string returnUrl)
{
bool validation;
try
{
LdapConnection ldc = new LdapConnection(new LdapDirectoryIdentifier((string)null, false, false));
NetworkCredential nc = new NetworkCredential(model.UserName, model.Password, "XXXXXXX");
ldc.Credential = nc;
ldc.AuthType = AuthType.Negotiate;
ldc.Bind(nc); // user has authenticated at this point, as the credentials were used to login to the dc.
validation = true;
return RedirectToAction("Index", "Home");
//validation = true;
}
catch (LdapException)
{
validation = false;
}
return View(model);
}
但我收到的错误是“LDAP服务器不可用”
Web.Config中:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="10"/>
</authentication>
<membership defaultProvider="AspNetActiveDirectoryMembershipProvider">
<providers>
<clear />
<add name="AspNetActiveDirectoryMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider,System.Web, Version=2.0.0.0,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ADConnectionString"
attributeMapUsername="sAMAccountName" />
</providers>
</membership>
<add name="ADConnectionString" connectionString="LDAP://XXXXXXX:389/DC=XXXX,DC=XXXX" />
答案 0 :(得分:0)
您没有设置LDAP服务器的路径(当前为空)
LdapConnection ldc = new LdapConnection(
new LdapDirectoryIdentifier((string)null, false, false)
);
要进行调试,请删除try..catch并查看错误的确切位置。您可能需要与网络管理员验证路径,或使用LDAP Browser之类的任何工具,您可以在其中查看路径和凭据是否有效。
此外,请确保您要进行身份验证的方式是正确的。如果这是一个Intranet应用程序,那么可能是您可以设置集成Windows身份验证,这不需要任何自定义登录过程,并且可以在IIS上进行配置。