简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM