I have a website that is using Windows authentication that calls an API. The API has the Authorize
attribute:
[Authorize(Roles = @"myrole.local\role")]
The API then makes a call to a method in my business layer that does this:
string [] directories = Directory.GetDirectories("\\\\server\\folder\\folder2");
When running locally this works as intended. When my IT ops guy checks the audit logs, he sees that my login has accessed that folder.
Now when I deploy my website to our development environment, it no longer works (we get an "access denied" error for that folder). So we looked into it and found that the user
trying to access the folder was our server (something like server$
) tried to access folder and failed.
So my question is: how do I access the folder with the current user that is logged in? I have looked this up here on Stack Overflow and I see impersonation comes up a lot. I have tried this example with no luck:
public static List<DirectoryName> GetDirectories(IPrincipal user)
{
string[] directories;
using (WindowsImpersonationContext impersonationContext = ((WindowsIdentity)user.Identity).Impersonate())
{
//Insert your code that runs under the security context of the authenticating user here.
directories = Directory.GetDirectories("\\\\server\\folder\\");
}
}
I am still denied access.
I have the user that is logged in though, so I know I can 'see' them, but the folder I am trying to access says it's the server.
Does anyone know how to get around this? Am I missing something?
P.S. I have created the website with IIS and have set both the API and website to use windows authentication. (anon = false;
); but still it says the server is trying to access the folder.
P.P.S. In the web.config
for the API, I have these tags as well:
<system.web>
<!-- ... -->
<authentication mode="Windows"/>
<authorization>
<allow roles="group.local\group" />
</authorization>
</system.web>
Edit: So we were able to access the folder path with the logged in user but only when going to the website on the server.
If we go to the website off our dev server we will then get an access denied error. Also there is no audit line when this fails.
Hopefully this edit provides more insight.