用户和用户组,以及文件和文件夹的权限
Authenticated Users
System
Administrators
Users
假如一个用户属于2个用户组的话,deny的优先级更高
log在写文件的时候,如果没有权限访问。会遇到UnauthorizedAccessException,这个异常需要直接抛出到顶层
获取当前用户
Console.WriteLine(WindowsIdentity.GetCurrent().Name);
Console.WriteLine(Environment.UserName);
Console.WriteLine(Environment.UserDomainName);
获取当前用户属于哪些用户组
方法1 只能获取20个用户 GetGroups
var userName = "clu"; var domainName = "asnet"; PrincipalContext principalContext = new PrincipalContext(ContextType.Domain,domainName); var userPrincipal = UserPrincipal.FindByIdentity(principalContext, userName); List<string> result=new List<string>(); if (userPrincipal != null) { var groups = userPrincipal.GetGroups(); foreach (Principal item in groups) { if (item is GroupPrincipal) { result.Add($@"GroupName = {item.Name}, DisplayName = {item.DisplayName}, Description = {item.Description}, Guid = {item.Guid}"); } } } Console.WriteLine($@"GroupCount = {result.Count}"); foreach (var item in result) { Console.WriteLine(item); }
GroupCount = 20
GroupName = SYG - ISC RDC, DisplayName = SYG - ISC RDC, Description = , Guid = 599392b2-cc8b-4e9e-8a6d-ff01539946d9
方法2 可以获取104个用户组 GetAuthorizationGroups
var userName = "clu"; var domainName = "asnet"; PrincipalContext principalContext = new PrincipalContext(ContextType.Domain,domainName); var userPrincipal = UserPrincipal.FindByIdentity(principalContext, userName); List<string> result=new List<string>(); if (userPrincipal != null) { var groups = userPrincipal.GetAuthorizationGroups(); foreach (Principal item in groups) { if (item is GroupPrincipal) { result.Add($@"GroupName = {item.Name}, DisplayName = {item.DisplayName}, Description = {item.Description}, Guid = {item.Guid}"); } } } Console.WriteLine($@"GroupCount = {result.Count}"); foreach (var item in result) { Console.WriteLine(item); }
GroupCount = 104
方法3 据说可以获取nested groups,虽然获取到的也是104个用户组
GetAuthorizationGroups()
does not find nested groups. To really get all groups a given user is a member of (including nested groups), try this:
List<string> result = new List<string>(); WindowsIdentity wi = new WindowsIdentity("clu"); foreach (IdentityReference group in wi.Groups) { try { result.Add(group.Translate(typeof(NTAccount)).ToString()); } catch (Exception ex) { } } result.Sort(); Console.WriteLine($@"GroupCount = {result.Count}"); foreach (var item in result) { Console.WriteLine(item); }
方法4 这个方法只能获取19个用户组
First of all, GetAuthorizationGroups() is a great function but unfortunately has 2 disadvantages:
- Performance is poor, especially in big company's with many users and groups. It fetches a lot more data then you actually need and does a server call for each loop iteration in the result
- It contains bugs which can cause your application to stop working 'some day' when groups and users are evolving. Microsoft recognized the issue and is related with some SID's. The error you'll get is "An error occurred while enumerating the groups"
Therefore, I've wrote a small function to replace GetAuthorizationGroups() with better performance and error-safe. It does only 1 LDAP call with a query using indexed fields. It can be easily extended if you need more properties than only the group names ("cn" property).
最后一句看不懂,cn property不知道是干嘛的
var userName = "clu"; var domainName = "asnet"; var result = new List<string>(); if (userName.Contains('\\') || userName.Contains('/')) { domainName = userName.Split(new char[] { '\\', '/' })[0]; userName = userName.Split(new char[] { '\\', '/' })[1]; } using (PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domainName)) using (UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, userName)) using (var searcher = new DirectorySearcher(new DirectoryEntry("LDAP://" + domainContext.Name))) { searcher.Filter = String.Format("(&(objectCategory=group)(member={0}))", user.DistinguishedName); searcher.SearchScope = SearchScope.Subtree; searcher.PropertiesToLoad.Add("cn"); foreach (SearchResult entry in searcher.FindAll()) if (entry.Properties.Contains("cn")) result.Add(entry.Properties["cn"][0].ToString()); } Console.WriteLine($@"GroupCount = {result.Count}"); foreach (var item in result) { Console.WriteLine(item); }
方法5 更快的方法 只获取了98个用户组
DirectorySearcher ds = new DirectorySearcher(); ds.Filter = String.Format("(&(objectClass=user)(sAMAccountName={0}))", @"clu"); SearchResult sr = ds.FindOne(); DirectoryEntry user = sr.GetDirectoryEntry(); user.RefreshCache(new string[] { "tokenGroups" }); var result = new List<string>(); for (int i = 0; i < user.Properties["tokenGroups"].Count; i++) { SecurityIdentifier sid = new SecurityIdentifier((byte[])user.Properties["tokenGroups"][i], 0); NTAccount nt = (NTAccount)sid.Translate(typeof(NTAccount)); //do something with the SID or name (nt.Value) result.Add(nt.Value); } Console.WriteLine($@"GroupCount = {result.Count}"); foreach (var item in result) { Console.WriteLine(item); }
获取指定的用户组有哪些用户
var domainName = "asnet"; var groupName = "SYG - ISC RDC"; PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domainName); var groupPrincipal = GroupPrincipal.FindByIdentity(principalContext, groupName); List<string> result = new List<string>(); if (groupPrincipal != null) { var users = groupPrincipal.GetMembers(true); foreach (UserPrincipal user in users) { result.Add( $"EmployeeId = {user.EmployeeId}, {user.DisplayName}, {user.EmailAddress}, {user.GivenName}, {user.MiddleName}, {user.Surname}"); } } else { Console.WriteLine($@"Can not find user group named as {groupName}"); } Console.WriteLine($@"UserCount = {result.Count}"); foreach (var item in result) { Console.WriteLine(item); }
获取用户是否有某一个文件的写权限
string path = @"D:\ChuckLu\Git\Edenred\LISA_5.0.0.0\LISA.ControlPanel\LISA.ControlPanel\bin\Debug\log\20171206.0.log"; string NtAccountName = @"asnet\clu"; FileInfo fileInfo = new FileInfo(path); var fileSecurity = fileInfo.GetAccessControl(); var authorizationRuleCollection = fileSecurity.GetAccessRules(true, true, typeof(NTAccount)); foreach (AuthorizationRule item in authorizationRuleCollection) { Console.WriteLine(item.IdentityReference); if (item.IdentityReference.Value.Equals(NtAccountName, StringComparison.OrdinalIgnoreCase)) { var item1 = item as FileSystemAccessRule; if (item1 != null) { if ((item1.FileSystemRights & FileSystemRights.WriteData) > 0) { Console.WriteLine(string.Format("{0} has write access to {1}", NtAccountName, path)); } else { Console.WriteLine(string.Format("{0} does not have write access to {1}", NtAccountName, path)); } } else { Console.WriteLine($@"{item.IdentityReference} can not convert to FileSystemAccessRule"); } } }
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2016-12-05 devenv.exe assert failure
2014-12-05 arp攻击的处理方法
2014-12-05 使用vs的时候,遇到这个:当前不会命中断点 还没有为该文档加载任何符号
2013-12-05 User-Defined Table Types 用户自定义表类型
2013-12-05 sql server 基础知识