将 Asp.net 核心身份添加到使用身份服务器保护的 API

Add Asp.net Core Identity to an API secured with Identity Server

我有一个 ASP.NET 身份服务器 4 配置为使用 ASP.NET 核心身份 (Auth Server) 进行授权和身份验证。我还有一个单独的 ASP.NET Core API (API) 配置为使用 Auth Server。从控制台应用程序,我可以使用 GrantTypes.ClientCredentialsAuth Server 进行身份验证,并使用访问令牌执行对 API 的请求。一切都按预期工作。

我想将此 API 用作 API 对 add/edit/remove 用户、角色等的身份管理,因此我使用 ASP.NET 核心身份对其进行配置,但是现在,当我从控制台应用程序执行相同的请求时,我得到一个 404,因为 API 正在重定向到不存在的登录屏幕(毕竟它是一个 API)。这告诉我当前的 AccessToken 和 Identity Server 身份验证未被使用。这意味着我的新配置似乎覆盖了身份服务器配置。

API Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        string connectionString = Configuration.GetConnectionString("IdentityContextConnection");

        //This was added for ASP.NET Identity
        services.AddDbContext<IdentityContext>(options =>
             options.UseSqlServer(connectionString));

        //This was added for ASP.NET Identity
        services.AddIdentity<IdentityUser, IdentityRole>()
               .AddEntityFrameworkStores<IdentityContext>()
               .AddDefaultTokenProviders();

        services.AddMvcCore()
            .AddAuthorization()
            .AddJsonFormatters();

        services.AddAuthentication("Bearer")
            .AddJwtBearer("Bearer", options =>
            {
                options.Authority = "http://localhost:5000";
                if (Environment.IsDevelopment())
                    options.RequireHttpsMetadata = false;
                options.Audience = "management-api";
            });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseAuthentication();
        app.UseMvc();
    }

我怎样才能让这个 API 针对我的 Auth Server 进行身份验证和授权,同时使用 ASP.NET 身份?

问题出在 services.AddIdentity<IdentityUser>() 的使用上。正如此 中所解释的,AddIdentityCore 应该用于 "adding the services that are necessary for user-management actions",而 AddIdentity 做同样的事情加上所有身份验证,这会覆盖我的身份服务器身份验证。

最终配置:

services.AddIdentityCore<IdentityUser>()
            .AddRoles<IdentityRole>()
            .AddUserManager<UserManager<IdentityUser>>()
            .AddEntityFrameworkStores<IdentityContext>()
            .AddDefaultTokenProviders();