aspnet / AspNetKatana

Microsoft's OWIN implementation, the Katana project
Apache License 2.0
963 stars 332 forks source link

Thread.CurrentPrincipal is sometimes empty (since upgrade to 4.1 library) #388

Closed dbarrett84 closed 3 years ago

dbarrett84 commented 3 years ago

Hi,

I have recently upgraded our OWIN packages to version 4.1.1 from 2.1.0.

We have a lot of usages of Thread.CurrentPrincipal to check the Identity or Claims. This is set in the OWIN pipeline like so:

    app.UseStageMarker(PipelineStage.Authorize);

     app.Use((context, next) =>
     {
        var user = HttpContext.Current.Request.GetOwinContext().Authentication.User;
        if (typeof(ClaimsPrincipal) == user.GetType() && !Thread.CurrentPrincipal.Identity.IsAuthenticated)
        {
           Thread.CurrentPrincipal = user;
        }
        return next.Invoke();
     });

     app.UseStageMarker(PipelineStage.PostAuthorize);

And when I debug I can see that user is valid when setting the CurrentPrincipal

But when access it in an API the Thread.CurrentPrincipal.Idenity is empty [see image] and so are the claims, even though HttpContext.Current.User is populated with correct values: image

The other unusual thing is it only happens when using Basic Authentication.

We're only getting this issue while trying to upgrade to 4.1.1, but I haven't seen anything in the change logs to suggest this should be affected.

Any help would be appreciated

Tratcher commented 3 years ago

With the async nature of these libraries, relying on thread specific state is not a good idea. You'd be better off using HttpContext.Current which is more actively managed to flow across threads. Your example already shows that working better.

ghost commented 3 years ago

This issue has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for 4 days. It will be closed if no further activity occurs within 3 days of this comment. If it is closed, feel free to comment when you are able to provide the additional information and we will re-investigate.

See our Issue Management Policies for more information.