[英]ASP.NET Core 6 MVC : create authorization policy dynamically
I am creating an ASP.NET Core 6 MVC app.我正在创建一个 ASP.NET Core 6 MVC 应用程序。
After the user login I go to the database and return the roles that are available for objects (textbox, buttons) for the entire application.用户登录后,我 go 到数据库并返回可用于整个应用程序的对象(文本框、按钮)的角色。
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.对于这些Object-Roles
,我想创建一个授权策略,用户将使用该策略来访问或不访问该 object。
As far as I know and my experience, the policy is set in program.cs
.据我所知和我的经验,该策略是在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.但在这种情况下,我必须在加载program.cs
之后在其他地方动态地执行此操作。
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.然后,您可以根据提供的 AuthorizationHandlerContext 评估要求以确定是否允许访问。
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. 在此处查看有关授权处理程序和要求的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.