We have a web app that runs on our corporate intr.net. I get the following error when I try to access a.network path in my MVC controller:
Access to the path '\Server001\SharedFiles\CA' is denied.
The App is hosted on IIS and app pool is set to ApplicationPoolIdentity. I do not want to set it with an account that has access right to all the directories. I'd like each user to only access the folders they're allowed to. After some research I figured the only way is to programmatically impersonate the user when it's needed. To test this out, I created a New ASP.NET Core 6 MVC project with Authentication set to Windows(Also enabled Windows Authentication in IIS site). Then I added the following code to my controller:
public async Task<IActionResult> Index()
{
// The user used as Log On as for the Windows Service
var serviceUser = WindowsIdentity.GetCurrent();
// returns "IIS APPPOOL\MvcTest"
// The user to be impersonated
// COMPANYDOMAIN\MyName
var userToImpersonate = (WindowsIdentity)HttpContext.User.Identity;
await WindowsIdentity.RunImpersonatedAsync(userToImpersonate.AccessToken, async () =>
{
var ImpersonatedUser = WindowsIdentity.GetCurrent();
_logger.LogInformation(ImpersonatedUser.ImpersonationLevel.ToString());
// returns "impersonate"
_logger.LogInformation(ImpersonatedUser.Name);
// Here we are getting "COMPANYDOMAIN\MyName"
try
{
var files = Directory.GetFiles("\\\\Server001\\SharedFiles\\CA");
return View(files);
}
catch (Exception ex) { }
});
}
Although this shows that WindowsIdentity.GetCurrent().Name
has changed to my domain account(what I logged in as) but for some reason it is not accepting the impersonated user. I still get access denied error. Is this permission issues?
I am able to browse the "\Server001\SharedFiles" using my domain account(COMPANYDOMAIN\MyName), Also when I change the app pool identity to my domain account, the app still works.
If WindowsIdentity.GetCurrent().Name
shows the correct user, then your impersonation is likely working correctly.
File shares in Windows have two sets of permissions that define what a user can do:
Make sure that both the share permissions and the file system permissions allow the user access. It is possible for the file system permissions to allow someone full control, but the share permissions to deny them any access. In that case they could access and modify any files locally, but couldn't do anything through the share.
I would usually set the share permissions to Read/Write for Everyone and then use the file system permissions to restrict access.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.