Security, Thread.CurrentPrincipal, and ConfigureAwait(false)

后端 未结 1 1810
栀梦
栀梦 2021-02-08 15:27

Would using Thread.CurrentPrincipal\'s claims in a referenced library that uses ConfigureAwait(false) pose any problems or will the flowing of ExecutionContext\'s logical call c

1条回答
  •  再見小時候
    2021-02-08 16:15

    From my tests, it appears that Thread.CurrentPrincipal will flow correctly, even if you use ConfigureAwait(false). The following WebAPI code sets the principal and then blocks on an async call, forcing another thread to resume the async method. That other thread does inherit the correct principal.

    private async Task Async()
    {
        await Task.Delay(1000).ConfigureAwait(false);
        return "Thread " + Thread.CurrentThread.ManagedThreadId + ": " + Thread.CurrentPrincipal.Identity.Name + "\n";
    }
    
    public string Get(int id)
    {
        var user = new ClaimsPrincipal(new ClaimsIdentity(
            new[]
            {
                new Claim(ClaimTypes.Name, "Bob"),
            }
        ));
        HttpContext.Current.User = user;
        Thread.CurrentPrincipal = user;
    
        var ret = "Thread " + Thread.CurrentThread.ManagedThreadId + ": " + Thread.CurrentPrincipal.Identity.Name + "\n";
    
        ret += Async().Result;
    
        return ret;
    }
    

    When I run this code on a new instance of IISExpress, I get:

    "Thread 7: Bob\nThread 6: Bob\n"
    

    However, I should point out that using ConfigureAwait(false) to avoid deadlock is not recommended. This is especially true on ASP.NET. If at all possible, use ConfigureAwait(false) and also use async all the way. Note that WebAPI is a fully-async stack and you should be able to do this.

    0 讨论(0)
提交回复
热议问题