Access to file is denied exception with asp.net impersonation - c#

I am trying to access the files with following c# code, but when i try to execute the code i am encountered with exception saying access to path #"\MAHESH-PC\D$\temp\CloudURL.txt is denied .
Impersonation imp = new Impersonation("MAHESH-PC", "mahesh", "welcome");
File.Copy(#"\MAHESH-PC\D$\temp\CloudURL.txt", #"C:\temp\CloudURL.txt", true);
I have given all the access rights to both the temp folders one in the c: drive and other in the d: drive
I have enabled the Impersonation in the IIS , even then i am getting access denied exception , please can i know is their any other settings i should implement to make this working.

Is impersonation enabled in your web.config? I'm not positive but I wouldn't think enabling impersonation in IIS has any affect on the impersonation of your site. If not, turn it on, or grant the app pool identity read/write access to both your directories and see if that helps.
Also, double check your folder system security. It appears you granted everyone read/write access to the share, but if you're navigating to the path \pc\drive$\ then it may be relying on file system security and not the security on the folder share itself. Make sense?

Related

Access to the path is denied in ASP.Net

I have an ASP.Net application running in IIS which creates a file in a specified location using CsvWriter. If I use the full UNC path I get error that Access to the path is denied, however if I use Drive letter it works fine. What is puzzling me is that it does work with UNC path in development environment.
This code which creates the file
using (var writer = new StreamWriter(fileName))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.WriteField("Foo");
csv.WriteField("Bar");
csv.NextRecord();
}
Following advice various posts such as Access to the path is denied and IIS7 Permissions Overview - ApplicationPoolIdentity and MS Documentation: Application Pool Identities. I was initially convinced my problem was security related. This was supported by the fact that the application would run perfectly in development environment (IIS Express) which uses my user credentials but not under IIS which uses Application Pool Identity. I gave MyApplicationPoolIdentity full access to the specific directory to no avail.
However, I discovered that if I use the drive letter (C:\myDirectory\mySubDirectory\myFile.csv) as opposed to the UNC path (\\myServer\myDirectory\mySubDirectory\myFile.csv) in production the file is created perfectly. Even though I have the application working my concern is that I may have some configuration issue with IIS or my server which may bite me later. So my question is what would cause the create file/write to fail using UNC path and not using Drive letter?
I am using Windows Server 2016.
Thanks
Tony
I think it is caused by permission issues. First, did you get any related error messages? Or you can try the following methods:
1.you can use Process Monitor to see which account is being used to access the share and what permission are required.
2.Check to ensure the account that IIS is running under has needed rights to the troublesome UNC.

Why do I get a UnauthorizedAccessException when reading files from a network share?

With this code:
DirectoryInfo info = new DirectoryInfo("\\s01\sharedfolder\folder");
FileInfo[] files = info.GetFiles().OrderBy(p => p.CreationTime).ToArray();
I get a System.UnauthorizedAccessException:
Access to the path '\s01sharedfolder\folder' is denied.
System.UnauthorizedAccessException: Access to the path '\s01\sharedfolder\folder' is denied.
On 's01' I have given Everyone full control to the sharedfolder. I also have set the owner of that shared folder to everyone.
The identity of the application pool of the .net app is set to LocalSystem and I have also tried to use the local administrator as the identity.
No matter what I try, I keep getting this exception. What do I need to do to fix this?
EDIT:
I have also tried to create a symbolic link, but this gave the same exception
LocalSystem will only be valid on your local machine. If the share is on another computer then you will get this exception.
It might be worth setting up a dedicated account for your site to run under (IIS Pool) and granting the required permissions to resources on the network (ala your file share and database if using Windows Authentication) and local to your site (ala local file system).
Granted when running as System you get admin rights to that local machine only (I think).
It might be the expected behavior for using File.OpenRead rather than a permission issue. File.OpenRead tries to open a file with that name in the local machine. Most of the time, the files are in the server, not in the local (client) machines. Therefore, it fails no matter what permissions are assigned to the folder. Try InputStream instead. Example:
String fileToUpload = FileUpload2.PostedFile.FileName;
long contentLength = FileUpload2.PostedFile.InputStream.Length;
byte[] buffer = new byte[contentLength];
FileUpload2.PostedFile.InputStream.Seek(0, SeekOrigin.Begin);
FileUpload2.PostedFile.InputStream.Read(buffer, 0, Convert.ToInt32(contentLength));
Stream stream = new MemoryStream(buffer);
Source: System.UnauthorizedAccessException occurred in mscorlib.dll

Permission error when uploading files

I have the following code:
var saveFolder = Path.Combine(Properties.Settings.Default.DropBoxFolder, guid.ToString("N"));
// Create folder, if it does not exist (for the first attachment, it shouldn't exist)
if (!Directory.Exists(saveFolder))
{
Directory.CreateDirectory(saveFolder);
}
var saveFilePath = Path.Combine(saveFolder, file.FileName);
file.SaveAs(saveFilePath);
I'm using GUIDs to generate folders for uploads on my IIS server. The .NET web application is configured to impersonate the user. I granted modify permissions to the target folder (it is a local path on the web server) for Domain Users, Local Service and Everyone, but some users still can't upload files. I can and other people on my team can.
The weird part is that the exception says this:
Could not find a part of the path 'C:\Users\USERID\Desktop\FILENAME'
That path is the path to the file the user selected to upload (their local file path). I feel it is safe to say that the user has permission to his own file on his own desktop. I don't use user impersonation much, so I am wondering what I missed in my configuration or permissions. Any suggestions for debugging this issue? Thanks!
Note: the CreateDirectory method works just fine, even when the exception is thrown. I would have thought that if the user didn't have permission the directory creation would have failed first.

how to grant write permissions to an web api application in IIS?

I simply have a web api application on IIS server that simply writes to text file on C:\FileStorage\test.txt however when I call this webservice I get the internal 500 error, after expanding the error,I get the following error, how do I grant write access to this web service on IIS server?
"ExceptionMessage": "Access to the path 'C:\\FileStorage\\test.txt' is denied.",
"ExceptionType": "System.UnauthorizedAccessException",
"StackTrace": " at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)\r\n at
Grant permissions for that folder to the application pool. So you'd go to the C:\FileStorage folder in Windows and edit permissions, and add IIS APPPOOL\appPoolNameHere as a user, then give it full permissions.
Hope that helps.
EDIT
Step by Step Instructions...
-Open Windows Explorer
-Browse to your folder
-Right click the folder and go to Properties
-On the Security tab click Edit
-Click Add
-Under Locations, make sure it is pointing at your local machine, not a domain
-For the object name, enter below but replace MyAppPool with the name of your application pool...
IIS APPPOOL\MyAppPool
-Set the permissions to Full, or just add Write, or whatever you need.
or you can repalce APPPOOL to the name of your server or computer and with the IIS_ISURS.
example:
yourserver\IIS_IUSRS
See this Screen Shot

Unable to read the files from shared folder

I am trying to access files from the shared folder(ftp location) in Asp.net application. It is working fine from visual studio. When i deploy same in IIS 7 , i am getting the following error
"Logon failure: the user has not been granted the requested logon type at this computer."
Stack Trace:
[IOException: Logon failure: the user has not been granted the
requested logon type at this computer. ]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
+9723522 System.IO.FileSystemEnumerableIterator1.CommonInit() +245 System.IO.FileSystemEnumerableIterator1..ctor(String path, String
originalUserPath, String searchPattern, SearchOption searchOption,
SearchResultHandler`1 resultHandler) +556
System.IO.DirectoryInfo.InternalGetFiles(String searchPattern,
SearchOption searchOption) +64 System.IO.DirectoryInfo.GetFiles()
+14
......
My application pool is running in NETWORKSERVICE mode
To which user in IIS i need to give the permission for accessing this folder? is it IUSER or NT AUTHORITY\NETWORK SERVICE ? How can i identify the current running user in IIS?
The reason the connection is refused it most likely a Group Policy which disallows access to that service by the user running the IIS service.
I would not want to give any of those system users permission to access a network resource. Other computers could potentially connect as well.
Instead - make your program authenticate with a guest account or another account which you create and give the appropriate permissions.
I would say that it would be a more secure approach.
You may be trying to log on interactively to a computer you can only access over a network, or vice versa.
Change your logon location. Try to log on either locally (interactively) or remotely (over the network), as appropriate. You may want to ask the person who administers computer security to change the security database so you can log on either locally or remotely.
To debug - look at Environment.UserName at the moment of exception. It will be either user that initiated request OR anonymous user.
To fix: if local files - granting permissions may be ok. If remote and using user's impersonated account - need to impersonate with another account that have permissions on remote machine as you can't use already impersonating account to access remote resource ("NTLM one hop").
Note: make sure you review security requirements when allowing access to files.

Categories

Resources