Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
emmanuelpare opened this issue Aug 29, 2023 · 6 comments · Fixed by #2499
Labels
bug Something isn't working P1 question Further information is requested

Comments

@emmanuelpare
Copy link

emmanuelpare commented Aug 29, 2023

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

@emmanuelpare emmanuelpare added the question Further information is requested label Aug 29, 2023
@emmanuelpare
Copy link
Author

it might be a duplicate of #2394

@jmprieur jmprieur added the bug Something isn't working label Aug 30, 2023
@jmprieur
Copy link
Collaborator

jmprieur commented Aug 30, 2023

thanks @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 :-).

@jmprieur jmprieur added the P1 label Aug 30, 2023
@emmanuelpare
Copy link
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

@emmanuelpare
Copy link
Author

thanks @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.

@jmprieur
Copy link
Collaborator

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

@jennyf19
Copy link
Collaborator

jennyf19 commented Sep 7, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working P1 question Further information is requested
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants