简体   繁体   中英

.NET Core 2.2 : How to auto-populate list of users from Azure AD in Azure app service.?

My application is using open id connect authentication and resource used is graph API to generate access token.

.AddOpenIdConnect(options =>
            {
                options.ClientId = azureAdConfig.ClientId;
                options.ClientSecret = azureAdConfig.ClientSecret;
                options.Authority = string.Format(azureAdConfig.AADInstance, azureAdConfig.Tenant);
                options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                options.Resource = azureAdConfig.ResourceURI_Graph;
                options.Events = new AuthEvents(azureAdConfig, connectionStringsConfig);
            });

Following code works very well locally which uses DirectorySearcher class to find users from directory using LDAP protocol.

 DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE");
        var defaultNamingContext = rootDSE.Properties["defaultNamingContext"].Value;      
  
   using (DirectorySearcher searcher = new DirectorySearcher("LDAP://" + defaultNamingContext))
                    {
           searcher.Filter = "(&(objectClass=user)(objectcategory=person)(displayName=" + username + "*))";
          SearchResult userProperty = searcher.FindOne();

}

But the same code fails once deployed to azure app service with Access denied exception.

    System.Runtime.InteropServices.COMException:
   at System.DirectoryServices.DirectoryEntry.Bind (System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
  

I have a token but how would i reuse the token generated using open Id to create a graphapi client and get the user's information.

Here's a pretty good example of how to use oidc with msal to get a token, save it and use it to call graph: https://github.com/microsoftgraph/aspnetcore-connect-sample to call graph, ultimately check /helpers/graphsdkhelper.cs . This is for .netcore 2.1 but 2.2 will be pretty much identical.

If you have the token, you create a GraphServiceClient give it a authentication header with bearer / token something like

requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

and use the graph client to make calls.

That example also has how to cache the tokens for use like this.

The other sample Microsoft provides is the newest one here: https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/master/2-WebApp-graph-user/2-1-Call-MSGraph

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM