[英]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
.创建开箱即用的应用程序
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..
通常(当我自己使用 WebApi 实现 OAuth 时)我会在应用程序请求 OAuth 令牌时从数据库中检索用户,然后注入声明说“UserID”=“1001”。当用户点击获取数据时 - 我会检索该用户 ID 和controller中的位置并返回与该用户相关的数据。
How do I do that with IdentityServer4 - getting user in a controller?如何使用 IdentityServer4 做到这一点 - 让用户进入 controller?
Startup.cs启动.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.. HttpContext.User 和 Claims 没有有意义的信息。
Currently with asp.net core 5.0 and identityServer4 this works inside a controller:目前使用 asp.net 核心 5.0 和 identityServer4 这在 controller 内工作:
this.User.FindFirst(ClaimTypes.NameIdentifier).Value;
and this returns null:这将返回 null:
userManager.GetUserId(User);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.