Error when trying to read custom seccurity attribute assignments using graph sdk in C#

Renezeder Markus 20 Reputation points
2023-03-20T11:50:03.5866667+00:00

If I try to read custom security attribute assignments using the graph sdk in C# (like the example https://learn.microsoft.com/en-us/graph/custom-security-attributes-examples?tabs=csharp "List custom security attribute assignments") I run into an error.

There is no meaningful error message and just returns error 500:

Microsoft.Graph.Models.ODataErrors.ODataError: Exception of type 'Microsoft.Graph.Models.ODataErrors.ODataError' was thrown.
   at Microsoft.Kiota.Http.HttpClientLibrary.HttpClientRequestAdapter.ThrowIfFailedResponse(HttpResponseMessage response, Dictionary`2 errorMapping, Activity activityForAttributes)
   at Microsoft.Kiota.Http.HttpClientLibrary.HttpClientRequestAdapter.SendAsync[ModelType](RequestInformation requestInfo, ParsableFactory`1 factory, Dictionary`2 errorMapping, CancellationToken cancellationToken)
   at Microsoft.Kiota.Http.HttpClientLibrary.HttpClientRequestAdapter.SendAsync[ModelType](RequestInformation requestInfo, ParsableFactory`1 factory, Dictionary`2 errorMapping, CancellationToken cancellationToken)
   at Microsoft.Graph.Users.Item.UserItemRequestBuilder.GetAsync(Action`1 requestConfiguration, CancellationToken cancellationToken)
   at Program.<Main>$(String[] args) in C:\Projects\TestGraph\TestGraph\Program.cs:line 27

Here is the code I use:

using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;

var scopes = new[] { "https://graph.microsoft.com/.default" };

var tenantId = "<tenantId>";

var clientId = "<clientid>";
var clientSecret = "<clientsecret>";

var options = new TokenCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};

var clientSecretCredential = new ClientSecretCredential(
    tenantId, clientId, clientSecret, options);

var client = new GraphServiceClient(clientSecretCredential, scopes);

string userid = "<userid>";


try
{
    var user = await client.Users[userid].GetAsync(
                        requestConfiguration =>
                        {
                            requestConfiguration.QueryParameters.Select = new string[] { "customSecurityAttributes" };
                        }
                    );

    Console.WriteLine("success");
}
catch(Exception ex)
{
    Console.WriteLine(ex.ToString());
}

If there is no custom security attribute assigned to the user, it works without an error.

I'm using Azure.Identity 1.8.2 and Microsoft.Graph 5.2.0

The app registration has assigned the following API permissions:

  • CustomSecAttributeAssignment.ReadWrite.All (Application)
  • CustomSecAttributeDefinition.ReadWrite.All (Application)
  • Directory.Read.All (Delegated and Application)
  • Group.Read.All (Application)
  • GroupMember.Read.All (Application)
  • User.Read (Delegated)
  • User.Read.All (Application)
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,553 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,221 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,435 questions
0 comments No comments
{count} votes

Accepted answer
  1. CarlZhao-MSFT 36,891 Reputation points
    2023-03-21T10:08:53.1866667+00:00

    Hi @Renezeder Markus

    The customSecurityAttributes is not a basic property and it is only returned in beta versions, so make sure your project downloads the graph beta package. Referring to my code, I've tested it locally and it works fine.

    dotnet add package Microsoft.Graph.Beta --version 5.22.0-preview
    
    using Azure.Identity;
    using Microsoft.Graph.Beta;
    using Microsoft.Graph.Models.ODataErrors;
    using Newtonsoft.Json;
     
    var scopes = new[] { "https://graph.microsoft.com/.default" };
     
    var tenantId = "{tenant id}";
     
    // Values from app registration
    var clientId = "{client id}";
    var clientSecret = "{client secret}";
     
    // using Azure.Identity;
    var options = new TokenCredentialOptions
    {
          AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
    };
     
    // https://docs.microsoft.com/dotnet/api/azure.identity.clientsecretcredential
    var clientSecretCredential = new ClientSecretCredential(
          tenantId, clientId, clientSecret, options);
      
    GraphServiceClient graphServiceClient = new GraphServiceClient(clientSecretCredential, scopes);
     
    try
    {
          var user = await graphServiceClient.Users["2b430883-a319-4218-837f-fa774724ff81"].GetAsync(
                              requestConfiguration =>
                              {
                                    requestConfiguration.QueryParameters.Select = new string[] { "customSecurityAttributes" };
                              }
                        );
     
          Console.WriteLine(JsonConvert.SerializeObject(user));
    }
    catch (ODataError odataError)
    {
          Console.WriteLine(odataError.Error.Code);
          Console.WriteLine(odataError.Error.Message);
    }
    

    User's image

    Hope this helps.

    If the reply is helpful, please click Accept Answer and kindly upvote it. If you have additional questions about this answer, please click Comment.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. CarlZhao-MSFT 36,891 Reputation points
    2023-03-21T08:24:33.7766667+00:00

    Hi @Renezeder Markus

    The Microsoft Graph .NET SDK v5 has made some changes to error handling, and errors and exceptions from the new generated version will be exception classed derived from the ApiException class from the Kiota abstrations library. Typically, this will be an instance of OdataError, and you can print the exception as follows:

    using Microsoft.Graph.Models.ODataErrors;
    
    
    try
    {
        var result = await client.Users[userid].GetAsync(
                            requestConfiguration =>
                            {
                                requestConfiguration.QueryParameters.Select = new string[] { "customSecurityAttributes" };
                            }
                        );
    
        Console.WriteLine(result);
    }
    catch (ODataError odataError)
    {
        Console.WriteLine(odataError.Error.Code);
        Console.WriteLine(odataError.Error.Message);
    }
    
    

    Hope this helps.

    If the reply is helpful, please click Accept Answer and kindly upvote it. If you have additional questions about this answer, please click Comment.