简体   繁体   中英

asp.net Access to the path XXX is denied

I've read tons of articles about this error.. also trying to set the folder's permission to the lowest:

在此处输入图片说明

But I still getting the error: Access to the path '\\servername\\shareFolder$\\folderNameWeWantToCreate' is denied.

I am trying to check whether a directory exists and try to create a directory if not using the below code:

string Folderpath = @"\\servername\shareFolder$\folderNameWeWantToCreate";
   if (!Directory.Exists(FolderPath))
        Directory.CreateDirectory(FolderPath);

The above code works well on local, but the error comes out when put on to the server.

Is there anything I did wrong??

There are two possible solutions:

Application Pool Identity

You need to create a new Application Pool in IIS that runs as the LocalSystem user and change your application to run on that AppPool. You need a high privilege user to do stuff on the local HD anyway and this'll save you a lot of permission slinging. In the future if you want to harden security you can always go back to a low privilege AppPool and just grant it permissions wherever it needs them.

Remote User Impersonation

If the above doesn't work, this is your recourse. It seems tricky but the code I'm running works perfectly on ASP.NET MVC 5 / .NET 4.5.1 so it should run fine on older versions too. Here's the code:

Helper classes:

public class ImpersonationHelper
{
    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
        int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public extern static bool CloseHandle(IntPtr handle);

    public const int LOGON32_PROVIDER_DEFAULT = 0;
    public const int LOGON32_PROVIDER_WINNT50 = 3;
    public const int LOGON32_PROVIDER_WINNT40 = 2;
    public const int LOGON32_PROVIDER_WINNT35 = 1;

    public const int LOGON32_LOGON_INTERACTIVE = 2;
    public const int LOGON32_LOGON_NETWORK = 3;
    public const int LOGON32_LOGON_NEW_CREDENTIALS = 9;

    public static SafeTokenHandle GetSafeTokenHandle(string userName, string password, string domain)
    {
        SafeTokenHandle safeTokenHandle;

        bool returnValue = LogonUser(userName, domain, password,
            LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50,
            out safeTokenHandle);

        if (false == returnValue)
        {
            int ret = Marshal.GetLastWin32Error();
            throw new System.ComponentModel.Win32Exception(ret);
        }

        return safeTokenHandle;
    }
}

public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
    private SafeTokenHandle()
        : base(true)
    {
    }

    [DllImport("kernel32.dll")]
    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
    [SuppressUnmanagedCodeSecurity]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CloseHandle(IntPtr handle);

    protected override bool ReleaseHandle()
    {
        return CloseHandle(handle);
    }
}

Main code:

var remoteUser = ConfigurationManager.AppSettings["RemoteUser"];
var remotePassword = ConfigurationManager.AppSettings["RemotePassword"];
var remoteDomain = ConfigurationManager.AppSettings["RemoteDomain"];
var safeTokenHandle = ImpersonationHelper.GetSafeTokenHandle(remoteUser, remotePassword, remoteDomain);

using (safeTokenHandle)
{
    using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
    {
        using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
        {
            // do stuff here the same as you would locally
        }
    }
 }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM