开发者

Cannot write on a mapped drive using impersonation

开发者 https://www.devze.com 2023-01-05 01:43 出处:网络
Basically I\'m running the same problem as this post Accessing mapped drives when impersonating in ASP.NET

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, thei开发者_开发技巧r 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);
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消