草庐IT

关于 c#:如何从 DOMAIN\\user 格式的用户名创建 WindowsIdentity/WindowsPrincipal

codeneng 2023-03-28 原文

How to create WindowsIdentity/WindowsPrincipal from username in DOMAIN\user format

WindowsIdentity(string) 构造函数要求用户名为 username@domain.com 格式。但在我的情况下,我从数据库中以旧的 DOMAIN\\user 格式获取用户名(然后必须检查他们的 Windows 角色成员身份)。

从旧样式 (sAMAccountName) 用户名??创建 WindowsPrincipal 的最佳方法是什么?

  • 您可以使用 DsCrackNames API 来转换格式。
  • 我在这里找到了一个 DsCrackNames C# 示例:technolog.nl/blogs/eprogrammer/archive/2005/11/16/…2800_upda??te_2900.aspx


似乎没有办法在不涉及对 Active Directory 的查询的情况下转换用户名格式。由于是这种情况,因此无需创建 WindowsPrincipal 来检查组成员身份,因为这可能需要另一个与 AD 的连接。

通过使用 System.DirectoryServices.AccountManagement 命名空间,您可以获得用户的 UPN 并检查组成员。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
string accountName = @"DOMAIN\\user";
var groupNames = new[] {"DOMAIN\\Domain Users","DOMAIN\\Group2" }; // the groups that we need to verify if the user is member of

// cannot create WindowsIdentity because it requires username in form user@domain.com but the passed value will be DOMAIN\\user.
using (var pc = new PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, Environment.UserDomainName))
{
    using (var p = UserPrincipal.FindByIdentity(pc, accountName))
    {
        // if the account does not exist or is not an user account
        if (p == null)
            return new string[0];

        // if you need just the UPN of the user, you can use this
        ////return p.UserPrincipalName;

        // find all groups the user is member of (the check is recursive).
        // Guid != null check is intended to remove all built-in objects that are not really AD gorups.
        // the Sid.Translate method gets the DOMAIN\\Group name format.
        var userIsMemberOf = p.GetAuthorizationGroups().Where(o => o.Guid != null).Select(o => o.Sid.Translate(typeof(NTAccount)).ToString());

        // use a HashSet to find the group the user is member of.
        var groups = new HashSet<string>(userIsMemberOf, StringComparer.OrdinalIgnoreCase);
        groups.IntersectWith(groupNames);

        return groups;
    }
}

  • 哪个 .NET 框架版本?和组件?哪个是 AccountManagement、PrincipalContext、UserPrincipal、StringComparer 类?
  • 为什么 UserPrincipal 在 using 语句中?它没有 Dispose() 方法?!
  • @Muflix - 它(和任何委托人)确实实现了 IDisposable:docs.microsoft.com/en-us/dotnet/api/...


这可以正常工作,但涉及对活动目录/SAM 存储的查询(取决于上下文)...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private WindowsIdentity GetWindowsIdentity(
  string userName)
{
  using (var user =
    UserPrincipal.FindByIdentity(
      UserPrincipal.Current.Context,
      IdentityType.SamAccountName,
      userName
      ) ??
    UserPrincipal.FindByIdentity(
      UserPrincipal.Current.Context,
      IdentityType.UserPrincipalName,
      userName
      ))
  {
    return user == null
      ? null
      : new WindowsIdentity(user.UserPrincipalName);
  }
}


我使用了 pinvoke.net 示例中的 DsCrackNames 并对其进行了修改,以将其从 nt4 名称转换为 UPN。它有点马虎,你可能想清理一下。为此,它也必须击中 DS。他们有 DS_NAME_FLAG_SYNTACTICAL_ONLY 标志,可用于不点击目录,但我认为这不会在这里工作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
class Entry
{

    const uint NO_ERROR = 0;
    [DllImport("ntdsapi.dll", CharSet = CharSet.Auto)]
    static public extern uint DsCrackNames(
      IntPtr hDS,
      DS_NAME_FLAGS flags,
      DS_NAME_FORMAT formatOffered,
      DS_NAME_FORMAT formatDesired,
      uint cNames,
      string[] rpNames,
      out IntPtr ppResult  // PDS_NAME_RESULT
      );

    [DllImport("ntdsapi.dll", CharSet = CharSet.Auto)]
    static public extern void DsFreeNameResult(IntPtr pResult /* DS_NAME_RESULT* */);

    public enum DS_NAME_ERROR
    {
        DS_NAME_NO_ERROR = 0,

        // Generic processing error.
        DS_NAME_ERROR_RESOLVING = 1,

        // Couldn't find the name at all - or perhaps caller doesn't have
        // rights to see it.
        DS_NAME_ERROR_NOT_FOUND = 2,

        // Input name mapped to more than one output name.
        DS_NAME_ERROR_NOT_UNIQUE = 3,

        // Input name found, but not the associated output format.
        // Can happen if object doesn't have all the required attributes.
        DS_NAME_ERROR_NO_MAPPING = 4,

        // Unable to resolve entire name, but was able to determine which
        // domain object resides in.  Thus DS_NAME_RESULT_ITEM?.pDomain
        // is valid on return.
        DS_NAME_ERROR_DOMAIN_ONLY = 5,

        // Unable to perform a purely syntactical mapping at the client
        // without going out on the wire.
        DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING = 6,

        // The name is from an external trusted forest.
        DS_NAME_ERROR_TRUST_REFERRAL = 7

    }

    [Flags]
    public enum DS_NAME_FLAGS
    {
        DS_NAME_NO_FLAGS = 0x0,

        // Perform a syntactical mapping at the client (if possible) without
        // going out on the wire.  Returns DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING
        // if a purely syntactical mapping is not possible.
        DS_NAME_FLAG_SYNTACTICAL_ONLY = 0x1,

        // Force a trip to the DC for evaluation, even if this could be
        // locally cracked syntactically.
        DS_NAME_FLAG_EVAL_AT_DC = 0x2,

        // The call fails if the DC is not a GC
        DS_NAME_FLAG_GCVERIFY = 0x4,

        // Enable cross forest trust referral
        DS_NAME_FLAG_TRUST_REFERRAL = 0x8

    }

    public enum DS_NAME_FORMAT
    {
        // unknown name type
        DS_UNKNOWN_NAME = 0,

        // eg: CN=User Name,OU=Users,DC=Example,DC=Microsoft,DC=Com
        DS_FQDN_1779_NAME = 1,

        // eg: Example\\UserN
        // Domain-only version includes trailing '\\\'.
        DS_NT4_ACCOUNT_NAME = 2,

        // Probably"User Name" but could be something else.  I.e. The
        // display name is not necessarily the defining RDN.
        DS_DISPLAY_NAME = 3,

        // obsolete - see #define later
        // DS_DOMAIN_SIMPLE_NAME = 4,

        // obsolete - see #define later
        // DS_ENTERPRISE_SIMPLE_NAME = 5,

        // String-ized GUID as returned by IIDFromString().
        // eg: {4fa050f0-f561-11cf-bdd9-00aa003a77b6}
        DS_UNIQUE_ID_NAME = 6,

        // eg: example.microsoft.com/software/user name
        // Domain-only version includes trailing '/'.
        DS_CANONICAL_NAME = 7,

        // eg: usern@example.microsoft.com
        DS_USER_PRINCIPAL_NAME = 8,

        // Same as DS_CANONICAL_NAME except that rightmost '/' is
        // replaced with '\
' - even in domain-only case.
        // eg: example.microsoft.com/software\
user name
        DS_CANONICAL_NAME_EX = 9,

        // eg: www/www.microsoft.com@example.com - generalized service principal
        // names.
        DS_SERVICE_PRINCIPAL_NAME = 10,

        // This is the string representation of a SID.  Invalid for formatDesired.
        // See sddl.h for SID binary <--> text conversion routines.
        // eg: S-1-5-21-397955417-626881126-188441444-501
        DS_SID_OR_SID_HISTORY_NAME = 11,

        // Pseudo-name format so GetUserNameEx can return the DNS domain name to
        // a caller.  This level is not supported by the DS APIs.
        DS_DNS_DOMAIN_NAME = 12
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public struct DS_NAME_RESULT_ITEM
    {
        public DS_NAME_ERROR status;
        public string pDomain;
        public string pName;
    }

    [DllImport("ntdsapi.dll", CharSet = CharSet.Auto)]
    static public extern uint DsBind(
      string DomainControllerName,      // in, optional
      string DnsDomainName,         // in, optional
      out IntPtr phDS);

    [DllImport("ntdsapi.dll", CharSet = CharSet.Auto)]
    static public extern uint DsUnBind(ref IntPtr phDS);

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public struct DS_NAME_RESULT
    {
        public uint cItems;
        public IntPtr rItems; // PDS_NAME_RESULT_ITEM
    }

    [STAThread]
    static void Main(string[] args)
    {
        // Bind to default global catalog
        IntPtr hDS;
        uint err = DsBind(null, null, out hDS);
        if (err != NO_ERROR)
        {
            Console.WriteLine("Error on DsBind : {0}", err);
            return;
        }
        // Crack the currently logged on name
        try
        {
            string[] names = new string[] { System.Security.Principal.WindowsIdentity.GetCurrent().Name };
            DS_NAME_RESULT_ITEM[] results =
              HandleDsCrackNames(hDS, DS_NAME_FLAGS.DS_NAME_NO_FLAGS, DS_NAME_FORMAT.DS_NT4_ACCOUNT_NAME, DS_NAME_FORMAT.DS_USER_PRINCIPAL_NAME, names);
            foreach (DS_NAME_RESULT_ITEM result in results)
            {
                Console.WriteLine("Result : {0}\
\
Domain : {1}\
\
Name : {2}", result.status, result.pDomain, result.pName);
            }
        }
        finally
        {
            DsUnBind(ref hDS);
        }
    }

    /// <summary>
    /// A wrapper function for the DsCrackNames OS call
    /// </summary>
    /// <param name="hDS">DsBind handle</param>
    /// <param name="flags">Flags controlling the process</param>
    /// <param name="formatOffered">Format of the names</param>
    /// <param name="formatDesired">Desired format for the names</param>
    /// <param name="names">The names to crack</param>
    /// <returns>The crack result</returns>
    public static DS_NAME_RESULT_ITEM[] HandleDsCrackNames(IntPtr hDS, DS_NAME_FLAGS flags, DS_NAME_FORMAT formatOffered, DS_NAME_FORMAT formatDesired, string[] names)
    {
        IntPtr pResult;
        DS_NAME_RESULT_ITEM[] ResultArray;
        uint err = DsCrackNames(
      hDS,
      flags,
      formatOffered,
      formatDesired,
      (uint)((names == null) ? 0 : names.Length),
      names,
      out pResult);
        if (err != NO_ERROR)
            throw new System.ComponentModel.Win32Exception((int)err);
        try
        {
            // Next convert the returned structure to managed environment
            DS_NAME_RESULT Result = new DS_NAME_RESULT();
            Result.cItems = (uint)Marshal.ReadInt32(pResult);
            Result.rItems = Marshal.ReadIntPtr(pResult, Marshal.OffsetOf(typeof(DS_NAME_RESULT),"rItems").ToInt32());
            IntPtr curptr = Result.rItems;
            ResultArray = new DS_NAME_RESULT_ITEM[Result.cItems];
            for (int index = 0; index < (int)Result.cItems; index++)
            {
                ResultArray[index] = (DS_NAME_RESULT_ITEM)Marshal.PtrToStructure(curptr, typeof(DS_NAME_RESULT_ITEM));
                curptr = (IntPtr)((int)curptr + Marshal.SizeOf(ResultArray[index]));
            }
        }
        finally
        {
            DsFreeNameResult(pResult);
        }
        return ResultArray;
    }

}

  • 谢谢你的努力。不幸的是,由于这涉及查询 AD,因此使用 System.DirectoryServices 命名空间似乎是一个更好的主意......虽然 - 这种方法可能会提供更好的性能。

有关关于 c#:如何从 DOMAIN\\user 格式的用户名创建 WindowsIdentity/WindowsPrincipal的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  4. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  5. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  6. ruby - 在 Ruby 中实现 `call_user_func_array` - 2

    我怎样才能完成http://php.net/manual/en/function.call-user-func-array.php在ruby中?所以我可以这样做:classAppdeffoo(a,b)putsa+benddefbarargs=[1,2]App.send(:foo,args)#doesn'tworkApp.send(:foo,args[0],args[1])#doeswork,butdoesnotscaleendend 最佳答案 尝试分解数组App.send(:foo,*args)

  7. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  8. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  9. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  10. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

随机推荐