[英]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.它返回 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.我知道我们可以使用 Controllers 中的 ControllerBase.User 属性访问它(我能够获得),但我需要在中间件中访问它。
Is there any way to achieve this?有什么办法可以做到这一点?
Am I doing something wrong?难道我做错了什么?
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.您可以使用ControllerBase.User
属性访问它的原因是,它会在设置User
之后的管道中稍后发生。
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.在Startup.Configure
方法中添加中间件组件的顺序定义了对请求调用中间件组件的顺序和响应的相反顺序。 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) User
由身份验证中间件设置,因此请确保在身份验证中间件之后注册依赖于User
的自定义中间件
//...
app.UseAuthentication();
app.UseAuthorization();
// app.UseSession();
app.AddCustomMiddleware();
//...
Reference ASP.NET Core Middleware参考ASP.NET 核心中间件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.