D365 Online插件沙箱模式下证书/JWT调用API网关遇程序集错误
问题描述
在Dynamics 365 Online插件中,尝试通过客户端证书结合JWT认证调用API网关时,触发以下错误:
Could not load file or assembly 'Microsoft.IdentityModel.Tokens, Version=8.11.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference.
已尝试的操作:
- 在
.csproj中添加配置:<PropertyGroup> <_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput> </PropertyGroup> - 将
Microsoft.IdentityModel.Tokens版本降级至5.6并重新构建测试,但问题依旧。
相关代码:
public string callApiGateway(Input inputData) { try { var json = JsonConvert.SerializeObject(inputData, jsonSettings); var data = new StringContent(json, Encoding.UTF8, "application/json"); using (HttpClient client = new HttpClient()) { var certificate = new X509Certificate2("privatecertificate_hardcoded", "certi_password"); var tokenDescriptor = new SecurityTokenDescriptor { Issuer = "Tester API", Subject = new ClaimsIdentity(new[] { new Claim("sub","API GWtest"), new Claim("scope","read:api") }), Expires = DateTime.UtcNow.AddMinutes(1), SigningCredentials = new X509SigningCredentials(certificate) }; var handler = new JwtSecurityTokenHandler(); var token = handler.CreateToken(tokenDescriptor); var jwt = handler.WriteToken(token); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwt); string url = "https://api_gateway/link"; var response = client.PostAsync(url, data).Result; } } catch (Exception ex) { return ex.Message; } return string.Empty; }
解决方案建议
1. 添加程序集绑定重定向
在插件的配置文件(app.config或web.config)中加入绑定重定向规则,强制Dynamics 365加载你项目中实际引用的版本:
<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Microsoft.IdentityModel.Tokens" publicKeyToken="31bf3856ad364e35" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-8.11.0.0" newVersion="5.6.0.0" /> </dependentAssembly> </assemblyBinding> </runtime>
注意:newVersion需与你项目中实际引用的Microsoft.IdentityModel.Tokens版本完全一致。
2. 统一所有相关依赖包版本
检查项目依赖链,确认是否有其他包(比如System.IdentityModel.Tokens.Jwt)自动引入了更高版本的Microsoft.IdentityModel.Tokens。通过NuGet包管理器将所有JWT相关依赖包统一到相同版本(比如5.6),避免跨版本依赖冲突。
3. 确认插件部署时的程序集完整性
使用插件注册工具(Plugin Registration Tool)部署插件时,确保勾选包含所有依赖项,将Microsoft.IdentityModel.Tokens及其关联程序集一同上传到Dynamics 365环境。也可以手动检查项目输出目录,确认这些程序集已被正确编译生成。
4. 优化证书加载方式
Dynamics 365插件运行环境中,硬编码的证书路径大概率无法访问,建议:
- 将证书上传至Azure Key Vault,通过插件的服务主体权限访问加载
- 使用证书Thumbprint从服务器本地证书存储中加载,避免路径依赖问题
内容的提问来源于stack exchange,提问作者jeenati

