在 .NET 6 Web api 上,我创建了一个 AuthorizedUser,它使用
WindowsIdentity.RunImpersonated
执行方法。在本例中,该类由 FileReaderWriterClass 使用。
public class AuthorizedUser : IDisposable
{
private readonly SafeAccessTokenHandle safeAccessTokenHandle;
public AuthorizedUser(IConfiguration configuration)
{
string domain = configuration.GetValue<string>("AuthorizedUser:Domain");
string username = configuration.GetValue<string>("AuthorizedUser:Username");
string password = configuration.GetValue<string>("AuthorizedUser:Password");
safeAccessTokenHandle = SafeAccessTokenHandle(domain, username, password);
}
private static SafeAccessTokenHandle SafeAccessTokenHandle(string domain, string username, string password)
{
bool loginSucces = LogonUser(username, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, out SafeAccessTokenHandle safeAccessTokenHandle);
if (!loginSucces)
{
throw new Exception("Unsuccesful login at SafeAccessTokenHandle()");
}
return safeAccessTokenHandle;
}
public async Task Run(Task task)
{
await WindowsIdentity.RunImpersonated(safeAccessTokenHandle, () => task);
}
public TResult Run<TResult>(Func<TResult> function)
{
return WindowsIdentity.RunImpersonated(safeAccessTokenHandle, () => function());
}
public TResult Run<TArg1, TResult>(Func<TArg1, TResult> function, TArg1 arg1)
{
return WindowsIdentity.RunImpersonated(safeAccessTokenHandle, () => function(arg1));
}
}
最后两种方法似乎有效,第一个等待任务的方法无效。出现错误
对路径“\ different-server ile\path.json”的访问被拒绝。
文档指出
为 Windows 线程或进程访问令牌提供安全句柄。
这是否意味着,当执行
Task
时,它位于不同的 Thread
上,SafeAccessToken 将不起作用?我应该吗
Task
?File.WriteAllBytesAsync
,可以用 File.WriteAllBytes
替换)?如果您想运行异步代码,您应该使用 WindowsIdentity.RunImpersonatedAsync 方法