有没有更好的(容易)的方式获取特定域的SID?容易、方式、SID

2023-09-07 16:01:02 作者:曾經不屑,如今卻不舍

我被分配到修改WinForms应用程序基本上检查登录的用户属于某个特定域。 这是我想出来的,到目前为止:

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

有没有更好/更简单的方式做到这一点? 对我来说,好像domainSid将是使用PrincipalContext或System.Security.Principal其他类某种方式进行访问。

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.

我使用的是硬codeD SID字符串考虑过,但我不知道如何正确,这将是。

I've considered using a hardcoded SID-string, but I don't know how "correct" that would be.

推荐答案

你在做什么样子对我最好的选择。硬编码字符串是definetely不是一个好主意。

What you're doing looks like the best option to me. Hardcoding strings is definetely not a good idea.