.net-coreasp.net-mvc-scaffoldingasp.net-core-6.0asp.net-core-scaffolding

Unable to add global AuthorizeFilter when using scaffolded Identity pages in ASP.Net Core MVC application


I created ASP.Net Core MVC project from template with enabled Identity.

I created db from migration files using update-database command.

I was able to run application, register users and login.

I added AuthorizeFilter globally:

builder.Services.AddControllersWithViews(o => o.Filters.Add(new AuthorizeFilter()));

it still worked.

But when I scaffolded Login page using Visual Studio functionality, I wasn't able to login anymore. I was being redirecting to "infinitelly" looped url: enter image description here

When I remove global AuthorizeFilter:

builder.Services.AddControllersWithViews()

and add it over Action:

[Authorize]
public IActionResult Index()

It works again.

Is there any bug preventing using scaffolded Razor Pages with global AuthorizeFilter? Or rather I did something wrong or missed?


Solution

  • Global AuthorizeFilter apply on every methods of your project that means your login method too.

    I guess your login page is the page where users are redirected to when they are not logged in. so what happen is :

    I'm going to login page => login page needs authorization => redirect to login page => login page needs authorization => redirect to login page...

    Your login method has to accept anonymous connection cause user is not logged in yet.

    Add the attribute [AllowAnonymous] on your login method.