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?
The preceding code uses an authorization filter, setting the fallback policy uses endpoint routing. Setting the fallback policy is the preferred way to require all users be authenticated.
Authentication is the process of determining a user's identity. Authorization is the process of determining whether a user has access to a resource. In ASP.NET Core, authentication is handled by the authentication service, IAuthenticationService, which is used by authentication middleware.
In ASP.NET Core, the policy-based authorization framework is designed to decouple authorization and application logic. Simply put, a policy is an entity devised as a collection of requirements, which themselves are conditions that the current user must meet.
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.
You can't. Policies are additive. So, global will always be there, and then any extra policies are evaluated after. In addition policies require authentication, you can't have a policy that allows unauthenticated users or something else, they must always be authenticated, as authentication acts upon the results of authorization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With