任务/不同线程上的WindowsIdentity.RunImpersonated/SafeAccessTokenHandle

问题描述 投票:0回答:1

在 .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 将不起作用?我应该吗

  1. 为此任务的请求创建一个新令牌,而不是使用字段?
  2. 在令牌线程上执行
    Task
  3. 不使用任务(我正在使用
    File.WriteAllBytesAsync
    ,可以用
    File.WriteAllBytes
    替换)?
c# multithreading asynchronous async-await task
1个回答
0
投票

如果您想运行异步代码,您应该使用 WindowsIdentity.RunImpersonatedAsync 方法

© www.soinside.com 2019 - 2024. All rights reserved.