[英]Trying to connect using PrincipalContext on Workgroup Server returns Invalid User.
我想創建一個應用程序來編輯服務器上的用戶帳戶。
服務器不使用僅 AD 本地帳戶。
我使用以下代碼連接遠程服務器:
try
{
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine, "192.168.123.110", null, ContextOptions.Negotiate, "Administrator", "password");
try
{
MessageBox.Show(oPrincipalContext.ConnectedServer);
GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, "Goetter");
try
{
// perform operations here
}
finally
{
oGroupPrincipal.Dispose();
}
}
finally
{
oPrincipalContext.Dispose();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
每當我嘗試這個時,我都會得到一個異常,即用戶和/或密碼未經授權,與我使用的用戶無關。 Administrator 是內置的 Admin 用戶帳戶。
PrincipalContext
是否僅適用於 AD 或也適用於本地帳戶? 我的代碼有什么問題嗎?
using(PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine, computer.Name, null, ContextOptions.Negotiate, Settings.UserName, Settings.UserPassword))
using(GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, Settings.AdministratorsGroup))
{
// perform operations here
}
更改代碼並將其包裝在using語句周圍,否則在嘗試調用 Dispose() 方法時可能會出現一些錯誤,原因是當您嘗試處理連接時可能已經關閉。
如果您使用 ActiveDirectory,您可以在此處使用此代碼並嘗試任一示例
示例 1
如果您使用 .NET 3.5,則可以使用 System.DirectoryServices.AccountManagement 命名空間並輕松驗證您的憑據:
// create a "principal context" - e.g. your domain (could be machine, too)
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
{
// validate the credentials
bool isValid = pc.ValidateCredentials("myuser", "mypassword");
}
示例 2
using System.Security;
using System.DirectoryServices.AccountManagement;
public struct Credentials
{
public string Username;
public string Password;
}
public class Domain_Authentication
{
public Credentials Credentials;
public string Domain;
public Domain_Authentication(string Username, string Password, string SDomain)
{
Credentials.Username = Username;
Credentials.Password = Password;
Domain = SDomain;
}
public bool IsValid()
{
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain))
{
// validate the credentials
return pc.ValidateCredentials(Credentials.Username, Credentials.Password);
}
}
}
上面的公共 bool IsValid() 方法應該適用於您要查找的內容。
看看 PrincipalContext.ValidateCredentials
對於您的 FindByIdentity 部分,您可以嘗試以下替換代碼
string strName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
// This is here because of a .Net error that gets 0x80005000 on "isUser = user.IsMemberOf(groupU);"
string domainName = strName.Split('\\')[0];
var pc = new PrincipalContext(ContextType.Domain, domainName);
附加參考鏈接 StackOverFlow Post ContextType.Machine
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.