【问题标题】:How to get current user in ASP.NET core with IdentityServer4 in a controller?如何在控制器中使用 IdentityServer4 获取 ASP.NET 核心中的当前用户?
【发布时间】:2020-12-06 07:03:00
【问题描述】:

创建开箱即用的应用程序dotnet new angular --auth Individual。它工作正常。

现在我想稍微升级一下。假设我想显示用户位置的天气预报。通常(当我自己使用 WebApi 实现 OAuth 时)我会在应用程序请求 OAuth 令牌时从数据库中检索用户,然后注入声明说“UserID”=“1001”。当用户单击 Fetch Data 时 - 我会检索该用户 ID 和控制器中的位置并返回与该用户相关的数据..

如何使用 IdentityServer4 做到这一点 - 让用户进入控制器?

Startup.cs

        public void ConfigureServices(IServiceCollection services)
            ...
            services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

            services.AddAuthentication()
                .AddIdentityServerJwt();
            services.AddControllersWithViews();

. . .

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, IConfiguration configuration)
            ...
            app.UseAuthentication();
            app.UseIdentityServer();
            app.UseAuthorization();

HttpContext.User 和 Claims 没有有意义的信息..

【问题讨论】:

  • 这里已经回答了这个问题:ASP.NET Core Identity - get current user
  • 你救了我! :) 谢谢.. 我试过 UserManager.GetUserId 但它返回 null... 我没有在任何地方看到 User.FindFirst 或者我错过了..

标签: c# asp.net-core security identityserver4


【解决方案1】:

目前使用 asp.net core 5.0 和 identityServer4,这在控制器内工作:

this.User.FindFirst(ClaimTypes.NameIdentifier).Value;

这会返回 null:

userManager.GetUserId(User);

【讨论】:

    猜你喜欢
    • 2022-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 2019-09-27
    • 2021-06-13
    • 1970-01-01
    相关资源
    最近更新 更多