簡體   English   中英

User.Identity.Name 在 asp.net core + angular 客戶端應用程序中為空

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM