I managed to get it working by adding a Users/Groups App Role 'LocalDevelopment' to the App Registration with the value 'API.Use.Local', then added the user I'm running as, which is in Azure AD to the App Registration via Enterprise Applications:
Enterprise applications -> TheApp -> Users and groups -> +Add
add the user I'm using with Azure CLI with role 'LocalDevelopment'
I could then login with az using the scope:
az login --scope api://APPLICATION_ID/.default
using the user I added in the Enterprise application part and then verifying obtaining an access token worked from the commandline:
az account get-access-token --output json --scope api://APPLICATION_ID/.default
The code then worked for running locally:
DefaultAzureCredentialOptions defaultAzureCredentialOptions = new()
{
ManagedIdentityClientId = clientIdOfuserAssignedManagedIdentity,
ExcludeInteractiveBrowserCredential = true,
ExcludeVisualStudioCodeCredential = true,
ExcludeVisualStudioCredential = true,
ExcludeAzureCliCredential = false,
ExcludeSharedTokenCacheCredential = true,
ExcludeAzurePowerShellCredential = true
};
DefaultAzureCredential tokenCredential = new(defaultAzureCredentialOptions);
string accessToken = tokenCredential.GetToken(new TokenRequestContext(new[] { "api://APPLICATION_ID/.default" })).Token.ToString();