Hemanth
Hemanth

Reputation: 91

How to validate if user is part of group in Azure AD?

I have written a Python application hosted on Open Shift.

After user login into application his privileges are decided based on his group membership in Azure Active Directory.

How can I validate if user is part of a group in Azure Active Directory through my application ?

Upvotes: 9

Views: 9657

Answers (1)

Rohit Saigal
Rohit Saigal

Reputation: 9664

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

  1. Check member groups

    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 
    

    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"
       ]
     }
    
  2. user: 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
    

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.

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.

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

Authorization in a web app using Azure AD groups & group claims

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.

Upvotes: 15

Related Questions