【问题标题】:.NET Core Web API HttpContext.User.Claims and HttpContext.User.Identity are always null in Controllers.NET Core Web API HttpContext.User.Claims 和 HttpContext.User.Identity 在控制器中始终为 null
【发布时间】:2022-02-14 18:49:33
【问题描述】:

我在后端使用 ASP.NET Core Web API,并在 Blazor WASM 客户端的 httpClient 标头中使用 JWT 令牌(我不将 JWT 令牌存储在 cookie 中)。

问题在于,虽然用户已经登录并且身份验证和授权工作没有问题,但在每个控制器中(继承自ControllerBase)总是:

  • HttpContext.User.Identity.IsAuthenticated 是假的
  • HttpContext.User.Identity.Name 为空
  • HttpContext.User.Claims 为空

但请求具有 JWT 令牌(Request.Headers["Authorization"][0] 等于 Bearer eyJhbGciOiJIUzI1...)并且 [Authorize] 属性正常工作。

这就是我的 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 =>
            {
            });

我还以正确的顺序调用了中间件:

app.UseRouting();

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

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

【问题讨论】:

  • 您能告诉我们您添加到控制器的属性吗?
  • @Nisd 在这种情况下仅使用 HttpGet。但是还有其他具有 Authorize 属性的方法
  • @Nisd 您的评论很有帮助。实际上,我正在使用没有任何 Authorize 属性的方法对其进行测试,因此答案是使用 Authorize Attribute 。随意添加它作为答案。谢谢

标签: c# jwt asp.net-core-webapi asp.net-core-identity


【解决方案1】:

HttpContext.User 仅在您启用该方法的身份验证时设置。

您可以通过在控制器或操作上设置[Authorize] 来启用它,或者配置一个全局过滤器,以便默认授权所有请求。

【讨论】:

    猜你喜欢
    • 2020-03-11
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 2017-08-28
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    相关资源
    最近更新 更多