我将ASP.NET Identity Server4配置为使用ASP.NET核心身份验证(Auth Server
)进行授权和验证。我还配置了一个单独的ASP.NET核心API (API
)来使用Auth Server
。在控制台应用程序中,我能够使用GrantTypes.ClientCredentials
对Auth Server
进行身份验证,并使用accesstoken执行对API
的请求。一切都按预期运行。
我想使用此API
作为身份管理应用程序接口来添加/编辑/删除用户、角色等,所以我使用ASP.NET核心身份对其进行了配置,但现在当我从控制台应用程序执行相同的请求时,我得到了404,因为API
重定向到不存在的登录屏幕(毕竟它是一个应用程序接口)。这告诉我当前没有使用AccessToken和Identity Server身份验证。这意味着我的新配置似乎覆盖了Identity Server配置。
接口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身份?
发布于 2019-08-02 12:21:52
问题与services.AddIdentity<IdentityUser>()
的使用有关。正如此answer中所解释的,AddIdentityCore
应用于“添加用户管理操作所需的服务”,而AddIdentity
执行相同的操作以及所有身份验证,这将覆盖我的Identity服务器身份验证。
最终配置:
services.AddIdentityCore<IdentityUser>()
.AddRoles<IdentityRole>()
.AddUserManager<UserManager<IdentityUser>>()
.AddEntityFrameworkStores<IdentityContext>()
.AddDefaultTokenProviders();
https://stackoverflow.com/questions/57319741
复制相似问题