Alvin Sartor
Alvin Sartor

Reputation: 2459

Is there a mandatory order of statements in the Configure method of a ASP.NET Core application?

Preface:

I spent the whole afternoon trying to understand why my application was always returning a 401 unauthorized response to my requests.

After much much digging, hair pulling and swearing, I came across this question, and this answer:

putting app.UseAuthentication(); before of app.UseAuthorization(); solves the problem.

In my case I saw that I was still receiving some CORS errors (that were not happening if I removed the [Authorize] attribute) so I moved app.UseCors(AllowSpecificOriginsPolicy); first and everything worked!

The working order is:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...
    app.UseCors(AllowSpecificOriginsPolicy); // this one first
    app.UseAuthentication(); // this one second
    app.UseAuthorization(); // this one third
    ...
}

Question:

My question is, how do we know what is the right order here?
Is it written somewhere in the documentation or you just find it with trial and error?

Upvotes: 3

Views: 1135

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93153

This information was recently added to the docs, in the form of an example Configure implementation:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    // app.UseCookiePolicy();
    app.UseRouting();
    // app.UseRequestLocalization();
    // app.UseCors();
    app.UseAuthentication();
    app.UseAuthorization();
    // app.UseSession();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

Note that:

Middleware that is not added when creating a new web app with individual users accounts is commented out.

Upvotes: 3

Related Questions