【问题标题】:Add Asp.net Core Identity to an API secured with Identity Server将 Asp.net Core Identity 添加到受 Identity Server 保护的 API
【发布时间】:2019-08-02 03:58:28
【问题描述】:

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

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

API 启动.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 身份?

【问题讨论】:

    标签: asp.net-core identityserver4 asp.net-core-2.2 asp.net-core-identity


    【解决方案1】:

    问题在于services.AddIdentity&lt;IdentityUser&gt;() 的使用。正如answer 中所解释的那样,AddIdentityCore 应该用于“添加用户管理操作所需的服务”,而 AddIdentity 做同样的事情加上所有身份验证,这会覆盖我的身份服务器身份验证。

    最终配置:

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

    【讨论】:

      猜你喜欢
      • 2021-04-19
      • 2018-06-03
      • 2021-08-23
      • 2021-01-22
      • 2021-10-09
      • 1970-01-01
      • 2019-08-16
      • 2018-01-24
      • 2018-09-14
      相关资源
      最近更新 更多