1

我正在使用 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.
        }

网页配置

<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> 
4

1 回答 1

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))
    {

    } 
于 2012-08-02T00:12:34.853 回答