Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of groups that Azure AD user belongs to in claims for .Net Core

Tags:

I am trying to get the list of groups in Azure AD user belongs to in .Net Core with token generated in the "implicit flow". There is no group information.

I am using "implicit flow" as mentioned in the following link: .NET Core and Azure Active Directory integration

The following shows how to do it in the .NET Framework but .NET Core don't have the 'ActiveDirectoryClient' class.

Get a list of groups that Azure AD user belongs to in claims

Any Help is much appreciated!

derek

like image 634
Derek Liang Avatar asked May 31 '17 21:05

Derek Liang


People also ask

How do you see what Azure AD groups I am in?

You can see all the groups for your organization in the Groups - All groups page of the Azure portal. Go to Azure Active Directory > Groups.

What is the All users group in Azure AD?

Creating an "all users" dynamic groupYou can create a group containing all users within a tenant using a membership rule. When users are added or removed from the tenant in the future, the group's membership is adjusted automatically.

What is group claims in Azure AD?

Group Claims automatically add the user to a group or remove the user from group memberships when the group claim in the SAML token contains a matching group in NetDocuments. Administrators only need to update group memberships in one place.


1 Answers

You could firstly set the groupMembershipClaims property to SecurityGroup in manifest , then get the groups list in asp.net core after login :

var groups = User.Claims.Where(c => c.Type == "groups").ToList();

Update :

Then you could call Azure AD Graph api to get the group information . Firstly refer to code sample :https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect-aspnetcore

In .net core app , you could get the group object id and call graph api :

https://graph.windows.net/myorganization/groups/<objectid>?api-version=1.6

You could set Read all groups delegated permission for Windows Azure Active Directory in Required permissions blade of your app . Then try below code to get the group name :

        try
        {

            var groups = User.Claims.Where(c => c.Type == "groups").ToList();


            string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
            AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID, HttpContext.Session));
            ClientCredential credential = new ClientCredential(Startup.ClientId, Startup.ClientSecret);
            result = await authContext.AcquireTokenSilentAsync(Startup.GraphResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

            //
            // Retrieve the group information.
            //
            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://graph.windows.net/myorganization/groups/"+ groups[1].Value + "?api-version=1.6" );
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
            HttpResponseMessage response = await client.SendAsync(request);


            if (response.IsSuccessStatusCode)
            {
                List<Dictionary<String, String>> responseElements = new List<Dictionary<String, String>>();
                JsonSerializerSettings settings = new JsonSerializerSettings();
                String responseString = await response.Content.ReadAsStringAsync();
                var model = JsonConvert.DeserializeObject<RootObject>(responseString);
                var groupName = model.displayName;
            }
            else
            {

                if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {

                }
            }
        }
        catch (Exception ee)
        {

        }

Group entity below is for your reference :

   public class RootObject
        {
            public string objectType { get; set; }
            public string objectId { get; set; }
            public object deletionTimestamp { get; set; }
            public string description { get; set; }
            public object dirSyncEnabled { get; set; }
            public string displayName { get; set; }
            public object mail { get; set; }
            public string mailNickname { get; set; }
            public bool mailEnabled { get; set; }
            public bool securityEnabled { get; set; }
        }
like image 89
Nan Yu Avatar answered Sep 21 '22 10:09

Nan Yu