I created a new project using Visual Studio 2015 and enabled authentication using work and school accounts against Azure Active Directory. Here is what the generated configure function looks like:
app.UseStaticFiles(); app.UseCookieAuthentication(); app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = Configuration["Authentication:AzureAd:ClientId"], ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"], Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"], ResponseType = OpenIdConnectResponseType.CodeIdToken }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });
Here is the rudimentary action code trying to get user groups:
public async Task<IActionResult> Index() { var client = new HttpClient(); var uri = "https://graph.windows.net/myorganization/users/{user_id}/$links/memberOf?api-version=1.6"; var response = await client.GetAsync(uri); if (response.Content != null) { ViewData["response"] = await response.Content.ReadAsStringAsync(); } return View(); }
What do I need to use or change this code to make sure I can get user groups? Currently, the response is:
{ "odata.error":{ "code":"Authentication_MissingOrMalformed", "message":{ "lang":"en", "value":"Access Token missing or malformed." }, "values":null } }
Select ASP.NET Core Web Application>Choose Web Application (Model-View-Controller) template> Click on the "Change Authentication" button>Select "Work or School Accounts". Choose Cloud - Single Organization. Fill up the field of Domain which is the Azure Active Directory tenant name (say, softdreams.onmicrosoft.com).
You can see all the groups for your organization in the Groups - All groups page of the Azure portal. Select Azure Active Directory > Groups. The Groups - All groups page appears, showing all your active groups.
I spent the last 2 days trying to figure this out and finally got it. Azure AD is a moving target and with ASPNETCORE still maturing most documentation on how to access the Azure AD Graph is outdated. So as of right now this is how you would go about access the Azure AD Graph.
Then you will use the above info to generate a Access Token, then use that token to make calls to the Graph.
public async void GetUsers() { // Get OAuth token using client credentials string tenantName = "your-tenant-name.onmicrosoft.com"; string authString = "https://login.microsoftonline.com/" + tenantName; AuthenticationContext authenticationContext = new AuthenticationContext(authString, false); // Config for OAuth client credentials string clientId = "your-client-id"; string key = "your-AzureAD-App-Key"; ClientCredential clientCred = new ClientCredential(clientId, key); string resource = "https://graph.windows.net"; AuthenticationResult authenticationResult; try { authenticationResult = await authenticationContext.AcquireTokenAsync(resource, clientCred); } catch(Exception ex) { throw new Exception(ex.Message, ex.InnerException); } var client = new HttpClient(); var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, "https://graph.windows.net/your-tenant-name.onmicrosoft.com/users?api-version=1.6"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken); var response = await client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); }
One other huge gotcha that you may find that I ran into and several forums are discussing is if you get a Authorization_Request_Denied error or Insufficient_Permissions error. This is resolved by running a PowerShell command to give the application you registered with Azure AD "Administrator" permissions. Requests to MS Graph API gives me "Authorization Request Denied - Insufficient privileges to complete the operation"
The powershell command you want to run is
Connect-MsolService $ClientIdWebApp = '{your_AD_application_client_id}' $webApp = Get-MsolServicePrincipal –AppPrincipalId $ClientIdWebApp #use Add-MsolRoleMember to add it to "Company Administrator" role). Add-MsolRoleMember -RoleName "Company Administrator" -RoleMemberType ServicePrincipal -RoleMemberObjectId $webApp.ObjectId
Hopefully this helps. Let me know if you think any refining needs to be made.
Code is much simpler with Graph client
var serviceRoot = new Uri(@"https://graph.windows.net/"+ tenantID); var activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, () => Task.FromResult(authenticationResult.AccessToken)); // Fetch more user details from the Graph var user = await activeDirectoryClient.Users.GetByObjectId(userObjectID).ExecuteAsync(); // fetch all groups (DG + SG) and roles transitively for the user var userGroups = await user.GetMemberObjectsAsync(securityEnabledOnly: false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With