将ASP.NET核心身份添加到具有身份服务器的API中



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

我想将此API用作身份管理API来添加/编辑/删除/删除用户,角色等,因此我使用ASP.NET Core Identity对其进行配置,但是现在,当我从Console App中执行相同的请求时,我得到了404,因为API正在重定向到不存在的登录屏幕(毕竟是API(。这告诉我的是,当前的访问和身份服务器验证尚未使用。这意味着我的新配置似乎覆盖了身份服务器。

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应用于"添加用户管理操作所需的服务",而AddIdentity则使用相同的所有身份验证,这覆盖了我的身份服务器身份验证。

最终配置:

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

最新更新