Skip to content

Thread.CurrentPrincipal was useful - alternatives? #27608

Answered by kevinchalet
Plasma asked this question in Q&A
Discussion options

You must be logged in to vote

FWIW, Thread.CurrentPrincipal is backed by an AsyncLocal<IPrincipal> instance on .NET Core, so it will work nicely with async/await and context switching: https://source.dot.net/#System.Private.CoreLib/Thread.cs,137

With that in mind, you can write a middleware registered after the authentication middleware that sets it for the rest of the request. You could also use ClaimsPrincipal.Current and set ClaimsPrincipal.ClaimsPrincipalSelector to resolve it from wherever you want.

Something like:

app.UseAuthentication();
app.UseAuthorization();

app.Use(next => async context =>
{
    var principal = Thread.CurrentPrincipal;

    // Use the principal resolved from the default authentication sche…

Replies: 3 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@rajatchanana7
Comment options

Answer selected by davidfowl
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
5 participants