Skip to content

[Bug] NullReferenceException when using Microsoft Graph (AppOnly) within IHostedService or anonymous web app controllersΒ #1372

Closed

Description

@Trancesphere

Which version of Microsoft Identity Web are you using?
1.15.2

Where is the issue?

  • Web app
    • Sign-in users
    • Sign-in users and call web APIs
  • Web API
    • Protected web APIs (validating tokens)
    • Protected web APIs (validating scopes)
    • Protected web APIs call downstream web APIs
  • Token cache serialization
    • In-memory caches
    • Session caches
    • Distributed caches
  • Other (please describe)

Is this a new or an existing app?
The app is in production (using 1.10.0) and I have upgraded to a new version of Microsoft Identity Web.

Repro

Debug Launch is set to Project.
Launch Browser is unticked.

The below code works fine with 1.10.0.
Anything above 1.10.0 (1.11-1.15.2) throws a NullReferenceException.

Startup.cs

        services.AddMicrosoftIdentityWebApiAuthentication(Configuration)
           .EnableTokenAcquisitionToCallDownstreamApi()
           .AddMicrosoftGraphAppOnly(authProvider => new GraphServiceClient(authProvider))
           .AddInMemoryTokenCaches();

Shortened code from IHostedService:

    private async void DoWork(object state)
    {
        using (var scope = Services.CreateScope())
        {
            var graphClient =
                scope.ServiceProvider
                    .GetRequiredService<GraphServiceClient>();

            var users = await graphClient.Users.Request().GetAsync();
        }
    }

Expected behavior
Return the list of users within Azure AD using Graph App Only

Actual behavior

System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Identity.Web.MergedOptions.PrepareAuthorityInstanceForMsal()
at Microsoft.Identity.Web.TokenAcquisition.BuildConfidentialClientApplication(MergedOptions mergedOptions)
at Microsoft.Identity.Web.TokenAcquisition.GetOrBuildConfidentialClientApplication(MergedOptions mergedOptions)
at Microsoft.Identity.Web.TokenAcquisition.GetAuthenticationResultForAppAsync(String scope, String authenticationScheme, String tenant, TokenAcquisitionOptions tokenAcquisitionOptions)
at Microsoft.Identity.Web.TokenAcquisitionAuthenticationProvider.AuthenticateRequestAsync(HttpRequestMessage request) at Microsoft.Graph.AuthenticationHandler.SendAsync(HttpRequestMessage httpRequestMessage, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancellationToken cancellationToken)
at Microsoft.Graph.HttpProvider.SendRequestAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at Microsoft.Graph.HttpProvider.SendRequestAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
at Microsoft.Graph.HttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
at Microsoft.Graph.BaseRequest.SendRequestAsync(Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
at Microsoft.Graph.BaseRequest.SendAsync[T](Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
at Microsoft.Graph.GraphServiceUsersCollectionRequest.GetAsync(CancellationToken cancellationToken)
at TestProject.BackgroundServices.TimedDirectorySynchroniserService.DoWork(Object state) in C:\Users\User\source\repos\TestProject\TestProject\BackgroundServices\TimedDirectorySynchroniserService.cs:line 48

Possible solution

Additional context / logs / screenshots

Activity

  1. paolovalladolid commented on Aug 6, 2021

    @paolovalladolid

    I am getting the same exception and stack trace. In my case, this is happening in a console app.

    Excerpt from Main method of the console app:

    var config = new ConfigurationBuilder()
            .AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true).Build();
    
    var builder = new HostBuilder().ConfigureServices((hostContext, services) =>
    {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                   .AddMicrosoftIdentityWebApi(config.GetSection("AzureAd"))
                       .EnableTokenAcquisitionToCallDownstreamApi()
                           .AddMicrosoftGraph(config.GetSection("DownstreamApi"))
                           .AddInMemoryTokenCaches();
     }).UseConsoleLifetime();
    

    Method that calls Azure using GraphServiceClient

    public async Task<Microsoft.Graph.Application> GetServiceFromAzureAsync(string serviceId)
    {
          var filterString = $"tags/any(c:c eq 'ThreescaleServiceId:{serviceId}')";
    
          var results = await graphClient.Applications.Request()
              .Filter(filterString)
              .GetAsync();
    }
    
  2. jennyf19 commented on Aug 11, 2021

    @jennyf19
    Collaborator

    paolovalladolid do you have a working repo or link to code that i can download and run locally?

  3. paolovalladolid commented on Aug 12, 2021

    @paolovalladolid

    paolovalladolid do you have a working repo or link to code that i can download and run locally?

    jennyf19 I have created a repo for a simple console app that demonstrates the issue with using GraphServiceClient with the IoC framework. Plug in your Azure settings into the appsettings.json of course.

    https://github.com/paolovalladolid/PVSimpleMSGraphConsole

  4. jennyf19 commented on Aug 17, 2021

    @jennyf19
    Collaborator

    paolovalladolid

    1. How do you add the authorization and authentication middleware? (app.UseAuthentication(); and app.UseAuthorization();) ?

      app.UseAuthentication();
      app.UseAuthorization();

    2. If you request an app only scope, you want to apply .WithAppOnly() to the request:

       var results = await graphClient.Applications.Request()
                   .WithAppOnly()
                   .Filter(filterString)
                   .GetAsync();
  5. paolovalladolid commented on Aug 17, 2021

    @paolovalladolid

    jennyf19 I tried to make the suggested code changes but am having a hard time pushing my changes to GitHub because I can't get my new token to work with GitHub. I modified the classes as follows. I still get the same stack trace:

    class Program
      {
        public static async Task Main(string[] args)
        {
          Console.WriteLine("Hello World!");
    
          var services = Startup.ConfigureServices();
          var serviceProvider = services.BuildServiceProvider();
    
          Console.WriteLine("My MSGraph app configuration loaded. Begin call to Azure...");
    
          var msapp = await GetServiceFromAzureAsync(serviceProvider);
        }
    
        public static async Task<Microsoft.Graph.Application> GetServiceFromAzureAsync(IServiceProvider injectedProvider)
        {
    
          var serviceId =  2555417833004;
          var filterString = $"tags/any(c:c eq 'ThreescaleServiceId:{serviceId}')";
    
          using IServiceScope serviceScope = injectedProvider.CreateScope();
          IServiceProvider provider = serviceScope.ServiceProvider;
    
          var graphClient = provider.GetRequiredService<GraphServiceClient>();
    
          var results = await graphClient.Applications.Request()
              .WithAppOnly()
              .Filter(filterString)
              .GetAsync();
    
          return results.First();
        }
      }
    
    public static class Startup
      {
        public static IServiceCollection ConfigureServices()
        {
          var services = new ServiceCollection();
    
          var config = new ConfigurationBuilder()
          .AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true)
          .Build();
    
          services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                  .AddMicrosoftIdentityWebApi(config.GetSection("AzureAd"))
                      .EnableTokenAcquisitionToCallDownstreamApi()
                          .AddMicrosoftGraph(config.GetSection("DownstreamApi"))
                          .AddInMemoryTokenCaches();
    
          return services;
        }
    
        public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
          app.UseAuthentication();
          app.UseAuthorization();
        }
      }
  6. jmprieur commented on Aug 20, 2021

    @jmprieur
    Collaborator

    Thanks @mrfrankbell
    I see, so it's not really a protected web API, paolovalladolid ?

  7. 12 remaining items

  8. jennyf19 commented on Aug 27, 2021

    @jennyf19
    Collaborator

    I tried to repro this with an anonymous controller and a GRPC service, but could not get the same error. MaxxDelusional could you provide a repro?

  9. MaxxDelusional commented on Aug 27, 2021

    @MaxxDelusional

    I suspect that I am probably doing something wrong.

    In any case, here is a simplified repo. You'll need to modify appsettings.json, and specify a userId in TestController.

    https://github.com/MaxxDelusional/IdentityWebTest

  10. jennyf19 commented on Aug 27, 2021

    @jennyf19
    Collaborator

    Thanks for the repro MaxxDelusional, was very helpful. We have a bug when using an anonymous controller, but as a work around, you can specify the auth scheme in the TestController and things should work:

    var request = await _graphServiceClient.Users[userId].Photo.Content
                    .Request()
                    .WithAppOnly()
                    .WithAuthenticationScheme(JwtBearerDefaults.AuthenticationScheme)
                    .GetAsync();

    also, in Startup.cs, you need to include:

    app.UseAuthentication();

    to set up all the middleware correctly.

    Jean-Marc Prieur (@jmprieur) we need to do something better here for when we don't have the token but it is a web API.

  11. mrichards3 commented on Aug 27, 2021

    @mrichards3

    Thanks jennyf19. We were having this same issue using IDownstreamWebApi.CallWebApiForAppAsync from an anonymous controller since version 1.10.

    Adding app.UseAuthentication(), and then also explicitly passing the authentication scheme like this avoids the NullReferenceException:

    var value = await _downstreamWebApi.CallWebApiForAppAsync(
                    "SecureService",
                    // Need to explicitly pass the authentication scheme here
                    JwtBearerDefaults.AuthenticationScheme,
                    options =>
                    {
                        ...
                    });
    
  12. jmprieur commented on Aug 27, 2021

    @jmprieur
    Collaborator

    Thanks for the investigation and the heads-up jennyf19
    Maybe we should leverage IAuthenticationSchemeProvider.GetDefaultAuthenticateSchemeAsync in ITokenAcquisition?

  13. jennyf19 commented on Aug 29, 2021

    @jennyf19
    Collaborator

    MaxxDelusional paolovalladolid Trancesphere the fix is in master if you want to try it out. will be in next release, possibly next week or week after (1st/2nd week of sept).

  14. modified the milestones: 1.16, 1.16.1 on Sep 3, 2021
  15. jennyf19 commented on Sep 6, 2021

    @jennyf19
    Collaborator

    Included in 1.16.1 release

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions