How can i get current user groups from Azure AD using claims in dotnet core?

Tomar, Abhishek 6 Reputation points
2024-04-16T09:54:17.1733333+00:00

I have a dotnet core web application and this app authorisation is working based on azure AD.

Question: How can i get all the groups name related to login user? do i have to make any changes in my azure app? I have already added this setting in Manifest.

            services.AddAuthentication(options=>{
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme =OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));

When my application is login i am getting the name of the login person using below code.

    @if (User.Identity.IsAuthenticated)
    {

        
    <a style="font-size: 14px; padding: 14px; height: 40px !important"><i></i>   Hello,  @User.FindFirst("name").Value.Split(", ")[1] </a>      

    }

Question: How can i get all the groups name related to login user? do i have to make any changes in my azure app? I have already added this setting in Manifest.

"groupMembershipClaims": "All, ApplicationGroup",

When i am running this code... these are the output of my claims.

            var listClaims = new List
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,385 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,175 questions
Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
6,897 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
19,508 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Tiny Wang-MSFT 1,571 Reputation points Microsoft Vendor
    2024-04-17T02:40:17.7+00:00

    Hi Tomar, when we use Azure AD as the authentication scheme in our web application, Microsoft already provide Graph API to query most of the user information. For example, this API help us to query all the groups this user belongs to.According to the api document, we could see that it requires API permissions. So that we additionally need to go to Azure AD -> registered app -> Certificates & Secrets to create a client secret, and in the API permissions blade to add required API permissions.

    User's image

    Then let's use Graph SDK into the web app, refer to my codes below.

    var builder = WebApplication.CreateBuilder(args);
    // Add services to the container.
    builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
        .EnableTokenAcquisitionToCallDownstreamApi()
        .AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApi"))
                            .AddInMemoryTokenCaches();
    builder.Services.AddControllersWithViews(options =>
    {
        var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
        options.Filters.Add(new AuthorizeFilter(policy));
    });
    builder.Services.AddRazorPages()
        .AddMicrosoftIdentityUI();
    	
    [Authorize]
    public class HomeController : Controller
    {
        private GraphServiceClient _graphServiceClient;
        public HomeController(GraphServiceClient graphServiceClient)
        {
            _graphServiceClient = graphServiceClient;
        }
        public async Task<IActionResult> IndexAsync()
        {
            var res = await _graphServiceClient.Me.MemberOf.GetAsync();
    		List<Group> groups = new List<Group>();
    		foreach (var obj in res.Value) {
    			if (obj.OdataType == "#microsoft.graph.group") {
    				groups.Add((Group)obj);
    				Group temp = (Group)obj;
    				var groupName = temp.DisplayName;
    			}
    		}
            return View();
        }
    }
    "AzureAd": {
      "Instance": "https://login.microsoftonline.com/",
      "ClientId": "client_id",
      "ClientSecret": "client_secret",
      "Domain": "TenantId",
      "TenantId": "TenantId",
      "CallbackPath": "/signin-oidc"
    },
    "Graph": {
      "BaseUrl": "https://graph.microsoft.com/v1.0",
      "Scopes": "user.read"
    },
    

    My test resultUser's image

    ================================================

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Best regards,
    Tiny