Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 390
Mathias Rönnlund Avatar asked Apr 05 '16 16:04

Mathias Rönnlund


People also ask

What is the fallback policy method that is used to require users to be authenticated?

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.

What is difference between authentication and authorization in ASP.NET Core?

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.

What is policy based authorization in .NET Core?

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.


2 Answers

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.

like image 76
Mathias Rönnlund Avatar answered Oct 09 '22 02:10

Mathias Rönnlund


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.

like image 4
blowdart Avatar answered Oct 09 '22 02:10

blowdart