1

我正在尝试将我的标准 WebApi 应用程序移至 OWIN,但在身份和 $batch 请求方面存在问题。

我目前有一个DelegatingHandler检测并分配身份的SendAsync

// Detect bearer token and build the identity above.
IOwinContext owinContext = request.GetOwinContext();
owinContext.Authentication.User = new ClaimsPrincipal(identity);

对于正常的请求,这会一直持续到ODataController.User. 但是,在$batch请求时,属性会返回到未经身份验证的ClaimsIdentity.

甚至GetOwinContext返回一个IOwinContext没有任何用户的。我假设它为每个批次部分创建了一个新的上下文,但我看不到任何找到原始上下文的方法。

任何帮助都会很棒!

4

3 回答 3

1

在您的SendAsync方法中尝试:

request.GetRequestContext().Principal = new ClaimsPrincipal(identity);

这将同时分配Thread.CurrentPrincipal当前的 OWIN 上下文(检查此链接)。我不是 100% 确定,但我的猜测是 Principal 没有在当前线程中设置,因为 OData 在不同的线程中执行 $batch 子请求,并且 OWIN 上下文丢失了。

另一种选择是在Configuration方法中从 OWIN 中间件分配标识,而不是在DelegatingHandler. 这在此答案中进行了解释:https ://stackoverflow.com/a/21420794/4067893 ,这也与您的问题有关。

希望能帮助到你。

于 2016-06-28T12:46:32.390 回答
1

目前我找到了解决方法。如果有人找到更好的东西,我很想听听。

在我的DelegatingHandler中,我将身份存储在 OwinContext 环境中:

owinContext.Set<ClaimsIdentity>("customdata:identity", principal);

然后我创建了一个自定义AuthorizeAttribute,它将当前身份拉出并分配给当前用户。

IOwinContext context = actionContext.Request.GetOwinContext();
owinContext.Authentication.User = context.Get<ClaimsIdentity>("customdata:identity");
actionContext.RequestContext.Principal = owinContext.Authentication.User;
于 2016-06-30T11:39:28.797 回答
0

批处理的子请求在单独的线程中执行,并在这些请求中失去身份验证主体。

在你的DelegatingHandler.

var principal = new ClaimsPrincipal(identity);

System.Threading.Thread.CurrentPrincipal = principal;
if (System.Web.HttpContext.Current != null) {
    System.Web.HttpContext.Current.User = principal;
}

// Detect bearer token and build the identity above.
IOwinContext owinContext = request.GetOwinContext();
owinContext.Authentication.User = principal;
于 2016-06-28T12:47:22.933 回答