Skip to content

[Bug] Getting Null Reference exception with 1.16.0 and MsalUiRequiredException with 1.16.1 when using MS Graph #1443

Closed

Description

@JFercan

Which version of Microsoft Identity Web are you using?
Microsoft Identity Web 1.16.0 and Microsoft Identity Web 1.16.1

Where is the issue?
When calling await _graphServiceClient.Users["username"].Request().GetAsync();
With 1.16.0 Get Null Reference Exception
With 1.16.1 Get MsalUiRequiredException

  • Web API
    • Protected web APIs (validating tokens)
    • Protected web APIs (validating scopes)
    • [ X] Protected web APIs call downstream web APIs
  • Token cache serialization
    • [X ] In-memory caches
    • Session caches
    • Distributed caches

Is this a new or an existing app?
This app is currently in production using .NET Core 2.2. Working on upgrading to .NET 5.0, updating the libraries and now running into this issue.

Repro

Service configuration:

services.AddMicrosoftIdentityWebApiAuthentication(configuration)
                .EnableTokenAcquisitionToCallDownstreamApi()
                .AddMicrosoftGraph(configuration.GetSection("MicrosoftGraph"))
                .AddInMemoryTokenCaches();

appsettings.json:

"AzureAd": {
    "ClientId": "xxx.xxx......",
    "Domain": "domain.com",
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "xxxxxx......",
    "ClientSecret": "xxxxxxxxx...."
  },
  "MicrosoftGraph": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": "user.read user.read.all"
  },

Usage of MS Graph

var user = await _graphServiceClient.Users["username"].Request().GetAsync();

Expected behavior
Get the requested user details

Actual behavior
The exceptions mentioned above are thrown instead of getting the user details

Additional context / logs / screenshots
1.16.0 - Log Entries

Method: Handle. Line: 73. Code: generalException
Message: An error occurred sending the request.

Status Code: 0
Microsoft.Graph.ServiceException: Code: generalException
Message: An error occurred sending the request.

---> 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.GetAuthenticationResultForUserAsync(IEnumerable1 scopes, String authenticationScheme, String tenantId, String userFlow, ClaimsPrincipal user, TokenAcquisitionOptions tokenAcquisitionOptions) at Microsoft.Identity.Web.TokenAcquisitionAuthenticationProvider.AuthenticateRequestAsync(HttpRequestMessage request) at Microsoft.Graph.AuthenticationHandler.SendAsync(HttpRequestMessage httpRequestMessage, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
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.UserRequest.GetAsync(CancellationToken cancellationToken)

1.16.1 - Log Entries

[INF] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.36.0.0 MSAL.NetCore .NET Core 3.1.18 Microsoft Windows 10.0.19042 [09-14 15:59:48.88 - 036cf0e8-9260-414d-9fe4-7c74dd014285]
=== Request Data ===
Authority Provided? - True
Scopes - user.read user.read.all
Extra Query Params Keys (space separated) -
ApiId - AcquireTokenSilent
IsConfidentialClient - True
SendX5C - False
LoginHint ? False
IsBrokerConfigured - False
HomeAccountId - False
CorrelationId - 036cf0e8-9260-414d-9fe4-7c74dd014285

[INF] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.36.0.0 MSAL.NetCore .NET Core 3.1.18 Microsoft Windows 10.0.19042 [09-14 15:59:48.89 - 036cf0e8-9260-414d-9fe4-7c74dd014285] === Token Acquisition (SilentRequest) started:
Scopes: user.read user.read.all
Authority Host: login.microsoftonline.com
[DBG] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.36.0.0 MSAL.NetCore .NET Core 3.1.18 Microsoft Windows 10.0.19042 [09-14 15:59:48.89 - 036cf0e8-9260-414d-9fe4-7c74dd014285] No account passed to AcquireTokenSilent.
[DBG] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.36.0.0 MSAL.NetCore .NET Core 3.1.18 Microsoft Windows 10.0.19042 [09-14 15:59:53.52 - 036cf0e8-9260-414d-9fe4-7c74dd014285] Token cache could not satisfy silent request.
[ERR] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.36.0.0 MSAL.NetCore .NET Core 3.1.18 Microsoft Windows 10.0.19042 [09-14 16:00:10.23 - 036cf0e8-9260-414d-9fe4-7c74dd014285] Exception type: Microsoft.Identity.Client.MsalUiRequiredException
, ErrorCode: user_null
HTTP StatusCode 0
CorrelationId

at Microsoft.Identity.Client.Internal.Requests.Silent.SilentRequest.ExecuteAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.Silent.SilentRequest.ExecuteAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
[INF] Microsoft.Identity.Web.TokenAcquisition: [MsIdWeb] An error occured during token acquisition: "No account or login hint was passed to the AcquireTokenSilent call. "
MSAL.NetCore.4.36.0.0.MsalUiRequiredException:
ErrorCode: user_null
Microsoft.Identity.Client.MsalUiRequiredException: No account or login hint was passed to the AcquireTokenSilent call.
at Microsoft.Identity.Client.Internal.Requests.Silent.SilentRequest.ExecuteAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.Silent.SilentRequest.ExecuteAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.ApiConfig.Executors.ClientApplicationBaseExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenSilentParameters silentParameters, CancellationToken cancellationToken)
at Microsoft.Identity.Web.TokenAcquisition.GetAuthenticationResultForWebAppWithAccountFromCacheAsync(IConfidentialClientApplication application, ClaimsPrincipal claimsPrincipal, IEnumerable1 scopes, String authority, MergedOptions mergedOptions, String userFlow, TokenAcquisitionOptions tokenAcquisitionOptions) at Microsoft.Identity.Web.TokenAcquisition.GetAuthenticationResultForUserAsync(IEnumerable1 scopes, String authenticationScheme, String tenantId, String userFlow, ClaimsPrincipal user, TokenAcquisitionOptions tokenAcquisitionOptions)
StatusCode: 0
ResponseBody:
Headers:
[ERR] Method: Handle. Line: 73. Code: generalException
Message: An error occurred sending the request.

Status Code: 0
Microsoft.Graph.ServiceException: Code: generalException
Message: An error occurred sending the request.

---> Microsoft.Identity.Web.MicrosoftIdentityWebChallengeUserException: IDW10502: An MsalUiRequiredException was thrown due to a challenge for the user. See https://aka.ms/ms-id-web/ca_incremental-consent.
---> MSAL.NetCore.4.36.0.0.MsalUiRequiredException:
ErrorCode: user_null
Microsoft.Identity.Client.MsalUiRequiredException: No account or login hint was passed to the AcquireTokenSilent call.
at Microsoft.Identity.Client.Internal.Requests.Silent.SilentRequest.ExecuteAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.Silent.SilentRequest.ExecuteAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.ApiConfig.Executors.ClientApplicationBaseExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenSilentParameters silentParameters, CancellationToken cancellationToken)
at Microsoft.Identity.Web.TokenAcquisition.GetAuthenticationResultForWebAppWithAccountFromCacheAsync(IConfidentialClientApplication application, ClaimsPrincipal claimsPrincipal, IEnumerable1 scopes, String authority, MergedOptions mergedOptions, String userFlow, TokenAcquisitionOptions tokenAcquisitionOptions) at Microsoft.Identity.Web.TokenAcquisition.GetAuthenticationResultForUserAsync(IEnumerable1 scopes, String authenticationScheme, String tenantId, String userFlow, ClaimsPrincipal user, TokenAcquisitionOptions tokenAcquisitionOptions)
StatusCode: 0
ResponseBody:
Headers:
--- End of inner exception stack trace ---
at Microsoft.Identity.Web.TokenAcquisition.GetAuthenticationResultForUserAsync(IEnumerable1 scopes, String authenticationScheme, String tenantId, String userFlow, ClaimsPrincipal user, TokenAcquisitionOptions tokenAcquisitionOptions) at Microsoft.Identity.Web.TokenAcquisitionAuthenticationProvider.AuthenticateRequestAsync(HttpRequestMessage request) at Microsoft.Graph.AuthenticationHandler.SendAsync(HttpRequestMessage httpRequestMessage, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
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.UserRequest.GetAsync(CancellationToken cancellationToken)

Activity

  1. jennyf19 commented on Oct 20, 2021

    @jennyf19
    Collaborator

    JFercan Can you provide your Startup.cs?

  2. JFercan commented on Oct 23, 2021

    @JFercan
    Author

    Startup.txt

    Hello jennyf19 ,

    As requested please find attached a version of our Startup.cs file.

    Thank you,

  3. JFercan commented on Feb 17, 2022

    @JFercan
    Author

    Hello jennyf19

    Is there any update on this issue? It is still happening even after updating to version 1.23.0 for both Microsoft.Identity.Web and Microsoft.Identity.Web.MicrosfotGraph.

    With this new version I still experience the same issue as 1.16.1.

    Thank you.

  4. jennyf19 commented on Feb 19, 2022

    @jennyf19
    Collaborator

    JFercan I would need to see the code of the controller, but you might need to pass the AuthenticationScheme if it's different from the default authentication scheme:

    var user = await _graphServiceClient.Users["username"]
    .Request()
    .WithAuthenticationScheme(JwtBearerDefaults.AuthenticationScheme)
    .GetAsync();

    Also, what does this do:

    services.AddAuthentication()
          .AddScheme<ApiKeyAuthenticationSchemeOptions, ApiKeyAuthenticationHandler>(AuthenticationSchemes.ApiKey, null);

    could it be overriding the default auth scheme?

  5. JFercan commented on Feb 19, 2022

    @JFercan
    Author

    Hello jennyf19 ,

    I tried adding WithAuthenticationScheme but it does not seem to be an option on Microsoft.Graph version 4.11.0. Some devices authenticate using a key instead of Azure AD, and this is a customer handler for those. We might move this to use a Secret from the Azure AD registration instead.

    I did get Graph to work by creating the instance this way, not sure if it would help:

    private static IServiceCollection AddGraphServiceClient(this IServiceCollection services)
    {
    	services.AddScoped(provider =>
    	{
    		string[] scopes = { "User.Read", "User.Read.All" };
    		var configuration = provider.GetRequiredService<IConfiguration>();
    		var httpContext = provider.GetRequiredService<IHttpContextAccessor>();
    		var token = (httpContext?.HttpContext?.User?.Identity as ClaimsIdentity)
    			?.FindFirst("jwt")?.Value;
    
    		var confidentialClientApplication = ConfidentialClientApplicationBuilder
    			.Create(configuration["AzureAd:ClientId"])
    			.WithTenantId(configuration["AzureAd:TenantId"])
    			.WithClientSecret(configuration["AzureAd:ClientSecret"] ?? "")
    			.Build();
    
    		return new GraphServiceClient(new DelegateAuthenticationProvider(async message =>
    		{
    			var assertion = new UserAssertion(token);
    			var authResult = await confidentialClientApplication
    				.AcquireTokenOnBehalfOf(scopes, assertion).ExecuteAsync();
    
    			message.Headers.Authorization =
    				new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
    		}));
    	});
    
    	return services;
    }
    

    Thank you.

  6. jennyf19 commented on Feb 20, 2022

    @jennyf19
    Collaborator

    JFercan WithAuthenticationScheme is added with Microsoft.Identity.Web.MicrosoftGraph, it's an extension method.

  7. JFercan commented on Feb 21, 2022

    @JFercan
    Author

    Hello jennyf19 ,

    Tried changing the code as follows:

    var search = $"startswith(mail,'{request.UserName}')";
    var user = await _graphServiceClient.Users.Request()
    	.WithAuthenticationScheme(JwtBearerDefaults.AuthenticationScheme)
    	.Select(u => new
    	{
    		u.Id,
    		u.GivenName,
    		u.Surname,
    		u.MailNickname,
    		u.MobilePhone,
    		u.BusinessPhones,
    		u.Mail,
    		u.JobTitle,
    	}).Filter(search).GetAsync(cancellationToken);
    

    However I still got the following exception:

    Status Code: 0
    Microsoft.Graph.ServiceException: Code: generalException
    Message: An error occurred sending the request.
    
     ---> Microsoft.Identity.Web.MicrosoftIdentityWebChallengeUserException: IDW10502: An MsalUiRequiredException was thrown due to a challenge for the user. See https://aka.ms/ms-id-web/ca_incremental-consent. 
     ---> MSAL.NetCore.4.41.0.0.MsalUiRequiredException: 
    	ErrorCode: user_null
    Microsoft.Identity.Client.MsalUiRequiredException: No account or login hint was passed to the AcquireTokenSilent call. 
       at Microsoft.Identity.Client.Internal.Requests.Silent.SilentRequest.ExecuteAsync(CancellationToken cancellationToken)
       at Microsoft.Identity.Client.Internal.Requests.Silent.SilentRequest.ExecuteAsync(CancellationToken cancellationToken)
       at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
       at Microsoft.Identity.Client.ApiConfig.Executors.ClientApplicationBaseExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenSilentParameters silentParameters, CancellationToken cancellationToken)
       at Microsoft.Identity.Web.TokenAcquisition.GetAuthenticationResultForWebAppWithAccountFromCacheAsync(IConfidentialClientApplication application, ClaimsPrincipal claimsPrincipal, IEnumerable`1 scopes, String tenantId, MergedOptions mergedOptions, String userFlow, TokenAcquisitionOptions tokenAcquisitionOptions)
       at Microsoft.Identity.Web.TokenAcquisition.GetAuthenticationResultForUserAsync(IEnumerable`1 scopes, String authenticationScheme, String tenantId, String userFlow, ClaimsPrincipal user, TokenAcquisitionOptions tokenAcquisitionOptions)
    	StatusCode: 0 
    	ResponseBody:  
    	Headers: 
       --- End of inner exception stack trace ---
       at Microsoft.Identity.Web.TokenAcquisition.GetAuthenticationResultForUserAsync(IEnumerable`1 scopes, String authenticationScheme, String tenantId, String userFlow, ClaimsPrincipal user, 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 Application.User.UserDetailQueryHandler.Handle(UserDetailQuery request, CancellationToken cancellationToken) in C:\Projects\Application\Application\Application\User\UserDetailQuery.cs:line 56
    

    Let me know if more details are required.

    Thank you,

  8. jmprieur commented on Mar 28, 2022

    @jmprieur
    Collaborator

    See PR: #1672

  9. jennyf19 commented on Apr 20, 2022

    @jennyf19
    Collaborator

    Released in 1.24.0.

  10. MattHartz commented on Oct 14, 2022

    @MattHartz

    So what is the solution to this jennyf19 Jean-Marc Prieur (@jmprieur)

  11. jmprieur commented on Oct 14, 2022

    @jmprieur
    Collaborator

    This was fixed in a later version of Id.Web

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions