Diego
Diego

Reputation: 2362

ASP.NET Core 6 MVC : create authorization policy dynamically

I am creating an ASP.NET Core 6 MVC app.

After the user login I go to the database and return the roles that are available for objects (textbox, buttons) for the entire application.

With those Object-Roles I want to create an authorization policy that will be used by the User to have or NOT Have access to that object.

As far as I know and my experience, the policy is set in program.cs.

services.AddAuthorization(options =>
{
    options.AddPolicy("AdminAccess", policy => policy.RequireRole("Admin"));
}

But in this case, I have to do it dynamically somewhere else, after program.cs is loaded.

What is the best approach to generate these policies?

Thanks

Upvotes: 0

Views: 1273

Answers (1)

MD Zand
MD Zand

Reputation: 2605

An authorization handler is responsible for the evaluation of a requirement's properties. Then you can evaluates the requirements against a provided AuthorizationHandlerContext to determine if access is allowed.

Then it will look like this code:

services.AddAuthorization(options =>
{
    options.AddPolicy("ThePolicy", policy => policy.Requirements.Add( new ThePolicyRequirement() ));
});

services.AddScoped<IAuthorizationHandler, MyPolicyAuthorizationHandler>();

Then you can

public class MyPolicyAuthorizationHandler : AuthorizationHandler<MyPolicyRequirement>
{
  readonly AppDbContext _context;


public MyPolicyAuthorizationHandler(DbContext c)
{
    _context = c;
   
}

protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, MyPolicyRequirement requirement)
{
    // Check context.User and context.Resource against db
     ....
    if (_context.PolicyRequirements.FirstOrDefault(....) && context.User.HasClaim("Some claim"))
     {
        
        context.Succeed(requirement);
     }

    return Task.CompletedTask;   
    ....
   }               
  }
}

public class MyPolicyRequirement : IAuthorizationRequirement { }

Check here for more information about authorization handler and requirements.

Upvotes: 1

Related Questions