是否有更好(更简单)的方法来获取特定域的 SID?
我被指派修改 WinForms 应用程序,主要检查登录用户是否属于特定域。 这就是我到目前为止所想出的:
byte[] domainSid;
var directoryContext =
new DirectoryContext(DirectoryContextType.Domain, "domain.se");
using (var domain = Domain.GetDomain(directoryContext))
using (var directoryEntry = domain.GetDirectoryEntry())
domainSid = (byte[])directoryEntry.Properties["objectSid"].Value;
var sid = new SecurityIdentifier(domainSid, 0);
bool validUser = UserPrincipal.Current.Sid.IsEqualDomainSid(sid);
有更好/更简单的方法来做到这一点吗? 对我来说,似乎可以使用PrincipalContext或System.Security.Principal中的其他类以某种方式访问domainSid。
我考虑过使用硬编码的 SID 字符串,但我不知道这有多“正确”。
I've been assigned to modify a WinForms application to basically check that the logged on user belongs to a specific domain.
This is what I've come up with so far:
byte[] domainSid;
var directoryContext =
new DirectoryContext(DirectoryContextType.Domain, "domain.se");
using (var domain = Domain.GetDomain(directoryContext))
using (var directoryEntry = domain.GetDirectoryEntry())
domainSid = (byte[])directoryEntry.Properties["objectSid"].Value;
var sid = new SecurityIdentifier(domainSid, 0);
bool validUser = UserPrincipal.Current.Sid.IsEqualDomainSid(sid);
Is there a better/easier way to do this?
To me it seems like the domainSid would be accessible in some way using the PrincipalContext or some other class in System.Security.Principal.
I've considered using a hardcoded SID-string, but I don't know how "correct" that would be.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你正在做的事情对我来说似乎是最好的选择。对字符串进行硬编码绝对不是一个好主意。
What you're doing looks like the best option to me. Hardcoding strings is definetely not a good idea.
每个域都有一个内置帐户 domainName\administrator,因此您可以使用此名称创建一个帐户,将其转换为 SecurityIdentifier 并读取 AccountDomainSid 属性。
这种方式的一个例子是:
您还可以找到其他解决方案来通过 WMI 或 Lsa 实现相同的结果。这对我来说似乎是最优雅的方式。
Each domain has a build in account domainName\administrator, so you can create an account with this name, translate it to the SecurityIdentifier and read the AccountDomainSid property.
An example of this way is:
Also you can find other solutions to achieve the same result via WMI or Lsa. This one seems the most elegant way for me.
这是与已接受答案略有不同的方法:
C#
C# One Liner
PowerShell:
PowerShell 1 Liner:
Here's a slightly different approach to the accepted answer:
C#
C# One Liner
PowerShell:
PowerShell 1 Liner:
要获取域的 sid,只需要这个简单的查询:
注意:当域名无法解析或用户没有查询 Active Directory 的权限时,此方法会引发异常。
To get the sid of domain just this simple query is needed:
Caution: this method throws exceptions when the domain name cannot be resolved or the user has no permissions to query Active Directory.