简体   繁体   English

.NET 核心 Web API HttpContext.User.Claims 和 HttpContext.User.Identity 在控制器中总是 null

[英].NET Core Web API HttpContext.User.Claims and HttpContext.User.Identity are always null in Controllers

I am using an ASP.NET Core Web API for the back-end and using JWT token in httpClient's header of a Blazor WASM client (I don't store JWT tokens in a cookie).我在后端使用 ASP.NET Core Web API,并在 Blazor WASM 客户端的 httpClient 的 header 中使用 JWT 令牌(我不将 88468485588 存储在 cookie 中)。

The problem is that although the user is logged in and the authentication and authorization works with no problems, but in every controller (inherited from ControllerBase ) always:问题是虽然用户已登录并且身份验证和授权没有问题,但在每个 controller (继承自ControllerBase )中总是:

  • HttpContext.User.Identity.IsAuthenticated is false HttpContext.User.Identity.IsAuthenticated为假
  • HttpContext.User.Identity.Name is null HttpContext.User.Identity.Name是 null
  • HttpContext.User.Claims is null HttpContext.User.Claims是 null

But the request has the JWT token ( Request.Headers["Authorization"][0] is equal to Bearer eyJhbGciOiJIUzI1... ) and [Authorize] attribute works correctly.但是请求具有 JWT 令牌( Request.Headers["Authorization"][0]等于Bearer eyJhbGciOiJIUzI1... )并且[Authorize]属性工作正常。

This is how my startup.cs looks like:这是我的 startup.cs 的样子:

services.AddIdentity()
            
services.AddSingleton<IAuthorizationPolicyProvider, AuthorizeExPolicyProvider>();

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                              options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(Configuration["jwt:key"])),
                    ClockSkew = TimeSpan.Zero
                });

services.AddAuthorization(options =>
            {
            });

And I also called the middleware in the right order:我还按正确的顺序调用了中间件:

app.UseRouting();

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

app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

HttpContext.User is only set when you have authentication for the method enabled. HttpContext.User仅在启用方法身份验证时设置。

You can enable it by setting [Authorize] on your controller or action, or configure a global filter so all requests are authorized by default.您可以通过在您的 controller 或操作上设置[Authorize]来启用它,或者配置一个全局过滤器,以便默认授权所有请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM