我正在尝试在Active Directory中按用户名查找用户.
这有效:
const string Domain = "SLO1.Foo.Bar.biz";
const string Username = "sanderso";
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, Domain);
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, Username);
Run Code Online (Sandbox Code Playgroud)
这不是:
const string Domain = "SLO1.Foo.Bar.biz";
const string Container = "CN=Users,DC=SLO1,DC=Foo,DC=Bar,DC=biz";
const string Username = "sanderso";
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, Domain, Container);
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, Username);
Run Code Online (Sandbox Code Playgroud)
我收到错误消息:
服务器上没有这样的对象.
这是我的ActiveDirectory设置的屏幕截图:

我也尝试使用以下Container:
const string Container = "OU=Users,DC=SLO1,DC=Foo,DC=Bar,DC=biz";
Run Code Online (Sandbox Code Playgroud)
这同样不成功.
如何在访问"用户"容器时指定我的容器?在尝试引入更复杂的需求之前,我尝试将其作为初始的简单设置.所以,我宁愿不满足于这个简单的解决方案,因为我无论如何都要对此进行故障排除,我相信.
以下代码仅适用于IIS中仅为我们网络上的本地用户启用Windows身份验证的情况.
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
UserPrincipal up = UserPrincipal.FindByIdentity(ctx, userName);
return up;
}
Run Code Online (Sandbox Code Playgroud)
否则会抛出此异常:
[ArgumentException :(&(objectCategory = user)(objectClass = user)(|(userPrincipalName =)(distinguishedName =)(name =)))搜索过滤器无效.] System.DirectoryServices.ResultsEnumerator.MoveNext()+434305 System .DirectoryServices.SearchResultCollection.get_InnerList()+282 System.DirectoryServices.SearchResultCollection.get_Count()+ 9 System.DirectoryServices.AccountManagement.ADStoreCtx.FindPrincipalByIdentRefHelper(Type principalType,String urnScheme,String urnValue,DateTime referenceDate,Boolean useSidHistory)+1898 System. DirectoryServices.AccountManagement.ADStoreCtx.FindPrincipalByIdentRef(类型principalType,String urnScheme,String urnValue,DateTime referenceDate)+85 System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context,Type principalType,Nullable`1 identityType,String identityValue,DateTime refDate)+ 211 System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context,String identi)tyValue)+95 WebApplication1.Index.GetUserPrincipal(String userName)在C:\ Users\xxx\Documents\Visual Studio 2010\Projects\WebApplication1\WebApplication1\Index.aspx.cs:38 WebApplication1.Index.Page_Load(Object sender,EventArgs) e)在C:\ Users\xxx\Documents\Visual Studio 2010\Projects\WebApplication1\WebApplication1\Index.aspx.cs:19 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp,Object o,Object t,EventArgs e) )+25 System.Web.UI.Control.LoadRecursive()+71 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint,Boolean includeStagesAfterAsyncPoint)+3064
是否有任何方法可以让这个用于获取本地用户UserPrincipal 而Windows和匿名身份验证都打开?
我有以下带有两棵树的AD森林:
Domain1的DNS名称是domain1.local.Domain4的DNS名称是domain4.local.
在每个域中都有一个启用了全局编录的域控制器.
我正在尝试通过其SID从域4获取UserPrincipal.该程序从Domain2中的计算机运行.
我使用以下代码:
// Running on some machine from Domain2
PrincipalContext context = new PrincipalContext(
ContextType.Domain,
"dc2.domain2.domain1.local:3268", // Using Global Catalog port and local domain controller
"DC=domain1, DC=local", // I guess the problem is here
"domain1\\super-admin", // User has all necessary rights across all domains
"password");
UserPrincipal principal = UserPrincipal.FindByIdentity(context, "SID-OF-A-USER-FROM-DOMAIN-4");
Run Code Online (Sandbox Code Playgroud)
在我的情况下,principal为null(找不到用户).
在一个树(domain1及其子代)中搜索可以正常使用上面的代码片段,但我不知道如何修改PrincipalContext构造函数的容器参数以真正启用林范围的搜索.
最初我认为"DC = domain1,DC = local"指向了林根,但似乎我在这里有误解.
我知道如果我将容器路径更改为"DC = domain4,DC = local",那么搜索将起作用,但仅适用于domain4中的用户.
但我真的需要这样一个指向整个林的容器路径,因此我可以使用相同的PrincipalContext从林中的任何域搜索用户.
任何帮助都表示赞赏,特别是如果有人能澄清我的要求是否可以实现.
由于某些原因,GetAuthorizationGroups()似乎需要大约20秒才能返回群组.我正在使用此代码:
UserPrincipal user;
// This takes 20 seconds
user.GetAuthorizationGroups().OfType<GroupPrincipal>().ToList();
Run Code Online (Sandbox Code Playgroud)
任何人有任何想法或只是一个缓慢的AD域?(例如,在Outlook中查看组不需要很长时间)
我对 UserPrincipal 类进行扩展以检索我需要的一些缺失的属性:
[DirectoryObjectClass("user")]
[DirectoryRdnPrefix("CN")]
class UserPrincipalExt : UserPrincipal
{
public UserPrincipalExt(PrincipalContext context)
: base(context)
{
}
[DirectoryProperty("department")]
public string Department
{
get
{
if (ExtensionGet("department").Length != 1)
return null;
return (string)ExtensionGet("department")[0];
}
set
{
this.ExtensionSet("department", value);
}
}
[DirectoryProperty("company")]
public string Company
{
get
{
if (ExtensionGet("company").Length != 1)
return null;
return (string)ExtensionGet("company")[0];
}
set
{
this.ExtensionSet("company", value);
}
}
[DirectoryProperty("c")]
public string CountryAbbreviation
{
get
{
if (ExtensionGet("c").Length != 1)
return null;
return (string)ExtensionGet("c")[0];
}
set
{
this.ExtensionSet("c", …Run Code Online (Sandbox Code Playgroud) c# active-directory userprincipal principalsearcher groupprincipal
我在这个stackoverflow问题中看到了一些使用AD的代码
我对使用声明感到困惑.我认为它只是用于你担心可能会成为内存泄漏的东西,比如WebClient或者类似的......
无论如何:
using (var context = new PrincipalContext( ContextType.Domain ))
{
using (var user = UserPrincipal.FindByIdentity( context, "username" ))
{
var groups = user.GetAuthorizationGroups();
...
}
}
Run Code Online (Sandbox Code Playgroud)
当我到达该行时var groups = user.GetAuthorizationGroups()- user为null,因此该行失败并显示NullReference.当我鼠标悬停它调试它显示null,然后显示静态成员,并具有所有值.
如果我从use语句中取出该行,只需var user = UserPrincipal.FindByIdentity( context, "username" )根据需要填充用户.
发生什么了 ???
编辑:我塞满了,发送了一个伪造的用户名.奇怪的是,当我在调试期间检查变量时,如果我发送伪造的用户ID,你会期望用户完全为空,但是它显示在user:null,静态成员下,并且我有当前登录的值 - 所以我认为这可能与使用声明有关.干杯!
今天早上,我开始注意到我的几个程序在 Active Directory 读取操作方面存在一些问题。我注意到所有这些应用程序(客户端和服务器)都使用System.DirectoryServices.AccountManagement.UserPrincipal该类进行读取操作,而仍然正确运行的程序则使用System.DirectoryServices.DirectorySearcher.
因此,为了缩小问题范围,我构建了以下非常简单的控制台应用程序
\nclass Program\n{\n static void Main(string[] args)\n {\n //this works great\n Console.WriteLine($"Enviroment.Username:{Environment.UserName}");\n\n //this works great\n PrincipalContext pcFull = new PrincipalContext(ContextType.Domain, "my.company.de", "dc=my,dc=company,dc=de");\n UserPrincipal upPrincipalContextFull = UserPrincipal.FindByIdentity(pcFull, Environment.UserName);\n\n //this doesn\'t work at all\n //Exception: \xe2\x80\x9cThe specified directory service attribute or value does not exist\xe2\x80\x9d\n PrincipalContext pc = new PrincipalContext(ContextType.Domain);\n UserPrincipal upPrincipalContext = UserPrincipal.FindByIdentity(pc, Environment.UserName);\n\n //this doesn\'t either, same exception\n UserPrincipal upCurrent = UserPrincipal.Current;\n \n Console.ReadKey();\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n正如您在评论中看到的,后两个操作在我测试的域中的每台计算机上都会失败,即使它们完美运行了几年。UserPrincipal.Current当我调用或未UserPrincipal.FindByIdentity(pc, …
我正在使用ASP.NET MVC 4和Windows身份验证.当我使用VisualStudio时,一切正常,但是当我部署我的网站时,会抛出异常.
var emailAddress = UserPrincipal.Current.EmailAddress;
Run Code Online (Sandbox Code Playgroud)
抛出:
无法将类型为"System.DirectoryServices.AccountManagement.GroupPrincipal"的对象强制转换为"System.DirectoryServices.AccountManagement.UserPrincipal".
其余的工作正常.用户可以进行身份验证,我可以获取用户名等.
编辑:
我在IIS上启用了Impersonation.现在我得到以下异常:
[DirectoryServicesCOMException(0x80072020):发生操作错误.] System.DirectoryServices.DirectoryEntry.Bind(布尔throwIfFail)781 System.DirectoryServices.DirectoryEntry.Bind()44 System.DirectoryServices.DirectoryEntry.get_AdsObject()42 System.DirectoryServices.PropertyValueCollection.PopulateList()29周
的System.DirectoryServices .PropertyValueCollection..ctor(DirectoryEntry entry,String propertyName)+119
System.DirectoryServices.PropertyCollection.get_Item(String propertyName)+163
System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInitNoContainer()+535649 System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit( )+51 System.DirectoryServices.AccountManagement.PrincipalContext.Initialize()+ 141 System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx()+42 System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context,Type principalType,Nullable`1 identityType, String identityValue,DateTime refDate)+27
System.DirectoryServices.Account Management.Principal.FindByIdentityWithType(PrincipalContext context,Type principalType,IdentityType identityType,String identityValue)+146
System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context,IdentityType identityType,String identityValue)+44
System.DirectoryServices.AccountManagement.UserPrincipal.get_Current ()390 Jericho.MVC.HtmlHelperExtensions.GetUser(的HtmlHelper的HtmlHelper)在C:\发展\杰里科\ Jericho.MVC\HtmlHelperExtensions.cs:48
我能做什么?
c# asp.net-mvc directoryservices windows-authentication userprincipal
我也有使用插件和appdomains的长期服务,并且因使用目录服务而导致内存泄漏.请注意,我使用的是system.directoryservices.accountmanagement,但我理解它使用相同的底层ADSI API,因此容易出现相同的内存泄漏.
我查看了所有CLR内存计数器,并且内存没有泄漏,并且都是在强制GC或卸载appdomain时返回的.泄漏是私有字节,不断增长.我在这里搜索并看到了一些与使用ADSI API时内存泄漏相关的问题,但它们似乎表明只需遍历directorysearcher即可解决问题.但正如您在下面的代码中看到的那样,我在foreach块中执行此操作,但内存仍然被泄露.有什么建议?这是我的方法:
public override void JustGronkIT()
{
using (log4net.ThreadContext.Stacks["NDC"].Push(GetMyMethodName()))
{
Log.Info("Inside " + GetMyMethodName() + " Method.");
System.Configuration.AppSettingsReader reader = new System.Configuration.AppSettingsReader();
//PrincipalContext AD = null;
using (PrincipalContext AD = new PrincipalContext(ContextType.Domain, (string)reader.GetValue("Domain", typeof(string))))
{
UserPrincipal u = new UserPrincipal(AD);
u.Enabled = true;
//u.Surname = "ju*";
using (PrincipalSearcher ps = new PrincipalSearcher(u))
{
myADUsers = new ADDataSet();
myADUsers.ADUsers.MinimumCapacity = 60000;
myADUsers.ADUsers.CaseSensitive = false;
foreach (UserPrincipal result in ps.FindAll())
{
myADUsers.ADUsers.AddADUsersRow(result.SamAccountName, result.GivenName, result.MiddleName, result.Surname, result.EmailAddress, result.VoiceTelephoneNumber,
result.UserPrincipalName, result.DistinguishedName, result.Description); …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用一种方法,该方法接受用户名,如果该用户是本地管理员(不是整个域,只是本地计算机),则返回 true,否则返回 false。我试图改变在 .NET/C# 测试中找到的技术,如果进程有管理权限可以工作,但它没有。我曾尝试使用 NetUserGetInfo 方式,但无法使其正常工作。现在我正在尝试使用 UserPrincipal。下面的代码是我所拥有的全部……主要只是测试基础知识是否有效并且它们确实有效。
PrincipalContext ctx = new PrincipalContext(ContextType.Machine);
UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userId);
if(usr == null)
{
Console.WriteLine("usr is null");
}
else
{
Console.WriteLine(usr.Enabled);
Console.WriteLine(usr.IsAccountLockedOut());
foreach (Principal p in usr.GetAuthorizationGroups())
{
Console.WriteLine(p.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
看起来我应该可以使用 isMemberOf 方法,但是如何为本地管理员创建一个组?或者有比 isMemberOf 方法更好的方法吗?
c# admin active-directory active-directory-group userprincipal
c# ×10
userprincipal ×10
.net ×4
admin ×1
asp.net ×1
asp.net-mvc ×1
dns ×1
iis-7.5 ×1
using ×1