Reputation: 2459
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 ofapp.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
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