你可以在asp.net核心使用政策,使用属性与命名策略,那么你在启动定义策略,要求组要求,并设置能通过组ID:
public void ConfigureServices(IServiceCollection services)
{
// Add MVC services to the services container.
services.AddMvc();
// Add Authentication services.
services.AddAuthentication(sharedOptions => sharedOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme);
services.AddAuthorization(options =>
{
options.AddPolicy(
"CanAccessGroup",
policyBuilder => policyBuilder.RequireClaim("groups", "8e39f882-3453-4aeb-9efa-f6ac6ad8e2e0"));
});
}
然后在控制器:
[Authorize(Policy = "CanAccessGroup")]
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
如果组ID不在用户组要求的,将重定向用户访问被拒绝页面,你也可以写你的策略规则的逻辑如图所示here。
我认为你也可以设置RoleClaimType,然后使用角色,但这是一个更好的解决方案。 – juunas
@juunas:不鼓励使用角色,因为它非常不灵活,需要对角色进行硬编码。而策略允许模块插入自己的策略或覆盖现有的策略。有了索赔,你可以做任何你可以做的一切,你可以做的角色和更多 – Tseng
是的,正是为什么我说这是更好的;) – juunas