skip to Main Content

I am using Azure Identity client SDK dotnet 1.10.4 and clientsecretcredential class to generate a token to read from my blob. I followed the list blob in container sample in this link

https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blobs-list

I am getting the following error

Azure.Identity.AuthenticationFailedException: ClientSecretCredential authentication failed: Method not found: ‘Void System.Text.Json.Serialization.Metadata.JsonObjectInfoValues1.set_ObjectCreator(System.Func1<!0>)’.
—> System.MissingMethodException: Method not found: ‘Void System.Text.Json.Serialization.Metadata.JsonObjectInfoValues1.set_ObjectCreator(System.Func1<!0>)’.
at Microsoft.Identity.Client.Platforms.net6.MsalJsonSerializerContext.get_InstanceDiscoveryResponse()
at Microsoft.Identity.Client.Platforms.net6.MsalJsonSerializerContext.GetTypeInfo(Type type)
at System.Text.Json.JsonSerializer.GetTypeInfo(JsonSerializerContext context, Type inputType)
at System.Text.Json.JsonSerializer.Deserialize(String json, Type returnType, JsonSerializerContext context)
at Microsoft.Identity.Client.Utils.JsonHelper.DeserializeFromJson[T](String json)
at Microsoft.Identity.Client.OAuth2.OAuth2Client.CreateResponse[T](HttpResponse response, RequestContext requestContext)
at Microsoft.Identity.Client.OAuth2.OAuth2Client.ExecuteRequestAsync[T](Uri endPoint, HttpMethod method, RequestContext requestContext, Boolean expectErrorsOn200OK, Boolean addCommonHeaders, Func2 onBeforePostRequestData) at Microsoft.Identity.Client.OAuth2.OAuth2Client.DiscoverAadInstanceAsync(Uri endpoint, RequestContext requestContext) at Microsoft.Identity.Client.Instance.Discovery.NetworkMetadataProvider.SendInstanceDiscoveryRequestAsync(Uri authority, RequestContext requestContext) at Microsoft.Identity.Client.Instance.Discovery.NetworkMetadataProvider.FetchAllDiscoveryMetadataAsync(Uri authority, RequestContext requestContext) at Microsoft.Identity.Client.Instance.Discovery.NetworkMetadataProvider.GetMetadataAsync(Uri authority, RequestContext requestContext) at Microsoft.Identity.Client.Instance.Discovery.InstanceDiscoveryManager.FetchNetworkMetadataOrFallbackAsync(RequestContext requestContext, Uri authorityUri) at Microsoft.Identity.Client.Instance.Discovery.InstanceDiscoveryManager.GetMetadataEntryAsync(AuthorityInfo authorityInfo, RequestContext requestContext, Boolean forceValidation) at Microsoft.Identity.Client.Instance.AuthorityManager.RunInstanceDiscoveryAndValidationAsync() at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.GetAccessTokenAsync(CancellationToken cancellationToken, ILoggerAdapter logger) at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.ExecuteAsync(CancellationToken cancellationToken) at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken) at Microsoft.Identity.Client.ApiConfig.Executors.ConfidentialClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenForClientParameters clientParameters, CancellationToken cancellationToken) at Azure.Identity.AbstractAcquireTokenParameterBuilderExtensions.ExecuteAsync[T](AbstractAcquireTokenParameterBuilder1 builder, Boolean async, CancellationToken cancellationToken)
at Azure.Identity.MsalConfidentialClient.AcquireTokenForClientCoreAsync(String[] scopes, String tenantId, Boolean enableCae, Boolean async, CancellationToken cancellationToken)
at Azure.Identity.MsalConfidentialClient.AcquireTokenForClientAsync(String[] scopes, String tenantId, Boolean enableCae, Boolean async, CancellationToken cancellationToken)
at Azure.Identity.ClientSecretCredential.GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
— End of inner exception stack trace —
at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String additionalMessage, Boolean isCredentialUnavailable)
at Azure.Identity.ClientSecretCredential.GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.AccessTokenCache.GetHeaderValueFromCredentialAsync(TokenRequestContext context, Boolean async, CancellationToken cancellationToken)
at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.AccessTokenCache.GetHeaderValueAsync(HttpMessage message, TokenRequestContext context, Boolean async)
at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.AccessTokenCache.GetHeaderValueAsync(HttpMessage message, TokenRequestContext context, Boolean async)
at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.AuthenticateAndAuthorizeRequestAsync(HttpMessage message, TokenRequestContext context)
at Azure.Storage.StorageBearerTokenChallengeAuthorizationPolicy.AuthorizeRequestInternal(HttpMessage message, Boolean async)
at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory1 pipeline, Boolean async) at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.InnerProcessAsync(HttpMessage message, ReadOnlyMemory1 pipeline)
at Azure.Core.Pipeline.RedirectPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory1 pipeline, Boolean async) at Azure.Core.Pipeline.RetryPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory1 pipeline, Boolean async)
at Azure.Core.Pipeline.RetryPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory1 pipeline, Boolean async) at Azure.Storage.Blobs.ContainerRestClient.ListBlobFlatSegmentAsync(String prefix, String marker, Nullable1 maxresults, IEnumerable1 include, Nullable1 timeout, CancellationToken cancellationToken)
at Azure.Storage.Blobs.BlobContainerClient.GetBlobsInternal(String marker, BlobTraits traits, BlobStates states, String prefix, Nullable1 pageSizeHint, Boolean async, CancellationToken cancellationToken) at Azure.Storage.Blobs.Models.GetBlobsAsyncCollection.GetNextPageAsync(String continuationToken, Nullable1 pageSizeHint, Boolean async, CancellationToken cancellationToken)
at Azure.Storage.StorageCollectionEnumerator1.StorageAsyncPageable.AsPages(String continuationToken, Nullable1 pageHintSize)+MoveNext()
at Azure.Storage.StorageCollectionEnumerator1.StorageAsyncPageable.AsPages(String continuationToken, Nullable1 pageHintSize)+System.Threading.Tasks.Sources.IValueTaskSource<System.Boolean>.GetResult()

below is my code

”’

     var tenantId = tenantid;
     var clientId = ClientId;
     var clientSecret = clientSecret;
     var credential = new Azure.Identity.ClientSecretCredential(
        tenantId,
        clientId,
        clientSecret,
        new TokenCredentialOptions
        {
            AuthorityHost = new Uri("https://login.microsoftonline.com")
        });



    Console.WriteLine($"credential object {credential}");

   var  blobServiceClient = new 
    BlobServiceClient(new Uri($"https://<storageaccountname>.blob.core.windows.net"),credential)
    ;
   


    Console.WriteLine(blobServiceClient);

    //Console.WriteLine(blobcontainerClient);

var blobcontainerClient = blobServiceClient.GetBlobContainerClient("containername");

Console.WriteLine(blobcontainerClient);

int? segmentSize = null;



   // Call the listing operation and return pages of the specified size.
    var resultSegment = blobcontainerClient.GetBlobsAsync()
        .AsPages(default, segmentSize);

    // Enumerate the blobs returned for each page.

    try
    {
    ***await foreach (Azure.Page<BlobItem> blobPage in resultSegment)***
    {
        foreach (BlobItem blobItem in blobPage.Values)
        {
            Console.WriteLine("Blob name: {0}", blobItem.Name);
        }

        Console.WriteLine("all complete");
    }
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex);
    }

”’

I get the exception at the await foreach line. This is the same line from the learn.microsoft link sample.

Any pointers and help are much appreciated.

2

Answers


  1. Chosen as BEST ANSWER

    i got the think working. The problem was

    1. I was running in .NET 7 which i think has some issues in handling the token response. I got to this conclusion by removing my apps permission fully and expected to get a different error such as 401/403. I still got method not found. I then changed the targetframework to .NET 8. Now I get 403 because by this time I added storageaccount.contributor role to my app. 403 is an expected error but this the error was more descriptive.

    So .NET 7 is the problem for me no problem with the code.

    Thanks @venkatesan for trying to run the code in your setup.


  2. Azure.Identity.AuthenticationFailedException: ClientSecretCredential authentication failed: Method not found: ‘Void System.Text.Json.Serialization.Metadata.JsonObjectInfoValues1.set_ObjectCreator(System.Func1<!0>)’. —> System.MissingMethodException:

    The error may be due to an incorrect or mismatched dependency for authentication between the blob package and identity package.

    In my environment, I have both updated packages with their respective versions.

    Version:

    <ItemGroup>
      <PackageReference Include="Azure.Identity" Version="1.10.4" />
      <PackageReference Include="Azure.Storage.Blobs" Version="12.19.1" />
    </ItemGroup>
    

    Now, using the updated version, I can list the blobs using ClientSecretCredential authentication.

    Code:

    using Azure.Identity;
    using Azure.Storage.Blobs;
    using Azure.Storage.Blobs.Models;
    
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var tenantId = "<Your tenant -id>";
            var clientId = "<Your client-id>";
            var clientSecret = "xxxxx";
            var options = new TokenCredentialOptions
            {
                AuthorityHost = new Uri("https://login.microsoftonline.com")
            };
            var credential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
            
            Console.WriteLine($"credential object {credential}");
    
            var blobServiceClient = new
             BlobServiceClient(new Uri($"https://<storageaccountname>.blob.core.windows.net"), credential)
             ;
            Console.WriteLine(blobServiceClient);
            var blobcontainerClient = blobServiceClient.GetBlobContainerClient("test");
            Console.WriteLine(blobcontainerClient);
            int? segmentSize = null;
            var resultSegment = blobcontainerClient.GetBlobsAsync()
                .AsPages(default, segmentSize);
            try
            {
                await foreach (Azure.Page<BlobItem> blobPage in resultSegment)
                {
                    foreach (BlobItem blobItem in blobPage.Values)
                    {
                        Console.WriteLine("Blob name: {0}", blobItem.Name);
                    }
    
                    Console.WriteLine("all complete");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
    

    Output:

    credential object Azure.Identity.ClientSecretCredential
    Azure.Storage.Blobs.BlobServiceClient
    Azure.Storage.Blobs.BlobContainerClient
    Blob name: jgs.html
    Blob name: sample.pdf
    Blob name: sample.txt
    Blob name: temp.png
    all complete
    

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search