Authorization in ASP.NET Core. Always 401 Unauthorized for [Authorize] attribute Authorization in ASP.NET Core. Always 401 Unauthorized for [Authorize] attribute asp.net asp.net

Authorization in ASP.NET Core. Always 401 Unauthorized for [Authorize] attribute


At the request of others here is the answer:

The problem was with the middleware order in Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){    ConfigureAuth(app); // your authorisation configuration    app.UseMvc();}

Why middleware order is important? If we put app.UseMvc() first - then the MVC actions would get in the routing and if they see the Authorize attribute they will take control of its handling and that's why we receives 401 Unauthorized error.

I hope it helps someone ;)


in ASP.NET Core 3.0, i had the same problem, what worked for me was:

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

in StartUp.Configure method.

This doc shows typical ordering of middleware components:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.0


If you are using ASP.NET Core 3.0

Check this order

app.UseAuthentication();

app.UseRouting(); //must be below app.UseAuthentication();

If you are using ASP.NET Core < 3.0

Just replace the app.UseRouting(); by app.UseMvc();

i.e:

app.UseAuthentication();

app.UseMvc(); //must be below app.UseAuthentication();