【问题标题】:User.Claims Is Empty In MVC ApplicationUser.Claims 在 MVC 应用程序中为空
【发布时间】:2019-10-17 17:22:07
【问题描述】:

我正在将我的 .NET Core 2.2 MVC 应用程序升级到 3.0。在这个应用程序中,我使用 JWT 令牌对控制器进行身份验证。该令牌包含多个声明,但当我尝试通过 User.Claims 访问它们时,结果列表始终为空。

在我的Startup.cs 中,我的身份验证设置如下:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Code removed for clarity //

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = JwtManager.Issuer,
                    ValidAudience = "MyAudience",
                    IssuerSigningKey = "MySigningKey"
                };
            });
    }
}

在 Core 2.2 中,我可以使用类似于以下的代码访问我的声明:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class MyController : Controller
{
    [HttpGet("MyController/Action")]
    public ActionResult<Aggregate[]> GetAction()
    {
        var username = User.FindFirstValue("MyUsernameClaim");
        if (username == null)
        {
            return Forbid();
        }       
        // Do Stuff //
    }
}

但是,当我将相同的代码迁移到 Core 3.0 时,我正确地进行了身份验证,但我没有收到 User 对象的声明。

我是否错过了将其转换为 3.0 的步骤? User 不会再自动填充信息吗?

【问题讨论】:

  • 您能否确认用户已通过身份验证?我看不到图像,但User.Identity.IsAuthenticated 似乎是错误的。如果是这样,那么这可能与 AuthenticationScheme 有关。
  • 你是如何配置路由的?您是否在 UseEndpoints 之前按顺序添加了 UseRouting、UseAuthentication 和 UseAuthorization?你能展示那段代码吗?
  • @RuardvanElburg 我将UseEndpoints 移动到Configure 方法的末尾并修复了问题。天哪,我无法相信这么简单的事情让我花费了令人尴尬的时间。如果您想将其发布为答案,我会接受。

标签: c# asp.net-mvc .net-core


【解决方案1】:

似乎用户根本没有经过身份验证。

随着 asp.net core 3.0 路由已更改为端点路由。您可以通过设置EnableEndpointRouting = false 选择退出。

但这里的情况似乎并非如此。这意味着您在使用时必须包含某些服务,例如身份验证和授权:

public void Configure(IApplicationBuilder app)
{
  ...

  app.UseStaticFiles();

  app.UseRouting();
  app.UseCors();

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

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

最重要的是,按这个顺序。如此处所述:Migrate Startup.Configure.

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-03
  • 1970-01-01
  • 2012-06-22
  • 2021-02-26
  • 2020-07-10
  • 2014-03-28
  • 1970-01-01
相关资源
最近更新 更多