|
| 1 | +using System.Threading.Tasks; |
| 2 | +using Microsoft.Graph; |
| 3 | +using System; |
| 4 | +using System.Collections.Generic; |
| 5 | +using Microsoft.AspNetCore.Authentication.OpenIdConnect; |
| 6 | +using Microsoft.Extensions.DependencyInjection; |
| 7 | +using System.IdentityModel.Tokens.Jwt; |
| 8 | +using System.Security.Claims; |
| 9 | +using System.Linq; |
| 10 | + |
| 11 | +namespace WebApp_OpenIDConnect_DotNet.Services.GroupProcessing |
| 12 | +{ |
| 13 | + public class GraphHelper |
| 14 | + { |
| 15 | + /// <summary> |
| 16 | + /// Adds groups claim for group overage |
| 17 | + /// </summary> |
| 18 | + /// <param name="context">TokenValidatedContext</param> |
| 19 | + public static async Task ProcessGroupsClaimforAccessToken(TokenValidatedContext context) |
| 20 | + { |
| 21 | + try |
| 22 | + { |
| 23 | + //Checks if the token contains 'Group Overage' Claim. |
| 24 | + if (context.Principal.Claims.Any(x => x.Type == "hasgroups" || (x.Type == "_claim_names" && x.Value == "{\"groups\":\"src1\"}"))) |
| 25 | + { |
| 26 | + //This API should have permission set for Microsoft graph: 'GroupMember.Read.All' |
| 27 | + var graph = context.HttpContext.RequestServices.GetService<GraphServiceClient>(); |
| 28 | + |
| 29 | + if (graph == null) |
| 30 | + { |
| 31 | + Console.WriteLine("No service for type 'Microsoft.Graph.GraphServiceClient' has been registered."); |
| 32 | + } |
| 33 | + else if (context.SecurityToken != null) |
| 34 | + { |
| 35 | + if (!context.HttpContext.Items.ContainsKey("JwtSecurityTokenUsedToCallWebAPI")) |
| 36 | + { |
| 37 | + //Added current access token in below key to get Access Token on-behalf of user. |
| 38 | + context.HttpContext.Items.Add("JwtSecurityTokenUsedToCallWebAPI", context.SecurityToken as JwtSecurityToken); |
| 39 | + } |
| 40 | + //Specify the property names in the 'select' variable to get values for the specified properties. |
| 41 | + string select = "id,displayName,onPremisesNetBiosName,onPremisesDomainName,onPremisesSamAccountNameonPremisesSecurityIdentifier"; |
| 42 | + |
| 43 | + //Request to get groups and directory roles that the user is a direct member of. |
| 44 | + var memberPage = await graph.Me.MemberOf.Request().Select(select).GetAsync().ConfigureAwait(false); |
| 45 | + |
| 46 | + if (memberPage?.Count > 0) |
| 47 | + { |
| 48 | + //There is a limit to number of groups returned, below method make calls to Microsoft graph to get all the groups. |
| 49 | + var allgroups = ProcessIGraphServiceMemberOfCollectionPage(memberPage); |
| 50 | + |
| 51 | + if (allgroups?.Count > 0) |
| 52 | + { |
| 53 | + var identity = (ClaimsIdentity)context.Principal.Identity; |
| 54 | + |
| 55 | + if (identity != null) |
| 56 | + { |
| 57 | + //Remove existing groups claims |
| 58 | + RemoveExistingClaims(context, identity); |
| 59 | + |
| 60 | + List<Claim> groupClaims = new List<Claim>(); |
| 61 | + |
| 62 | + foreach (Group group in allgroups) |
| 63 | + { |
| 64 | + //Claim is added in list and it can be used by saving the groups in session or as per project implementation. |
| 65 | + //Adds group id as 'groups' claim. But it can be changed as per requirment. |
| 66 | + //For instance if the required format is 'NetBIOSDomain\sAMAccountName' then the code is as commented below: |
| 67 | + //groupClaims.AddClaim(new Claim("groups", group.OnPremisesNetBiosName+"\\"+group.OnPremisesSamAccountName)); |
| 68 | + groupClaims.Add(new Claim("groups", group.Id)); |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + catch (Exception ex) |
| 77 | + { |
| 78 | + Console.WriteLine(ex.Message); |
| 79 | + } |
| 80 | + finally |
| 81 | + { |
| 82 | + if (context.HttpContext.Items.ContainsKey("JwtSecurityTokenUsedToCallWebAPI")) |
| 83 | + { |
| 84 | + //Remove the key as Microsoft.Identity.Web library utilizes this key. |
| 85 | + //If not removed then it can cause failure to the application. |
| 86 | + context.HttpContext.Items.Remove("JwtSecurityTokenUsedToCallWebAPI"); |
| 87 | + } |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + /// <summary> |
| 92 | + /// Remove groups claims if already exists. |
| 93 | + /// </summary> |
| 94 | + /// <param name="context"></param> |
| 95 | + /// <param name="identity"></param> |
| 96 | + private static void RemoveExistingClaims(TokenValidatedContext context, ClaimsIdentity identity) |
| 97 | + { |
| 98 | + //clear existing claim |
| 99 | + List<Claim> existingGroupsClaims = context.Principal.Claims.Where(x => x.Type == "groups").ToList(); |
| 100 | + if (existingGroupsClaims?.Count > 0) |
| 101 | + { |
| 102 | + foreach (Claim groupsClaim in existingGroupsClaims) |
| 103 | + { |
| 104 | + identity.RemoveClaim(groupsClaim); |
| 105 | + } |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + /// <summary> |
| 110 | + /// Returns all the groups that the user is a direct member of. |
| 111 | + /// </summary> |
| 112 | + /// <param name="membersCollectionPage">First page having collection of directory roles and groups</param> |
| 113 | + /// <returns>List of groups</returns> |
| 114 | + private static List<Group> ProcessIGraphServiceMemberOfCollectionPage(IUserMemberOfCollectionWithReferencesPage membersCollectionPage) |
| 115 | + { |
| 116 | + List<Group> allGroups = new List<Group>(); |
| 117 | + |
| 118 | + try |
| 119 | + { |
| 120 | + if (membersCollectionPage != null) |
| 121 | + { |
| 122 | + do |
| 123 | + { |
| 124 | + // Page through results |
| 125 | + foreach (DirectoryObject directoryObject in membersCollectionPage.CurrentPage) |
| 126 | + { |
| 127 | + //Collection contains directory roles and groups of the user. |
| 128 | + //Checks and adds groups only to the list. |
| 129 | + if (directoryObject is Group) |
| 130 | + { |
| 131 | + allGroups.Add(directoryObject as Group); |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + // are there more pages (Has a @odata.nextLink ?) |
| 136 | + if (membersCollectionPage.NextPageRequest != null) |
| 137 | + { |
| 138 | + membersCollectionPage = membersCollectionPage.NextPageRequest.GetAsync().Result; |
| 139 | + } |
| 140 | + else |
| 141 | + { |
| 142 | + membersCollectionPage = null; |
| 143 | + } |
| 144 | + } while (membersCollectionPage != null); |
| 145 | + } |
| 146 | + } |
| 147 | + catch (ServiceException ex) |
| 148 | + { |
| 149 | + Console.WriteLine($"We could not process the groups list: {ex}"); |
| 150 | + return null; |
| 151 | + } |
| 152 | + return allGroups; |
| 153 | + } |
| 154 | + } |
| 155 | +} |
0 commit comments