Dheeraj Kumar
Dheeraj Kumar

Reputation: 4175

How to get current User/ClaimsPrincipal in Middleware .Net Core Web API

I need to access Current User's claims in Middleware before request goes any Controllers.

On login I have set claims like this.

new Claim(ClaimTypes.NameIdentifier, user.ID.ToString());

//...

public async Task InvokeAsync(HttpContext httpContext)
{
    var claim = httpContext.User.FindFirst(ClaimTypes.NameIdentifier);
}

It returns null.

I know that we can access this using ControllerBase.User property in Controllers (which I am able to get), But I need to access it in Middleware.

Is there any way to achieve this?

Am I doing something wrong?

Upvotes: 7

Views: 5984

Answers (1)

Nkosi
Nkosi

Reputation: 247088

The reason you can access this using ControllerBase.User property in Controllers is because it happens later in the pipeline well after the User has been set.

This depends on middleware registration order.

The order that middleware components are added in the Startup.Configure method defines the order in which the middleware components are invoked on requests and the reverse order for the response. The order is critical for security, performance, and functionality.

The User is set by the authentication middleware(s) so make sure your custom middleware that depend on having User is registered after the authentication middleware(s)

//...

app.UseAuthentication();
app.UseAuthorization();
// app.UseSession();

app.AddCustomMiddleware();

//...

Reference ASP.NET Core Middleware

Upvotes: 14

Related Questions