Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For the first time I'm creating Authorization in ASP.NET Core. I used tutorial from here TUTORIAL

The problem is when I sending request from postman:

Authorization:Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6I... 

to my method in controller decorated with [Authorize] attribute.

I receive 401 Unauthorized always... I saw comments bellow that tutorial and it seems that some people have similar issue also. I've no idea how I can solve this problem.

like image 570
DiPix Avatar asked Apr 23 '17 17:04

DiPix


People also ask

How do I fix the 401 unauthorized error in ASP.NET Core?

I fixes mine by changing the UseAuthentication() and order of UseAuthentication() and UseRouting() in the Configure method on Startup class.

How can use Authorize attribute in core in asp net?

Authorization in ASP.NET Core is controlled with AuthorizeAttribute and its various parameters. In its most basic form, applying the [Authorize] attribute to a controller, action, or Razor Page, limits access to that component to authenticated users. Now only authenticated users can access the Logout function.


1 Answers

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 ;)

like image 94
DiPix Avatar answered Sep 20 '22 17:09

DiPix