Search code examples
c#impersonation

Impersonating user for local file access in C#


The situation I'm trying to address is this: I'm writing an application which multiple users will have access to. Access is restricted based on Windows permissions for folders - users will be granted access to the folder containing the application if needed.

For better or worse, the application stores its data in files on the same network as the application. I don't want users to be able to edit the data directly, so I plan to restrict access to the data files.

The approach I've been trying to use is then to have a 'service user' which does have read/write access to the data, and to use impersonation within the application to 'login' as the service user, perform required read/write, and return to the original user.

I've had a few different attempts at this without luck. Perhaps the simplest/most promising is based on Mark Johnson's answer here:

How do you do Impersonation in .NET?

I use it as follows:

            using (new Impersonation(serviceAccount.Domain, serviceAccount.UserName, serviceAccount.Password))
            {
                DoImport(app);
            }

where 'DoImport(app)' performs the reading of the data.

However, this gives an error 'Access to the path '...' is denied'. I'm trying to run this locally (the path is C:...) where I've restricted access to the path for the user I'm logged into but the user I'm trying to impersonate with has access.

Is there something I'm doing wrong here? Is there a better way to achieve what I'm after?

Thanks,

Andrew


Solution

  • The code at the below link seems to do what I'm after:

    http://www.codeproject.com/Articles/10090/A-small-C-Class-for-impersonating-a-User

    I think the token duplication is the important part, but I'm not exactly sure why.

    I did have a further issue doing this - any assemblies that needed to be loaded for the 'DoImport(...)' function couldn't be loaded after the impersonation, access was denied for some reason (sorry for the vagueness, I didn't have time to look into this). Ensuring they're loaded before doing the impersonation, either through some dummy function calls or code to force load (see e.g. Is there a way to force all referenced assemblies to be loaded into the app domain?) did the trick.