Search code examples
asp.net-web-apiodataowinowin-middleware

OWIN losing Identity on OData $batch requests


I'm trying to move my standard WebApi app over to OWIN, but having a problem with identities and $batch requests.

I currently have a DelegatingHandler that detects and assigns the identity in SendAsync:

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

And for normal requests, this carries on through to the ODataController.User. However on $batch requests the property returns to an unauthenticated ClaimsIdentity.

Even GetOwinContext returns an IOwinContext without any User. I assume it has created a new context for each batch part, but I cannot see any way of finding the original context.

Any help would be great!


Solution

  • Currently I've found a work around. If anyone finds something better I'd love to hear it.

    In my DelegatingHandler, I have stored the identity in the OwinContext environment:

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

    Then I created a custom AuthorizeAttribute which pulls the current identity out and assigns to the current User.

    IOwinContext context = actionContext.Request.GetOwinContext();
    owinContext.Authentication.User = context.Get<ClaimsIdentity>("customdata:identity");
    actionContext.RequestContext.Principal = owinContext.Authentication.User;