【问题标题】:User.Identity.Name is null in asp.net core + angular client appUser.Identity.Name 在 asp.net core + angular 客户端应用程序中为空
【发布时间】:2020-06-19 09:42:55
【问题描述】:

我使用以下 .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 是 true。

虽然在客户端(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");
                }
            });
        }

luanchSettings.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"
      }
    }
  }
}

【问题讨论】:

  • 或者您可以在身份服务器发出访问令牌时包含用户名作为声明,例如,使用profile service

标签: c# angular asp.net-core


【解决方案1】:

如果在 .Net Core + Angular 基础设置中发现以下声明正在填充并提供用户 ID。

User.FindFirstValue(ClaimTypes.NameIdentifier)

使用用户 ID,我们可以获得应用程序用户并做任何我们需要的事情,在我的例子中,在执行特定控制器操作之前验证 actionfilter 中的角色。

【讨论】:

  • 那么为什么这行得通而 userManager 方法却不行呢?
猜你喜欢
  • 2019-02-07
  • 2020-07-31
  • 2019-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多