microsoft-identity-web: [Bug] Not compatible with .NET 6 and Azure Functions when calling AddMicrosoftIdentityWebApi

Which version of Microsoft Identity Web are you using? Microsoft Identity Web 1.21.0

Where is the issue?

  • Web app
    • Sign-in users
    • Sign-in users and call web APIs
  • Web API
    • Protected web APIs (validating tokens)
    • Protected web APIs (validating scopes)
    • Protected web APIs call downstream web APIs
  • Token cache serialization
    • In-memory caches
    • Session caches
    • Distributed caches
  • Other (please describe)
    • Azure Function protected Web API (Http Trigger)

Is this a new or an existing app? c. This is a new app or an experiment.

Repro

  1. In Visual Studio 2022 create a new project.

  2. Select Azure Functions template.

  3. Enter FunctionApp1 as the name and click Create.

  4. In the Create a new Azure Functions application prompt select a .NET 6 Empty template with a Storage account (AzureWebJobsStorage) see to None.

  5. Update the FunctionApp1.csproj with the following code:

<Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
            <TargetFramework>net6.0</TargetFramework>
            <AzureFunctionsVersion>v4</AzureFunctionsVersion>
            <_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
      </PropertyGroup>
      <ItemGroup>
            <PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
            <PackageReference Include="Microsoft.Identity.Web" Version="1.21.0" />
            <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.0.1" />
      </ItemGroup>
      <ItemGroup>
            <None Update="host.json">
                  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
            </None>
            <None Update="local.settings.json">
                  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
                  <CopyToPublishDirectory>Never</CopyToPublishDirectory>
            </None>
      </ItemGroup>
</Project>

Note: The line <_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput> is required in order to bypass the issue noted here: https://github.com/AzureAD/microsoft-identity-web/issues/1428

  1. Create a class called Startup.cs and add the following code
using FunctionApp1;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Identity.Web;

[assembly: FunctionsStartup(typeof(Startup))]

namespace FunctionApp1;

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder) =>
        builder.Services
            .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApi(builder.GetContext().Configuration.GetSection("Azure"));
 
    [FunctionName("Function1")]
    public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest request) =>
        request.HttpContext.AuthenticateAzureFunctionAsync().Result.Item2;
}
  1. Build and then run the application.
  2. Navigate to the URL http://localhost:7071/api/Function1.
  3. You should get the following error when invoking the endpoint:
System.AggregateException: 'One or more errors occurred. (Method not found: 'Microsoft.IdentityModel.Tokens.TokenValidationParameters Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerOptions.get_TokenValidationParameters()'.)'

Inner Exception
MissingMethodException: Method not found: 'Microsoft.IdentityModel.Tokens.TokenValidationParameters Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerOptions.get_TokenValidationParameters()'.

Actual behavior The request.HttpContext.AuthenticateAzureFunctionsAsync() throws a Method not found exception.

Expected behavior The request.HttpContext.AuthenticateAzureFunctionsAsync() should not throw a Method not found exception.

Workaround Downgrading to version Microsoft Identity Web 1.12.0 or prior fixes this issue.

snap issue

snap issue 2

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 6
  • Comments: 46

Most upvoted comments

The Azure Functions team is re-visiting this. Will post any updates here.

Thanks @jennyf19 BTW, 2 days ago I tested latest MS Identity web in an Az Functions project with an HttpTrigger. With the new Factory, I was able to inject the TokenAcquisition etc, but when running, I got the same issue with not finding some version of the IdentityModel class (if memory serves me well). I was NOT using Az Function isolated mode, so, I guess the Functions runtime, is using a different version of some of the libraries using by MS Identity web…

Yeah, I’m getting Method not found on both Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerOptions.set_TokenValidationParameters(Microsoft.IdentityModel.Tokens.TokenValidationParameters) and Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerOptions.get_TokenValidationParameters()

Seeing as this is gonna be an issue forever, because of how the Azure Function team delivers their runtime, can we get a table with Azure Function Runtime versions and their compatible Microsoft.Identity.Web versions? At this point, i have abandoned the tought of having a common lib for my WebApps and Function Apps. Having it documented would at least allow people to pick the proper version for the current runtime, without having to go thru 3 or 4 issues on github and trying to mix’n’match.

@luismanez can you send me an email at jeferrie@microsoft.com?

Rough ETA is another 2 weeks.

I literally gave up. I´m not using the library in Az Functions v4 with .net 6 (not working and can´t wait to upgrade my project, as MS is deprecating .net 3.1 in less than 6 months). For my Az Functions, I´m using MSAL directly with ClientCredentials flow. It´s a shame, but I have no option. Last, I must say that this is not on this MS team. Jenny and Jean-Marc have been helping as much as they can, but is on Az Functions team.

image

Still the same issue, any update?

Any update here @jmprieur @jennyf19 ??

Hitting very similar issue, likely same cause. In my case, I´m not calling AddAuthentication as that break HttTriggers secured by Function code. My startup has:

var authBuilder = new AuthenticationBuilder(services);
            authBuilder.AddMicrosoftIdentityWebApi(configuration.GetSection("AzureAd"))
                .EnableTokenAcquisitionToCallDownstreamApi()
                .AddMicrosoftGraphAppOnly(authProvider => new GraphServiceClient(authProvider))
                .AddInMemoryTokenCaches();

But when using the injected GraphServiceClient, I´m getting this issue:

Method not found: ‘Microsoft.IdentityModel.Tokens.TokenValidationParameters Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerOptions.get_TokenValidationParameters()’.

Stack trace:

   at Microsoft.Identity.Web.MicrosoftIdentityWebApiAuthenticationBuilderExtensions.<>c__DisplayClass3_0.<AddMicrosoftIdentityWebApiImplementation>b__0(JwtBearerOptions options, IServiceProvider serviceProvider, IOptionsMonitor`1 mergedOptionsMonitor, IOptionsMonitor`1 msIdOptionsMonitor, IOptions`1 msIdOptions)
   at Microsoft.Extensions.Options.ConfigureNamedOptions`5.Configure(String name, TOptions options)
   at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name)
   at Microsoft.Azure.WebJobs.Hosting.WebJobsOptionsFactory`1.Create(String name) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Hosting\OptionsFormatter\WebJobsOptionsFactory.cs:line 57
   at Microsoft.Extensions.Options.OptionsMonitor`1.<>c__DisplayClass10_0.<Get>b__0()
   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
   at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
   at System.Lazy`1.CreateValue()
   at Microsoft.Identity.Web.TokenAcquisition.GetAuthenticationResultForAppAsync(String scope, String authenticationScheme, String tenant, TokenAcquisitionOptions tokenAcquisitionOptions)
   at Microsoft.Identity.Web.TokenAcquisitionAuthenticationProvider.<AuthenticateRequestAsync>d__3.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Graph.AuthenticationHandler.<SendAsync>d__16.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.Http.HttpClient.<<SendAsync>g__Core|83_0>d.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.Graph.HttpProvider.<SendRequestAsync>d__19.MoveNext()

This also blocking us to move our product to .NET 6 and latest ms-identity-web 😦

Thanks.

Still happening on Function Runtime 4.3.2.18186 for me.

That’s great! Thanks for checking on this @dirthsj! I will try to carve out time in the next day or two to come back to this.

@jmprieur it looks like that PR was merged and released with in 4.2.0, can you confirm this version does include the fix?

@Mitars, @newbiedev123, @dirthsj, @luismanez:

The Azure function team is fixing the issue on their side (The PR is https://github.com/Azure/azure-functions-host/pull/8129). Please use that PR to get the update. When this is fixed, this should just work.

Note that we also have a number of improvements around the support of Azure functions by Id.Web, which are blocked by this issue: See https://github.com/AzureAD/microsoft-identity-web/projects/44 for that backlog. We’ll resume that work when the Azure function work is fixed and deployed.

Here’s a work around for updating the package:

  • update the package to 2.13
  • make sure you’re using Function Runtime Version: 4.25.3 (for testing locally)
  • remove Microsoft.IdentityModel.Abstractions.dll from build folder
  • run the function

I will update this thread once the issue being fixed completely without any workaround.

good question. can someone explain how configuring logging filter fixes the issue? I tried it on our project and it didn’t work!

@jmprieur and @jennyf19 we need update the package to the latest version to get the update for System.Security.Cryptography.Pkcs that has vulnerability issues. I also see you added a label for work-around-available. did you try the work around and does it work for you?

@jennyf19 Any updates on this?

This is blocking everybody, @muzzar78 (us included)

New VS2022 17.2.0 preview 6.0… Old issues… still same Az Tools… this is really frustrating and totally disappointed on the Az Functions team 😦

@jennyf19 yeah, just tested and same experience (VS2022 17.2.0 Preview 5.0). Seems the Core tools version hasn´t changed…

image

Thanks a lot for checking and chasing this. Really appreciate it.

Thank you very much for testing and confirming my results. Hope you get an update from the Az Functions team (no luck for me on twitter). Thanks again.

@luismanez I tried with this: Azure Functions Core Tools Core Tools Version: 4.0.4483 Commit hash: N/A (64-bit) Function Runtime Version: 4.1.3.17473

In both VS 17.1.5 and 17.2.0 Preview 4, I am still hitting the same issue. I’ve asked the Azure Functions team for an update, as last we heard, it was supposed to be available beginning of April. Will keep you posted.

@luismanez I’ve asked the Az Functions team how to pick up the changes, I’m waiting to hear back from them.

This is next on our priority list, @dirthsj But we are also working on some important internal commitments.

@jennyf19 and I would like to have a plan on what to do for Azure functions next week.

How do you create your azure functions with .NET 6?

This bug is blocking our upgrade to Azure Functions v4 / Dotnet 6, is there any ETA for resolution?