Working around custom security attribute limitations in .NET Graph SDK

Microsoft Graph SDK uses Kiota for serialization of generic objects from Graph, and this currently causes major headaches. I wanted to get two custom security attributes (CSAs) for my users, namely “personalinformation” attribute set and “firstname” and “lastname”, but the generic AdditionalData dictionary for CustomSecurityAttributes on Microsoft.Graph.Models.User was litterally impossible to use, even though the values were present i non-public members (_Properties). The issue is documented on github .

The solution I came up with is not optimal but works:

internal class DefaultStudentDisplayNameHandler : IStudentDisplayNameHandler
    {
        public string GetDisplayName(User user)
        {
            // Check whether CSA is present and return that
            if(user.CustomSecurityAttributes != null) {
                if(user.CustomSecurityAttributes.AdditionalData.ContainsKey("personalinformation")) {
                    var personalInformation = (UntypedNode) user.CustomSecurityAttributes.AdditionalData["personalinformation"];

                    // This is a somewhat funky workaround for this issue: https://github.com/microsoftgraph/msgraph-sdk-dotnet/issues/2442
                    var tempJson = KiotaJsonSerializer.SerializeAsString(personalInformation);
                    var asDict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(tempJson);

                    if(asDict != null && asDict.TryGetValue("lastname", out var lastname) && asDict.TryGetValue("firstname", out var firstname)) {
                        return $"{firstname} {lastname}";
                    }
                }
            }
            
            return user.DisplayName ?? user.Id ?? "Unknown";
        }
    }

Essentially – serialize to json and deserialize back into a Dictionary<string,object>. Hope this solution helps someone to not spend 2 hours crawling the web with no luck.

Leave a comment