Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running as Admin, How do I check if some windows account has permissions to read a directory?

I only got the account username (DOMAIN\USER). The check also has to take into account the user's groups. I'd like to use this sample, but I can't figure out how to get a WindowsIdentity only from a username without his password.

like image 910
Zvika Avatar asked Nov 05 '22 13:11

Zvika


2 Answers

Whole problematics of getting effective rights for some folder or file is rather complex. But you don't need to get WindowsIdentity from username and domain name. For reading effective rights it is enough to have SID of the user you are checking.

There is a class NTAccount which takes exactly what you have - username and domain, that can be easily translated to the SecurityIdentifier, which represents exactly one SID.

There classes can be found in System.Security.Principal namespace.

NTAccount ntaccount = new NTAccount("domain", "username");
SecurityIdentifier identifier =
    (SecurityIdentifier)ntaccount.Translate(typeof(SecurityIdentifier)); 

In this way you can translate username (with or without domain) to the SID which can be then used for determining to which groups this user belongs (recursively) and then you can easily read access rights using FileSecurity class (from FileInfo) and its method GetAccessRules.

like image 122
Lukáš Rubeš Avatar answered Nov 14 '22 22:11

Lukáš Rubeš


You can make use of following code:

DirectorySecurity security = directoryInfo.GetAccessControl();
AuthorizationRuleCollection authCollection = security.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));

var username = (from FileSystemAccessRule rule in authCollection
                where rule.IdentityReference.Value == "domain\\username"
                select rule).ToList();
like image 38
danish Avatar answered Nov 15 '22 00:11

danish