简体   繁体   English

User.Identity.Name 在 asp.net core + angular 客户端应用程序中为空

[英]User.Identity.Name is null in asp.net core + angular client app

I use the following .net cli command:我使用以下 .net cli 命令:

dotnet new angular -o MyAngularApp -au individual

This results in the expected .net core Web Api project with the embedded Angular client app which has an example guarded API controller and example guarded client route.这会导致预期的 .net 核心 Web Api 项目带有嵌入式 Angular 客户端应用程序,该应用程序具有示例受保护的 API 控制器和示例受保护的客户端路由。

Then I run the app and add a user.然后我运行应用程序并添加一个用户。

I add the following 2 lines to the default authorized WeatherForecastsController get action to investigate the User state:我将以下 2 行添加到默认授权 WeatherForecastsController 获取操作以调查用户状态:

[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
    var isAuthenticated = User.Identity.IsAuthenticated; //1
    var userId = userManager.GetUserId(User); //2

And upon checking userId this is null and isAuthenticated is true.并且在检查 userId 时这是 null 并且 isAuthenticated 是真的。

在此处输入图片说明

Although in the client side (chrome browser) I do see that the user data is being stored in a cookie and the Api controller is being guarded by the Authorize attribute it seems the user information is not propagated in the API controller.尽管在客户端(chrome 浏览器)中,我确实看到用户数据存储在 cookie 中,并且 Api 控制器由 Authorize 属性保护,但似乎用户信息并未在 API 控制器中传播。

Is there more settings that need to be added in launch config, or the startup class to wire this up correctly.是否需要在启动配置或启动类中添加更多设置以正确连接它。 The end game is to confirm that the user has a set of roles but without the appropriate user I am getting nowhere.最后的游戏是确认用户有一组角色,但没有合适的用户,我一事无成。 I could send the user id on every request to the api controller but I thought this is the purpose of adding the IdentityJwt to the mix.我可以将每个请求的用户 ID 发送到 api 控制器,但我认为这是将 IdentityJwt 添加到混合中的目的。

Startup.cs ConfigureServices 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 Configure method 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 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"
      }
    }
  }
}

If found that in .Net Core + Angular base setup the following claim is being populated and provides the User Id.如果发现在 .Net Core + Angular 基础设置中,则会填充以下声明并提供用户 ID。

User.FindFirstValue(ClaimTypes.NameIdentifier)

With the user id we can obtain the Application User and do whatever we need which in my case is verify the Roles in an actionfilter before performing a specific controller action.使用用户 ID,我们可以获得应用程序用户并执行我们需要的任何操作,在我的情况下是在执行特定控制器操作之前验证 actionfilter 中的角色。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 User.Identity.Name 是 null 在我的 ASP.NET 核心 Web ZDB974238714CA8A14A7CE1D0 - User.Identity.Name is null in my ASP.NET Core Web API User.Identity.Name 在 ASP.NET Core MVC 应用程序中返回 null - User.Identity.Name returns null in ASP.NET Core MVC application 对于托管在 asp.net core 中的 Blazor Wasm,User.Identity.Name 为 null - User.Identity.Name is null for Blazor Wasm hosted in asp.net core 会话与User.Identity.Name进行比较,以使用Windows身份验证检查ASP.net核心应用程序的登录用户名 - Session vs User.Identity.Name to check the loggeduser name for ASP.net core application with windows authentication 为什么运行 ASP.NET 6 项目时 `User.Identity.Name` `null`? - Why is `User.Identity.Name` `null` when running ASP.NET 6 project? ASP.NET控制器基类User.Identity.Name - ASP.NET Controller Base Class User.Identity.Name User.Identity.Name 在 PasswordSignInAsync MVC .Net Core 3.0 之后始终为 null 并声明计数为 0 - User.Identity.Name always null and claims count 0 after PasswordSignInAsync MVC .Net Core 3.0 测试使用User.Identity.Name的Asp.Net控制器操作方法? - Test an Asp.Net Controller action method which uses User.Identity.Name? ASP.NET Web 表单应用程序 User.Identity.Name 在 IIS 中不起作用 - ASP.NET web form application User.Identity.Name not working in IIS 如何在ASP.NET中使用User.Identity.Name作为SqlDataSource的参数? - How to use User.Identity.Name as a parameter for SqlDataSource in ASP.NET?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM