简体   繁体   中英

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

I use the following .net cli command:

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.

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:

[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.

在此处输入图片说明

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.

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.

Startup.cs ConfigureServices

        // 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

        // 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"
      }
    }
  }
}

If found that in .Net Core + Angular base setup the following claim is being populated and provides the User 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM