我正在使用AD成员资格提供程序来验证用户名,并且在使用user@upnDomain.com以外的任何其他工作时遇到问题。
是否可以使用其他用户名格式?
代码
MembershipProvider domainProvider;
domainProvider = Membership.Providers["MyADMembershipProvider"];
if (domainProvider.ValidateUser("zzTest123", "pass"))
{
}
if (domainProvider.ValidateUser(@"PARTNERSGROUP\zzTest123", "pass"))
{
}
if (domainProvider.ValidateUser("zzTest123@company.com", "pass"))
{
}
if (domainProvider.ValidateUser("zzTest123@testfirm.com", "pass"))
{
// this is the UPN and the only one that works.
}
的Web.config
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" name=".ADAuthCookie" timeout="10" />
</authentication>
<membership>
<providers>
<add name="MyADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="TestDomain1ConnectionString" />
</providers>
</membership>
答案 0 :(得分:0)
根据我的测试,会员提供商仅适用于UPN。要实现对其他类型的支持,请覆盖ActiveDirectoryMembershipProvider的ValidateUser函数并添加以下内容的一些变体:
//
// Will validate UPN, shortname only, or domain prefixed (domain\user)
public bool IsAuthenticated( string usr, string pwd)
{
bool authenticated = false;
DirectorySearcher dseSearcher=null;
DirectoryEntry entry = null;
try
{
dseSearcher = new DirectorySearcher();
string rootDSE = dseSearcher.SearchRoot.Path;
entry = new DirectoryEntry(rootDSE, usr, pwd);
object nativeObject = entry.NativeObject;
authenticated = true;
}
catch (DirectoryServicesCOMException cex)
{
//not authenticated; reason why is in cex
}
catch (Exception ex)
{
//not authenticated due to some other exception [this is optional]
}
finally
{
dseSearcher.Dispose();
entry.Dispose();
}
return authenticated;
}
请注意,System.DirectoryServices.AccountManagement命名空间仅验证短名称UPN,但似乎不验证DOMAIN \ Username帐户。
如果以DOMAIN \ Username格式
传递用户名,则以下代码将引发异常“LdapException:发生了本地错误。”
var ctx = new PrincipalContext(ContextType.Domain);
if (ctx.ValidateCredentials(username,password , ContextOptions.Negotiate))
{
}