Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Dec 2, 2025

Add meaningful error message when identity configuration is missing

  • You've read the Contributor Guide and Code of Conduct.
  • You've included unit or integration tests for your change, where applicable.
  • You've included inline docs for your change, where applicable.
  • There's an open issue for the PR that you are making. If you'd like to propose a new feature or change, please open an issue to discuss the change or find an existing issue.

Replace NullReferenceException with meaningful error when identity config keys have typos

Description

When configuration keys have typos (e.g., "ManagedIdentity " with trailing space), the library throws an unhelpful NullReferenceException instead of guiding the user to the actual problem.

Changes:

  • Add validation in BuildConfidentialClientApplicationAsync() to detect incomplete identity configuration
  • Add null-safety check for Instance in GetAuthenticationResultForAppAsync()
  • New error code IDW10708 with actionable message pointing to common causes and documentation link

Before:

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Identity.Web.MergedOptions.PrepareAuthorityInstanceForMsal()

After:

System.ArgumentException: IDW10708: The identity configuration is incomplete. 
Provide either 'Instance' and 'TenantId', or 'Authority', or enable 'ManagedIdentity' 
in the configuration. Check your configuration keys for typos (e.g., trailing spaces).
See https://aka.ms/ms-id-web/configuration.

Fixes #2921

Original prompt

This section details on the original issue you should resolve

<issue_title>Microsoft.Identityj.Web.DownstreamApi should give meaningful error message when identity is specified through configuration with a wrong key</issue_title>
<issue_description>### Microsoft.Identity.Web Library

Microsoft.Identity.Web.DownstreamApi

Microsoft.Identity.Web version

2.19.0

Web app

Not Applicable

Web API

Protected web APIs (validating tokens)

Token cache serialization

In-memory caches

Description

Following example "6-Call-OwnApi - ManagedIdentity" from https://github.com/Azure-Samples/active-directory-dotnetcore-daemon-v2, I accidentally have a wrong configuration in appsettings.json, and when running the application it threw "NullRefernceException".

Reproduction steps

Following example "6-Call-OwnApi - ManagedIdentity" from https://github.com/Azure-Samples/active-directory-dotnetcore-daemon-v2,

Note, in appsettings.json there is an empty space at the end of the key name: "ManagedIdentity "

{
	"MyWebApi": {
		"BaseUrl": "<API_URL>",
		"RelativePath": "api/<API_Name>",
		"RequestAppToken": true,
		"Scopes": [ "api://<API_Application_Id>/.default" ],
		"AcquireTokenOptions": {
			"ManagedIdentity ": {
				"UserAssignedClientId ": "<UAMI_ID>"
			}
		}
	}
}

Run the application in Azure VM.

Error message

Run the application in Azure VM, I got this error message:

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Identity.Web.MergedOptions.PrepareAuthorityInstanceForMsal()
   at Microsoft.Identity.Web.TokenAcquisition.BuildConfidentialClientApplicationAsync(MergedOptions mergedOptions)
   at Microsoft.Identity.Web.TokenAcquisition.GetOrBuildConfidentialClientApplicationAsync(MergedOptions mergedOptions)
   at Microsoft.Identity.Web.TokenAcquisition.GetAuthenticationResultForAppAsync(String scope, String authenticationScheme, String tenant, TokenAcquisitionOptions tokenAcquisitionOptions)
   at Microsoft.Identity.Web.DefaultAuthorizationHeaderProvider.CreateAuthorizationHeaderForAppAsync(String scopes, AuthorizationHeaderProviderOptions downstreamApiOptions, CancellationToken cancellationToken)
   at Microsoft.Identity.Web.DownstreamApi.UpdateRequestAsync(HttpRequestMessage httpRequestMessage, HttpContent content, DownstreamApiOptions effectiveOptions, Boolean appToken, ClaimsPrincipal user, CancellationToken cancellationToken)
   at Microsoft.Identity.Web.DownstreamApi.CallApiInternalAsync(String serviceName, DownstreamApiOptions effectiveOptions, Boolean appToken, HttpContent content, ClaimsPrincipal user, CancellationToken cancellationToken)
   at Microsoft.Identity.Web.DownstreamApi.GetForAppAsync[TOutput](String serviceName, Action`1 downstreamApiOptionsOverride, CancellationToken cancellationToken)
   at Program.<Main>$(String[] args) in C:\Users\<me>\source\repos\active-directory-dotnetcore-daemon-v2\6-Call-OwnApi - ManagedIdentity\daemon-console\Program.cs:line 36
   at Program.<Main>(String[] args)

Id Web logs

No response

Relevant code snippets

#
// Extract the downstream API service from the 'tokenAcquirerFactory' service provider.
var api = sp.GetRequiredService<IDownstreamApi>();

// You can use the API service to make direct HTTP calls to your API. Token
// acquisition is handled automatically based on the configurations in your
// appsettings.json file.
var result = await api.GetForAppAsync<IEnumerable<TodoItem>>("MyApi");

Regression

No response

Expected behavior

The library does some validation and return meaningful error message rather than an NullReferenceException, it took me for a while to figure out the problem.</issue_description>

<agent_instructions>Please help fix the bug with no other changes unrelated to fixing this issue. Add unit tests if needed.</agent_instructions>

Comments on the Issue (you are @copilot in this section)

@bgavrilMS Hi @jennyf19, I'd like to take this as a usability bug. SDKs should not throw NullReferenceExceptions in any circumstance. @bgavrilMS I fixed the sample. @jennyf19 @bgavrilMS did you fix it in IdWeb?

💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Copilot AI changed the title [WIP] Fix error handling for invalid identity configuration key Add meaningful error message when identity configuration is missing Dec 2, 2025
Copilot AI requested a review from neha-bhargava December 2, 2025 19:45
Copilot finished work on behalf of neha-bhargava December 2, 2025 19:45
Copilot AI requested a review from neha-bhargava December 3, 2025 19:44
Copilot finished work on behalf of neha-bhargava December 3, 2025 19:44
Copilot finished work on behalf of neha-bhargava December 3, 2025 21:32
Copy link
Collaborator

@jmprieur jmprieur left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM
Thanks @copilot @neha-bhargava

@neha-bhargava neha-bhargava marked this pull request as ready for review December 4, 2025 19:20
@neha-bhargava neha-bhargava requested a review from a team as a code owner December 4, 2025 19:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Microsoft.Identityj.Web.DownstreamApi should give meaningful error message when identity is specified through configuration with a wrong key

3 participants