【问题标题】:.net core [Authorize] using ClaimsIdentity with AAD groups.net 核心 [授权] 将 ClaimsIdentity 与 AAD 组一起使用
【发布时间】:2017-06-20 14:07:07
【问题描述】:

我在我的((System.Security.Claims.ClaimsIdentity)User.Identity).Claims 看到这个:

如何使用从 Azure AD 获取的这些组 GUID(以基于组成员身份保护端点)?

[Authorize(Roles="<group guid here>")]

[Authorize("<group guid here>")]

或者我需要在startup.cs 文件中进行设置吗?

【问题讨论】:

    标签: c# asp.net-core authorization azure-active-directory


    【解决方案1】:

    您可以在 asp.net core 中使用策略,使用具有命名策略的属性,然后在启动时定义策略以要求组声明并设置允许的组 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,然后使用Roles,但这是一个更好的解决方案。
    • @juunas:不鼓励使用角色,因为它非常不灵活并且需要对角色进行硬编码。而策略允许模块插入自己的策略或覆盖现有的策略。有了声明,你可以做你可以用角色做的一切,还有更多
    • 是的,这正是我说这更好的原因;)
    • 如何为一个资源授予对多个组的访问权限?在我的应用程序的大部分区域中,我希望特定部门能够访问网站的特定部分,但将访问权限授予管理员。
    猜你喜欢
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 2018-03-13
    • 1970-01-01
    • 2022-10-13
    • 2019-08-14
    相关资源
    最近更新 更多