Boppity Bop
Boppity Bop

Reputation: 10463

How to get current user in ASP.NET core with IdentityServer4 in a controller?

Created out of the box app dotnet new angular --auth Individual. It works fine.

Now I want to upgrade it a little. Say I want to show weather forecast for the user location. Normally (when I implement OAuth with WebApi myself) I would retrieve user from data base when application requests OAuth token and then inject Claim say "UserID"="1001".. And when user clicks Fetch Data - I would retrieve that userid and the location in the controller and return data relevant to that user..

How do I do that with IdentityServer4 - getting user in a controller?

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 and Claims has no meaningful information.. enter image description here

Upvotes: 2

Views: 1605

Answers (1)

Boppity Bop
Boppity Bop

Reputation: 10463

Currently with asp.net core 5.0 and identityServer4 this works inside a controller:

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

and this returns null:

userManager.GetUserId(User);

Upvotes: 1

Related Questions