异步设置 Thread.CurrentPrincipal ? [英] Set Thread.CurrentPrincipal Asynchronously?

查看:20
本文介绍了异步设置 Thread.CurrentPrincipal ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 ASP.NET WebAPI,在身份验证期间,设置 Thread.CurrentPrincipal 以便控制器稍后可以使用 ApiController.User 属性.

Using ASP.NET WebAPI, during authentication, Thread.CurrentPrincipal is set so that controllers can later use the ApiController.User property.

如果该身份验证步骤变得异步(以咨询另一个系统),CurrentPrincipal 的任何变化都会丢失(当调用者的 await 恢复同步上下文时).

If that authentication step becomes asynchronous (to consult another system), any mutation of CurrentPrincipal is lost (when the caller's await restores the synchronization context).

这是一个非常简化的示例(在实际代码中,身份验证发生在操作过滤器中):

Here's a very simplified example (in the real code, authentication happens in an action filter):

using System.Diagnostics;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;

public class ExampleAsyncController : System.Web.Http.ApiController
{
    public async Task GetAsync()
    {
        await AuthenticateAsync();

        // The await above saved/restored the current synchronization
        // context, thus undoing the assignment in AuthenticateAsync(). 
        Debug.Assert(User is GenericPrincipal);
    }

    private static async Task AuthenticateAsync()
    {
        // Save the current HttpContext because it's null after await.
        var currentHttpContext = System.Web.HttpContext.Current;

        // Asynchronously determine identity.
        await Task.Delay(1000);
        var identity = new GenericIdentity("<name>");

        var roles = new string[] { };
        Thread.CurrentPrincipal = new GenericPrincipal(identity, roles);
        currentHttpContext.User = Thread.CurrentPrincipal;
    }
}

如何在异步函数中设置 Thread.CurrentPrincipal 以便调用者的 await 在恢复同步上下文时不会丢弃该突变?

How do you set Thread.CurrentPrincipal in an async function such that the caller's await doesn't discard that mutation when restoring the synchronization context?

推荐答案

您还必须设置 HttpContext.Current.User.请参阅此答案这篇博文 了解更多信息.

You have to set HttpContext.Current.User as well. See this answer and this blog post for more info.

更新:还要确保您在 .NET 4.5 上运行并将 UserTaskFriendlySynchronizationContext 设置为 true.

Update: Also ensure you are running on .NET 4.5 and have UserTaskFriendlySynchronizationContext set to true.

这篇关于异步设置 Thread.CurrentPrincipal ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆