Search code examples
c#asp.net-coreauthorization

Require authenticated user in asp.net core but require custom policy in some actions require custom policy


My Asp.net core site required authentication by default

services.AddMvc(config =>
{
    //only allow authenticated users
    var policy = new AuthorizationPolicyBuilder()
    .RequireAuthenticatedUser()
    .Build();

    config.Filters.Add(new AuthorizeFilter(policy));
});

but for one action I would need to allow anonymous access (/Account/AddUser if there are no users in the database).

I created this custom policy which checks that the user is either authenticated or that the user db is empty.

[Authorize(Policy = "NoUsersInDatabaseOrUserAuthenticated")]
public IActionResult AddUser()
{
    return View();
}

There seems to be an AND between the global policy and this so it won't work. If I add [AllowAnonymous] the policy is not evaluated at all.

How can I replace the global policy with a custom policy for one action?


Solution

  • I ended up leaving the global authentication requirement and put AllowAnonymous on the actions. I then solved the requirement by adding code in the action that checks that the user is either authenticated or that the user db is empty.