'ASP.NET Core MVC, Identity, Custom policy - Problem with custom authorization, policy

I want to add a policy so that every user expect the ones with role "Admin" could use a controller. Below is my code. When I type [Authorize(Policy="NotAdmin")] over my controller class, then actually every person (no matter if is admin or not) has access denied to actions from the controller. I use Visual Studio 2022 and .NET 6.0. In my project I use Identity, I have class ApplicationUser which extends IdentityUser class.

 public class NotAdminRequirement : IAuthorizationRequirement
    {
     
     
    }

public class NotAdminHandler : AuthorizationHandler<NotAdminRequirement>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, NotAdminRequirement requirement)
        {
            var user = context.User;

            if (!user.IsInRole("Admin"))
            {
                context.Succeed(requirement);
            } 

            return Task.CompletedTask;
        }
    }

In Program.cs:

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("NotAdmin", policy => policy.Requirements.Add(new NotAdminRequirement()));
});


Solution 1:[1]

You need to add this to Program.cs:

builder.Services.AddSingleton<IAuthorizationHandler, NotAdminHandler>();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rob Jansen