Cannot write on a mapped drive using impersonation

那年仲夏 提交于 2019-12-02 09:25:08

问题


Basically I'm running the same problem as this post Accessing mapped drives when impersonating in ASP.NET

I'm working on a legacy website and I need to allow the admins to change the site's logo, banners, etc, from an image file on their desktops to a mapped drive on the server.

So, their website is using impersonation whenever it needs to save on the drive, and it's working just fine; however I can't manage to make it work on their test environment nor in my test environment.

¿Any ideas? I've double checked user and password (the code doesn't specify domain) and that's not the issue.

Here's an excerpt from the code that handles impersonation:

public bool ImpersonateUser(String user, String password, String domain)
{
    WindowsIdentity tempWindowsIdentity;
    IntPtr token = IntPtr.Zero;
    IntPtr tokenDuplicate = IntPtr.Zero;

    if (RevertToSelf())
    {
        if (LogonUserA(user, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
        {
            if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
            {
                tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                impersonationContext = tempWindowsIdentity.Impersonate();
                if (impersonationContext != null)
                {
                    CloseHandle(token);
                    CloseHandle(tokenDuplicate);
                    return true;
                }
            }
        }
    }
    //... rest of the code

And a -sanitized- test:

if (impUtility.ImpersonateUser("user", "password", string.Empty))
{
    fu.SaveAs(@"C:\Images\" + imgName);
}

回答1:


I couldn't get that to work either.

Then I realized that even if I could implement it, there is an easier way. What I did was share the folder on the target machine, and give only read/write permissions to the users that would be using my application.

//Impersonate user to save file on server
WindowsIdentity wi = (WindowsIdentity)User.Identity;
WindowsImpersonationContext wic = null;

try
{
    wic = wi.Impersonate();
    if (wi.IsAuthenticated)
        asyncFileUpload.SaveAs(location);
}
catch (Exception ex)
{
    //Log Error or notify here
    success = false;
}
finally
{
    if (wic != null)
        wic.Undo();
}

I created an AD group for the users, and give read/write permissions for those users on the hidden shared drive. This makes it easier to maintain, since I don't have to create mapped drives for each user.



来源:https://stackoverflow.com/questions/3150122/cannot-write-on-a-mapped-drive-using-impersonation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!