0

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

1
  • It seems you could only get services from Servicecollection (the default container) after builded,modify ,delete or add services are not allowed,may be you could try to replace the default container Commented Dec 9, 2022 at 2:17

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.