Authorisation with Azure AD Groups
When authenticating your Web application with Azure AD all users from the specified Azure Active Directory will have access to the secured Web Application. In order to have more granular access control you can implement a custom authorisation filter based on the signed in user’s Azure AD Group.
User group information can be available to you from the Claims collections for the authenticated user if the group claims feature is enabled. To do so you need to:
- In Azure portal, find the app registration your Web App is using for the authentication.
- Click on ‘Edit Manifest’ link and update GroupMembershipClaims to be ‘Security Group’.
After making this change you will start getting group claims in the token for the users of your application. Note that SecurityGroup value will only return you security group claims. If you want to get distribution lists set the groupMembershipClaims to ‘All’.
In your code you can get to the list of user group ids through the ClaimsPrincipal class:
var claimsPrincipal = httpContext.User as ClaimsPrincipal;
var groupIds = claimsPrincipal.Claims.Where(c => c.Type == “groups”).Select(c => c.Value).ToList();
To check if the signed in user belongs to a specific group you need to perform the following steps:
- In Azure Portal, go to Users and Groups.
- Search for a group you are interested in. Click on it and copy its ObjectID.
- Check if the ObjectID is in the list of groupIDs you got from the claims.
Based on user group claims you can restrict access to certain areas of your web application. For ASP.NET MVC applications you can wrap the code above into an AuthorizeCore method of a custom Authorize Attribute to control access to your controllers/actions.