且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何验证用户是否属于 Azure AD 中的组?

更新时间:2023-11-28 22:33:34

您可以根据您的场景从您的应用程序调用以下 Microsoft Graph API -

You can call the following Microsoft Graph APIs from your application depending on your scenario -

  1. 检查成员组

如果您已经知道要检查/验证成员资格的组,这将很有帮助.

This one will be helpful if you already know the groups that you want to check/validate membership in.

 POST https://graph.microsoft.com/v1.0/users/{id | userPrincipalName}/checkMemberGroups 

在请求正文中,您可以提供 groupdIds,即包含要检查成员资格的组的对象 ID 的集合.最多可以指定 20 个组.

In request body, you can provide groupdIds, i.e. a collection that contains the object IDs of the groups in which to check membership. Up to 20 groups may be specified.

 {
  "groupIds": [
       "fee2c45b-915a-4a64b130f4eb9e75525e",
       "4fe90ae065a-478b9400e0a0e1cbd540"
   ]
 }

  • 用户:getMemberGroups

    如果您还不知道该组并想获取该用户所属的所有组,这将很有帮助.

    This one will be helpful if you don't already know the group and want to get all the groups that this user belongs to.

     POST https://graph.microsoft.com/v1.0/users/{id | userPrincipalName}/getMemberGroups
    

  • 您还可以通过编辑应用程序的清单(这可以直接在 Azure 门户中完成)并将 "groupMembershipClaims" 属性设置为,启用组声明作为应用程序访问令牌的一部分"All""SecurityGroup" 根据需要.

    You can also enable group claims to come in as part of the access token for your application by editing your application's manifest (this can be done directly in Azure Portal) and setting "groupMembershipClaims" property to "All" or "SecurityGroup" as needed.

    虽然 groupMemembershipClaims 有一个问题,但该令牌并不总是随用户所属的所有组一起提供.如果用户是太多组的成员(AFAIK 是 6 个或更多),您只会得到一个像 hasGroups 这样的超龄指标声明,告诉您用户是许多组的一部分,您应该调用 graph api获取所有组的列表.这就是我强调相关 Microsoft Graph API 的原因.

    There is a catch with groupMemembershipClaims though, that token doesn't always come with all the groups that user is member of. In case a user is member of too many groups (AFAIK it's 6 or more), you only get back an overage indicator claim like hasGroups telling you that user is part of many groups and you should call graph api to get the list of all groups. That's the reason I've highlighted the relevant Microsoft Graph API.

    这是一个基于组声明进行授权的示例应用程序.它使用 .NET 4.5 MVC、C#,但概念相同 -

    Here is a sample application that does authorization based on group claims. It's using .NET 4.5 MVC, C# but concepts are same -

    使用 Azure AD 组在 Web 应用程序中授权 &团体声明

    这是另一个 SO 帖子,其中讨论了类似的要求.它还提到考虑应用程序角色来做出授权决定,因为在某些情况下这可能更合适.

    Here is another SO Post, where a similar requirement is discussed. It also mentions considering Application Roles to make authorization decisions, as that can be more appropriate in some cases.