您的位置:首页 > 其它

用户和用户组,以及文件和文件夹的权限

2017-12-05 16:04 253 查看
Authenticated Users

System

Administrators

Users

假如一个用户属于2个用户组的话,deny的优先级更高





log在写文件的时候,如果没有权限访问。会遇到UnauthorizedAccessException,这个异常需要直接抛出到顶层

获取当前用户

Console.WriteLine(WindowsIdentity.GetCurrent().Name);
Console.WriteLine(Environment.UserName);
Console.WriteLine(Environment.UserDomainName);


获取当前用户属于哪些用户组

https://stackoverflow.com/questions/5309988/how-to-get-the-groups-of-a-user-in-active-directory-c-asp-net

方法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个用户组

https://stackoverflow.com/questions/4460558/how-to-get-all-the-ad-groups-for-a-particular-user/4460658#4460658

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");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐