[英]User.Identity.Name is null in my ASP.NET Core Web API
[英]User.Identity.Name is null in asp.net core + angular client app
我使用以下 .net cli 命令:
dotnet new angular -o MyAngularApp -au individual
这会导致预期的 .net 核心 Web Api 项目带有嵌入式 Angular 客户端应用程序,该应用程序具有示例受保护的 API 控制器和示例受保护的客户端路由。
然后我运行应用程序并添加一个用户。
我将以下 2 行添加到默认授权 WeatherForecastsController 获取操作以调查用户状态:
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var isAuthenticated = User.Identity.IsAuthenticated; //1
var userId = userManager.GetUserId(User); //2
并且在检查 userId 时这是 null 并且 isAuthenticated 是真的。
尽管在客户端(chrome 浏览器)中,我确实看到用户数据存储在 cookie 中,并且 Api 控制器由 Authorize 属性保护,但似乎用户信息并未在 API 控制器中传播。
是否需要在启动配置或启动类中添加更多设置以正确连接它。 最后的游戏是确认用户有一组角色,但没有合适的用户,我一事无成。 我可以将每个请求的用户 ID 发送到 api 控制器,但我认为这是将 IdentityJwt 添加到混合中的目的。
Startup.cs 配置服务
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
services.AddAuthentication()
.AddIdentityServerJwt();
services.AddControllersWithViews();
services.AddRazorPages();
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
Startup.cs 配置方法
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
if (!env.IsDevelopment())
{
app.UseSpaStaticFiles();
}
app.UseRouting();
app.UseAuthentication();
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
lunchSettings.json
{
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
"iisExpress": {
"applicationUrl": "http://localhost:62083",
"sslPort": 44373
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"MyAngularApp": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
如果发现在 .Net Core + Angular 基础设置中,则会填充以下声明并提供用户 ID。
User.FindFirstValue(ClaimTypes.NameIdentifier)
使用用户 ID,我们可以获得应用程序用户并执行我们需要的任何操作,在我的情况下是在执行特定控制器操作之前验证 actionfilter 中的角色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.