0

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
}

1 Answer 1

2

Issue is because of order of middleware added in the Startup.Configure method. Proper order is critical for security. Read more here. In this case you move app.UseAuthorization() to be after app.UseAuthentication(). The code would be like:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
       app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer, I knew it was something simple and I knew order for the middleware was important, I just didn't know what the order was as I've been following guides which don't really empathize the order, especially now I'm deviating from the flow of the guides. I'll read up on that link you sent so this won't happen again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.