Impersonation in Asp.net for Upload a file - c#

Please consider this scenario:
I have a web site that host behind IIS 7.0 . Almost every IIS setting are defaulr settings. I have a folder for upload files that ASP.Net user had write access to it.currently IIS manager cancel this write access and he want to add a local user in Windows Server that this user can has write access to that folder. Now my question is how I can Impersonate user in asp.net and if this method is secure? I want all the request execute on server according to default IIS user but I want just impersonate for upload a file.
thanks

What you need is partial impersonation. you don't need all request to be impersonated but only a few call should be impersonated. i think you must have a look at this article.
http://support.microsoft.com/kb/306158
this is how it impersonate a piece of code under logged in user's credentials while rest of the call will be processed using default app Pool identity
System.Security.Principal.WindowsImpersonationContext impersonationContext;
impersonationContext =
((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();
//Insert your code that runs under the security context of the authenticating user here.
impersonationContext.Undo();

Related

Letting .json files be written too - .NET MVC

I am getting error's saying
Exception Details: System.UnauthorizedAccessException: Access to the
path 'E:\web\aawebapp\Content\events\events.json' is denied.
ASP.NET is not authorized to access the requested resource. Consider
granting access rights to the resource to the ASP.NET request
identity. ASP.NET has a base process identity (typically
{MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, and
the configured application pool identity on IIS 7.5) that is used if
the application is not impersonating. If the application is
impersonating via , the identity will be
the anonymous user (typically IUSR_MACHINENAME) or the authenticated
request user.
To grant ASP.NET access to a file, right-click the file in File
Explorer, choose "Properties" and select the Security tab. Click "Add"
to add the appropriate user or group. Highlight the ASP.NET account,
and check the boxes for the desired access.
Where this happens is in the Controller when I try to do the following.
string eventspathway =
HostingEnvironment.MapPath(#"~/Content/events/events.json");
System.IO.File.WriteAllText(eventspathway, newtext);
When I am running on localhost/debug this works fine, but does not work when webdeployed and thus spews out all the errors above.
What's hard to understand here? That exception means exactly what it says.
Your web app runs in an IIS worker process (w3wp.exe — "world-wide web worker process", get it?) called an app pool (application pool). That process runs under an account. Any process running under those credentials won't be able to read (or write) to a path for which it lacks the prerequisite permissions.
You (or your system adminstrators) need to grant the app pool identity under which your app is running sufficient permissions to do what it needs to do. Or you need to find a place to park your data where your app pool identity has sufficient permissions.
Another alternative — not recommended for a production system! — would be to run the app pool under the local system account.
For more information, see
http://www.iis.net/learn/manage/configuring-security/application-pool-identities
How to set up IIS 7 application pool identity correctly?
http://technet.microsoft.com/en-us/library/cc771170(v=ws.10).aspx

Difference in ASP.Net impersonation methods

In this MSDN article on "How to implement impersonation in an ASP.NET application" they list 4 different ways to change the account that's used to execute the web request. Unfortunately, it doesn't describe the differences between these alternatives.
I'm trying to impersonate the IIS authenticated user to copy some files off their local machine. It works when I use the WIN32 api LogonUserA and impersonate a specific user. But I need the webapp to work with many users (I don't have an account that can access everyone's files).
I thought simply setting Impersonate = "true" and configuring IIS should work but something is different. When I check Environment.UserName it appears to be impersonating the correct account but I am getting "Access is denied" errors.
Anyone know the difference between these impersonation methods? Is it possible to impersonate the IIS authenticated user and then do some file operations with it?
Update: From the feedback I've been getting I need to be more clear about what I'm facing.
Environment setup:
IIS: disable anonymous authentication, enable integrated windows authentication
ASP.Net's web.config: authentication mode = "windows", impersonate = true, deny anonymous users
Suppose I'm accessing the page as "userA":
Scenario 1: impersonate the IIS Authenticated user
try{
File.Copy(srcFile, destFile); // Access Denied even though userA has access to srcFile.
} catch(Exception ex) {
...
}
Scenario 2: impersonate userA with LogonUser
try{
// Impersonater is a wrapper around the WIN32 LogonUser API
using(Impersonater imp = new Impersonator("domain", "userA", "pwd"))
{
File.Copy(srcFile, destFile); // Works
}
} catch(Exception ex) {
...
}
In both cases, I'm impersonating "userA".
Q: Anyone know the difference between these impersonation methods?
A: First some background on how IIS handles request.
There is a specific system user called IUSR_computername (default in IIS6) which the IIS-server uses to handle file access. And there is a process running on the IIS server called Aspnet_wp.exe which runs under an account called ASPNET or NetworkService.
So when a request is made to the server, the IIS reacts and if the request is to a ASP.NET application it passes the request to that process.
This means that if the IIS-server is setup to use the IUSR_computername (anonymous) access method. The server will use that account to process the request, and if it sees that it is an ASP.NET application it will transfer the request to the ASP.NET process.
By default impersonation is disabled, this means that the request will run under the ASPNET or NetworkService account when the ASP.NET process handles the request.
Now to the difference between the impersonation methods:
Impersonate the IIS authenticated account or user
Uses an account that the IIS is setup to use. Usually IUSR_computername.
Usage: <identity impersonate="true" />
Impersonation enabled for a specific identity
Uses a specific account that is specified.
Usage: <identity impersonate="true" userName="accountname" password="password" />
The third option is the default state, which is to disable impersonation.
Q: Is it possible to impersonate the IIS authenticated user and then do some file operations with it?
A: Depends on the priviliges of the IIS authenticated user. If the account has permission to manipulate files (NTFS permission in Windows), the answer would be yes.
Read more here:
IIS Authentication
ASP.NET Authentication
I believe you've run into the "double hop" issue described here. Basically, the connection between the client and IIS is one hop, the connection between IIS and the network share is the second one and with impersonation double hops are not allowed by default. That means in your first example the user should be able to access resources local to the IIS machine but not remote ones.
When the credentials are entered on the IIS programmatically, there's no second hop. That's the difference you're looking for.
To support your requirements, you need to implement delegation rather than impersonation. Please have a look at MSDN for more info.

Access to the path is denied

I am currently creating a folder and writing a file to the folder that need to be create on a file server that we have. When i do a localhost test, it work perfectly but when i access the website from outside the localhost and from another pc. It said that
System.UnauthorizedAccessException: Access to the path 'My File Server
URL' is denied
ASP.NET is not authorized to access the requested resource. Consider
granting access rights to the resource to the ASP.NET request
identity. ASP.NET has a base process identity (typically
{MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6) that is used if
the application is not impersonating. If the application is
impersonating via , the identity will be
the anonymous user (typically IUSR_MACHINENAME) or the authenticated
request user.
To grant ASP.NET access to a file, right-click the file in Explorer,
choose "Properties" and select the Security tab. Click "Add" to add
the appropriate user or group. Highlight the ASP.NET account, and
check the boxes for the desired access.
But the thing is that i have already set the identity impersonate="true" in the web.config and it still didn't work. My web server is running on Winder Server 2003 and IIS 6
Any advice and help will be deeply appreciated
Thanks
Brandon
You need to grant write, modify permission to the Users group for that file/folder.
Check your IIS Authentication setting and make sure that Anonymous authentication is enabled.
Hi Guys i manage to find the solution to it
If u are creating a folder, using this code before file or folder creation
WindowsImpersonationContext ctx = WindowsIdentity.Impersonate(IntPtr.Zero);
// Insert the create code here
ctx.Undo();
Well i do not know if this is the best solution. if anyone know the downside or implication of this code please share and comment.
no harm knowing more

Facing problem with ASP.NET hosted in IIS and Windows Authentication

I have an asp.net website that is hosted in IIS 7.5
The website has to use windows authentication. The users are added to an AD group. The AD user group has full control on the web folder in which the website is published. Server/IIS_IUSRS has full control on the web folder too.
The data that the website is required to use is stored in another server. The AD group has Full control on the folder in which the data is stored.
I am using Classic mode because Integrated breaks it.
What should be the website authentication and APP Pool settings?
Personally I have become a fan of setting the app pool identity to an AD service account and then allowing the app to access the database and other resources using those credentials. No need to pass the credentials on the connection string or try to impersonate the users (EDIT: Should note that this applies to resources which use windows integrated security). Also no need to try to give the users direct access to the datastore or other resources, just the app credentials need to have access. It is a bit more trouble to set up initially but much easier to manage in the long run.
Here is the checklist I send to our server group whenever I ask them to set up a new site for me: (note this is based on Win Serv2003 and IIS 6, things may be different in the newer versions.)
Set up a separate App Pool for the
application
Configure the App pool to run as the
service account
Add the service account to the
IIS_WPG group on the server
Make sure the IIS_WPG group has Read,
Read & Execute, and List Folder
Contents permissions for the website
directory and Read and List Folder
Contents to the C:\Windows\Temp
folder (or equivalent).
Grant User Rights “Adjust Memory
Quotas for a Process”, “Replace a
Process Level Token”, and “Log On as
Service” to the service account
Don't mix up IIS autorization and ASP.NET autorization :
IIS autorization
IP/DNS Address Restrictions
Web Permissions (Read, Write, Script Source Access...)
NTFS Permissions (non ASP.NET ISAPI extension only : .htm, .jpg...)
ASP.NET autorization
URL Authorization (<authorization> element)
File Authorization (ASP.NET ISAPI extension only : .aspx, .ascx...)
Principal Permissions (Demands)
.NET Roles
Restrict access to your web :
Uncheck anonymous access
Configure NTFS rights
Give access to your data folder, few solutions :
Use a service account for your application pool, allow it on your folder and manage access control in your application
Use default IIS 7 ASP.NET account, and impersonate the user locally in your code when accessing your data folder
System.Security.Principal.WindowsImpersonationContext
impersonationContext;
impersonationContext =
((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();
//Insert your code that runs under the
security context of the authenticating
user here.
impersonationContext.Undo();
Activate impersonation globally (<identity impersonate="true"/>) ; dont like this one

Service unavailable message in IIS

I have created a sample ASP.NET website and hosted it in IIS 6.0 . It is working fine , if the identity of the defalut app pool is "local system". But when i changed the identity with some other configurable user id then it is showing as "Service Unavailable".
The following message is found in the event viewver.
"The identity of application pool 'DefaultAppPool' is invalid, so the World Wide Web Publishing Service can not create a worker process to serve the application pool. Therefore, the application pool has been disabled."
Either the credentials provided for the user is not valid, or the user does not have the needed permissions.
I believe there is a security group on the machine called IIS_WPG that is created when Asp.net is installed, add the user to this group, it should give them the needed permissions.
Message is self-explanatory. The selected user id isn't valid - probably due to insufficient privaledges to run the service.
The user identity you use needs to have fairly significant rights to operate. At a minimum the user needs to have read/execute permission on the root directory of the folder. This user should also have read/write/execute permission on the Temporary Asp.Net Files folder located within the %SystemRoot%/Microsoft.Net/Framework/ folder.
FYI,
In a development environment you can use the default app pool to create your web applications.
In production environment you want to use lusrmgr.msc (Server 2008/R2/7 Ultimate and Pro) to create new users (and their credentials) on the machine and assign the users to the right group (IIS_IUSRS).
Also once you have created the user, you will want to give it access to your data source back-end (if sql is running on the same machine and using windows authentication to access SQL).
Check Application Pools which assign Site on IIS, probably it is stopped.

Categories

Resources