[我正在与Identity Server 4一起学习Asp.Net Core身份。到目前为止,我已经根据IDS4对用户进行了身份验证,然后我可以获取令牌来使用访问我的API,所有这些都可以正常工作,但是,即使我将其指定为我的API的AuthenticationScheme
(根据我已阅读的多个资料/指南),我也始终需要使用指定的Config.cs
参数在API控制器上创建我的授权属性。
这是我的API的Config.cs
,我已将其他尝试注释掉。每个版本都没有任何效果,偶尔会出现500错误而不是401错误,但这取决于我做错了什么!
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationCoreDbContext>(opt => opt.UseInMemoryDatabase("TestItem"));
services
.AddMvc();
services
//.AddAuthentication(cfg =>
//{
// cfg.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
// cfg.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
//})
.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
//.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = "https://localhost:5001";
options.RequireHttpsMetadata = false;
options.ApiName = "web_api";
options.EnableCaching = true;
options.CacheDuration = TimeSpan.FromMinutes(10);
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
这里是我的API控制器的示例端点。在当前状态下,它可以正常工作,但是我认为我不需要指定AuthenticationSchemes
,但是如果删除它,则总是会出现401错误。有人对我的失踪有任何建议吗?
// GET: api/TestItems
[HttpGet]
//[Authorize]
[Authorize(AuthenticationSchemes = "Bearer")]
public async Task<ActionResult<IEnumerable<TestItemDto>>> GetTestItems()
{
//SNIP
}
我正在与Identity Server 4一起学习Asp.Net Core身份。到目前为止,我已经根据IDS4对用户进行了身份验证,然后我可以获取令牌来使用访问我的API,所有这些都以.. 。
问题是由于在Startup.Configure
方法中添加了中间件的顺序。正确的订单对于安全至关重要。阅读更多here。在这种情况下,将app.UseAuthorization()
移到app.UseAuthentication()
之后。代码如下: