我最近刚刚从事了一个非常相似的项目,我将文件保存到网络共享。两台计算机在同一个子网上,但不受域控制器控制,所以每台计算机都有自己的用户。
我在两台计算机上创建了一个具有相同用户名和密码的用户。然后我创建了一个网络共享并设置文件夹/共享权限以允许用户读写。
然后我创建了以下类来管理模拟:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using System.Text;
namespace MyProject.Business.Web
{
public class SecurityManager
{
#region DLL Imports
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
#endregion
public string Domain { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
private WindowsImpersonationContext m_CurrentImpersonationContext;
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public void StartImpersonation()
{
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
IntPtr tokenHandle = IntPtr.Zero;
IntPtr dupeTokenHandle = IntPtr.Zero;
// obtain a handle to an access token
bool wasLogonSuccessful = LogonUser(UserName, Domain, Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle);
if (!wasLogonSuccessful)
throw new Exception(String.Format("Logon failed with error number {0}", Marshal.GetLastWin32Error()));
// use the token handle to impersonate the user
WindowsIdentity newId = new WindowsIdentity(tokenHandle);
m_CurrentImpersonationContext = newId.Impersonate();
// free the tokens
if (tokenHandle != IntPtr.Zero)
CloseHandle(tokenHandle);
}
public void EndImpersonation()
{
m_CurrentImpersonationContext.Undo();
}
}
}
然后在 ASP.NET 页面中,我执行了以下操作:
SecurityManager sm = new SecurityManager();
sm.UserName = ConfigurationManager.AppSettings["UserFileShareUsername"];
sm.Password = ConfigurationManager.AppSettings["UserFileSharePassword"];
sm.StartImpersonation();
if (!Directory.Exists(folderPath)) Directory.CreateDirectory(folderPath);
File.Move(sourcePath, destinationPath);
sm.EndImpersonation();