确认所使用的资源ID “https://myapp-registration-westus-dev.azurewebsites.net/” 是准确的。我按照这里的步骤设置Azure AD身份验证,并使用与您相同的代码,并且能够获取令牌。 https://docs.microsoft.com/en-us/azure/app-service/app-service-mobile-how-to-configure-active-directory-authentication
您也可以运行此代码来检查MSI返回的确切错误。如果错误无法解决问题,请发布错误消息。
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Secret", Environment.GetEnvironmentVariable("MSI_SECRET"));
var response = await client.GetAsync(String.Format("{0}/?resource={1}&api-version={2}", Environment.GetEnvironmentVariable("MSI_ENDPOINT"), "https://myapp-registration-westus-dev.azurewebsites.net/", "2017-09-01"));
string msiResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
log.Info($"MSI Response: {msiResponse}");
更新: - 这project.json文件和文件run.csx工作对我来说。注意:project.json是指.NET 4.6,按照Azure Functions文档(注释中的链接),.NET 4.6是目前唯一受支持的版本。 您不需要再次上传引用的程序集。最有可能的是,不正确的手动上传netstandard程序集,而不是net452正在导致您的问题。
只有在.NET Framework 4.6支持,所以请确保您 project.json文件指定如下所示net46。当您上传 project.json文件时,运行时会获取软件包,并自动向软件包组件添加引用。你不需要添加#r “AssemblyName”指令。要使用NuGet 包中定义的类型,请将所需的使用语句添加到run.csx文件中。
project.json
{
"frameworks": {
"net46":{
"dependencies": {
"Microsoft.Azure.Services.AppAuthentication": "1.0.0-preview"
}
}
}
}
run.csx
using Microsoft.Azure.Services.AppAuthentication;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
try
{
var azureServiceTokenProvider = new AzureServiceTokenProvider();
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://vault.azure.net/");
log.Info($"Access Token: {accessToken}");
return req.CreateResponse(new {token = accessToken});
}
catch(Exception ex)
{
log.Error("Error", ex);
throw;
}
}
“Microsoft.Azure.Services.AppAuthentication”:“1.0.0-preview”, –
使用具有相同资源的client.GetAsync()函数返回一个有效的标记。在Azure函数中,我使用NuGet来解析AppAuthentication组件并使用#r“.. \ bin \ ...”引用。我使用这个参考:**“Microsoft.Azure.Services.AppAuthentication”:“1.0.0-preview”**这是最新版本吗?此外,对该函数进行后续调用会导致GetAccesstokenAsync()挂起并永远不会返回。 –
你可以请分享你从client.GetAsync()获得的响应 - “MSI响应”得到记录?请用占位符替换访问令牌(例如“eyJ0eXAi ...”)。只是想确保响应格式符合预期。 NuGet版本是正确的,这是唯一的版本。 –