I'm in the process of learning Asp.Net Core Identity along with Identity Server 4. So far I have got my User authenticated against IdS4, then I can get a token to use access my API, this all works as expected, however I always need to create my Authorization Attributes on my API controller with a specified AuthenticationScheme parameter, even though I specify it my API's Config.cs (according to several sources/guides I have read).
This is my API's Config.cs, I have left the different attempts commented out. Each version hasn't has any effect, occasionally a 500 error instead of a 401, but that will be down to me doing something very wrong!
Config.cs
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();
});
}
Here is a sample endpoint from my API Controller. In it's current state it works fine, however I believe I shouldn't need to specify the AuthenticationSchemes, but if I remove it, I always get a 401 error. Does anyone have any suggestions on what I'm missing?
API Controller
// GET: api/TestItems
[HttpGet]
//[Authorize]
[Authorize(AuthenticationSchemes = "Bearer")]
public async Task<ActionResult<IEnumerable<TestItemDto>>> GetTestItems()
{
//SNIP
}