“Could not load file or assembly ‘Microsoft.IdentityModel.JsonWebTokens” when running PowerShell in Azure Functions

I was recently trying to migrate some PowerShell scripts to run in Azure Functions. These scripts needed to call both the Microsoft Graph API & the Microsoft Teams API.

Naturally, I tried to import both the Microsoft.Graph & the MicrosoftTeams cmdlets in the requirements.psd1 file.

@{
   'Microsoft.Graph' = '1.22.0'
    MicrosoftTeams    = '5.0.0'
}

My PowerShell script first tries to connect to the Microsoft Graph API, issues some queries & then calls the Teams API.

#connect to the Microsoft Graph API
Connect-MgGraph -AccessToken $graphToken

...

#connect to the Microsoft Teams API
Connect-MicrosoftTeams -AccessTokens @("$graphToken", "$teamsToken")

...

Unfortunately, when I tried to run the PowerShell script, I got the following error.

2023-04-03T20:19:34Z   [Error]   ERROR: Could not load file or assembly 'Microsoft.IdentityModel.JsonWebTokens, Version=6.8.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. Could not find or load a specific file. (0x80131621)

Exception             : 
    Type           : System.IO.FileLoadException
    Message        : Could not load file or assembly 'Microsoft.IdentityModel.JsonWebTokens, Version=6.8.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. Could not find or load a specific file. (0x80131621)
InvocationInfo        : 
    MyCommand        : Connect-MicrosoftTeams
    ScriptLineNumber : 6
    OffsetInLine     : 3
    HistoryId        : 1
    Line             : Connect-MicrosoftTeams -AccessTokens @("$GraphToken", "$TeamsToken")
                       
    PositionMessage  : At C:\home\site\wwwroot\Modules\run.ps1:6 char:3
                       +   Connect-MicrosoftTeams -AccessTokens @("$GraphToken", "$TeamsToken"
                       +   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The PowerShell script was able to successfully connect to the Microsoft Graph API, but errors out when it tries to connect to the Microsoft Teams API.

Turns out the Microsoft.Graph & MicrosoftTeams cmdlets use different & incompatible DLLs (Microsoft.IdentityModel.JsonWebTokens and others).

Solution is to run two different Azure Functions, each with only 1 of those cmdlets loaded. This ensures each one gets its own runtime and appropriate DLL versions loaded.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *