【问题标题】:windows credential validation [duplicate]Windows凭据验证[重复]
【发布时间】:2014-01-08 02:23:15
【问题描述】:

我需要一些 C# 代码来验证 Windows 凭据,该帐户可能是本地帐户或域帐户。

请提供一些关于如何做到这一点的想法。

【问题讨论】:

标签: c# credentials


【解决方案1】:

取决于您使用的 .NET 版本。如果您使用的是包含 System.DirectoryServices.AccountManagement 的 .NET 版本,您可以执行以下操作:

 bool valid = false;

 using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
 {
     valid = context.ValidateCredentials(username, password);
 }

将本地计算机的 ContextType.Domain 更改为 ContextType.Machine。您还可以尝试通过查询 Active Directory 或尝试使用类似的方式强制登录到本地系统来模拟用户。不过,我会推荐上述方法。

public bool IsAuthenticated(string server, string username, string password)
{
    bool authenticated = false;

    try
    {
        DirectoryEntry entry = new DirectoryEntry(server, username, password);
        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]
    }

    return authenticated;
}

【讨论】:

  • 如果我没有 Active Directory 怎么办?
猜你喜欢
  • 2010-12-08
  • 2018-03-25
  • 1970-01-01
  • 2010-10-03
  • 2016-11-10
  • 2016-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多