Search code examples
c#file-permissions

Web service needs to check NTFS file permissions for user


We have an asp.net mvc web service that needs to be able to check NTFS permissions on network folders, and to return a list of only those folders and files to the UI that the user is authorized to view. We can't use impersonation for this. How would we go about accomplishing this?


Solution

  • In tackling this problem, I found this question helpful, but it didn't quite meet our needs:
    Effective file permissions tool's api in windows. Thanks to @YacoubMassad for pointing me in this direction. Using this code, I created an effective permissions service to check for Read permissions, but I ran into an unexpected issue. The service would work properly for folders for which the user had View permissions, but it would incorrectly return true for others because it wasn't returning a mask for them. The result was that my service displayed a list of folders the user wasn't authorized to view. I'm guessing I could have altered my service to address this, but it was getting complicated.

    The solution I went with isn't as elegant, but is simple and effective. I wrote a method that calls GetDirectories() for each directory. For each directory that GetDirectories() executes successfully, the path is added to a list which gets returned to the view. Since our permissions are handled at the directory level, this was as far as I needed to go. I handle any UnauthorizedAccessExceptions on the files as well, just in case permissions are ever set at that level.

            public IList<FilePathObject> PopulateAuthorizedPathList()
            {
                IList<FilePathObject> authorizedPathList = new List<FilePathObject>();
                foreach (FilePathObject pathObject in fullPathList)
                {
                    var dir = new DirectoryInfo(pathObject.FullPath);
                    if (dir.Exists)
                    {
                        try
                        {
                            var info = dir.GetDirectories();
                            authorizedPathList.Add(pathObject);
                        }
                        catch (UnauthorizedAccessException ex)
                        {
    
                        }
                    }
                }
                return authorizedPathList;
            }