Skip to content

Error GetAccessTokenForAppAsync Exception thrown: 'System.NullReferenceException' in System.Private.CoreLib.dll #2410

Closed

Description

Microsoft.Identity.Web Library

Microsoft.Identity.Web

Microsoft.Identity.Web version

2.13.3

Web app

Sign-in application and call web APIs

Web API

Protected web APIs call downstream web APIs

Token cache serialization

In-memory caches

Description

Iam building a console app in dotnet core that consume a protected webapi. Since I upgraded to 2.13.3 tokenresult thrown an exception "Exception thrown: 'System.NullReferenceException' in System.Private.CoreLib.dll" Object reference not set to an instance of an object.

public async Task<string> GetAuthenticationForClientResultAsync(string appId)
    {
        try
        {
            var tokenresult = await _tokenAcquisition.GetAccessTokenForAppAsync(
                $"{appId}/.default"
            );

            return tokenresult;
        }
        catch (Exception ex)
        {
            _consentHandler.HandleException(ex);
        }

        return null;
    }

Reproduction steps

Here is how Iam starting the console app with dependancy injection. I think it might be the cause of my issue but I dont know enough to explain why.

using gcb_libs.Services;
using gcb_taskscheduler;
using gcb_taskschudler.Jobs;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Web;
using Quartz;
using System.IO;

var configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", true, false)
    .AddEnvironmentVariables()
    .AddUserSecrets<Program>()
    .Build();


var host = Host.CreateDefaultBuilder()
    .ConfigureServices(
        (context, services) =>
        {
            services.AddSingleton<IConfiguration>(configuration);
            services
                .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(configuration.GetSection("AzureAd"))
                .EnableTokenAcquisitionToCallDownstreamApi()
                .AddInMemoryTokenCaches();
            services.AddMicrosoftIdentityConsentHandler();
            services.AddScoped<AzureAuthTokenService>();
            services.AddScoped<LogService>();
            services.AddScoped<ScheduledJobService>();
            services.AddHostedService<WorkerService>();
        }
    )
    .Build();

host.Run();

Error message

{"Object reference not set to an instance of an object."}

Id Web logs

No response

Relevant code snippets

tokenresult is always null. 

  var tokenresult = await _tokenAcquisition.GetAccessTokenForAppAsync(
                $"{appId}/.default"
            );

Regression

2.13.2

Expected behavior

It should return the token

Activity

  1. emmanuelpare commented on Aug 30, 2023

    @emmanuelpare
    Author

    it might be a duplicate of #2394

  2. jmprieur commented on Aug 30, 2023

    @jmprieur
    Collaborator

    thanks Emmanuel Pare (@emmanuelpare)
    Do you have a call stack for the exception?

    I see that you wrote
    AddAuthentication(JwtBearerDefaults.AuthenticationScheme), but you are building a web app.
    So it should be:

    AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)

    I would recommend you use:

    .AddTokenAcquisition()

    instead of the following:

                    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .AddMicrosoftIdentityWebApp(configuration.GetSection("AzureAd"))
                    .EnableTokenAcquisitionToCallDownstreamApi()

    I think this should fix your issue.

    _

    Aside, I think we've introduced a bug in 2.13.3, indeed, (by not using the ASP.NET Core token TokenAcquisition, but the default token acquisition): I had not anticipated that you could use AddMicrosoftWebApp without really needing a web app :-).

  3. emmanuelpare commented on Aug 30, 2023

    @emmanuelpare
    Author

    Here the stacktrace
    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.TokenAcquisition.d__17.MoveNext()
    at gcb_libs.Services.AzureAuthTokenService.d__5.MoveNext() in C:\Source\GCB-Dashboard\gcb-libs\Services\AzureAuthTokenService.cs:line 42

  4. emmanuelpare commented on Aug 30, 2023

    @emmanuelpare
    Author

    thanks Emmanuel Pare (@emmanuelpare) Do you have a call stack for the exception?

    I see that you wrote AddAuthentication(JwtBearerDefaults.AuthenticationScheme), but you are building a web app. So it should be:

    AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)

    I would recommend you use:

    .AddTokenAcquisition()

    instead of the following:

                    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .AddMicrosoftIdentityWebApp(configuration.GetSection("AzureAd"))
                    .EnableTokenAcquisitionToCallDownstreamApi()

    I think this should fix your issue.

    _

    Aside, I think we've introduced a bug in 2.13.3, indeed, (by not using the ASP.NET Core token TokenAcquisition, but the default token acquisition): I had not anticipated that you could use AddMicrosoftWebApp without really needing a web app :-).

    Hi Thanks jmprieur I will try to implement your advice.... Iam building a console application that need to use a protected webapi. Iam using the webapp to be able to use dependancy injection into my console app.

  5. jmprieur commented on Aug 30, 2023

    @jmprieur
    Collaborator

    If you need a console app calling a protected web API, you might want to try out this sample, Emmanuel Pare (@emmanuelpare)
    https://github.com/Azure-Samples/active-directory-dotnetcore-daemon-v2/tree/master/2-Call-OwnApi

  6. jennyf19 commented on Sep 7, 2023

    @jennyf19
    Collaborator

    Emmanuel Pare (@emmanuelpare) any update on this? Going to close, but please re-open if it's still not working.

  7. added 2 commits that reference this issue on Oct 3, 2023
    8169958
    5f191c2
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

    P1bugSomething isn't workingquestionFurther information is requested

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions