我创建了一个API,我试图在其中获取令牌,然后使用该令牌获取数据它在Visual Studio调试模式下/在本地工作正常,提示启用用户凭据,因为启用了MFA,还将要求OTP并正常工作
问题是当我在Azure API / WEb应用程序中部署时,它不起作用,并且在获取令牌的那一行失败。还应注意,在Web应用程序中部署时,它从不提示输入USer凭据。如果不可能,我想静默获取令牌,提示输入证书也可以。至少在Web应用程序中进行深度部署后,它应该可以工作。这里是代码片段:
using Microsoft.IdentityModel.Clients.ActiveDirectory;
//API Method
public async Task<IEnumerable<string>> Get()
{
try
{
private static string authority = String.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}" ,"575d120d-78ae-41fc-b5a0-4072a4349b");
AuthenticationResult result = null;
HttpClient httpClient = new HttpClient();
AuthenticationContext authContext = new AuthenticationContext(authority);
result = await authContext.AcquireTokenAsync(todoListResourceId, clientId, redirectUri, new PlatformParameters(PromptBehavior.Auto));//new PlatformParameters(PromptBehavior.Auto)
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
// Call the To Do list service.
HttpResponseMessage response = await httpClient.GetAsync(todoListBaseAddress + "locations");//+ "/api/values/4"
if (response.IsSuccessStatusCode)
{
//MessageBox.Show(response.RequestMessage.ToString());
string s = await response.Content.ReadAsStringAsync();
}
}
catch (HttpRequestException ex)
{
return new string[] { ex.Message, ex.StackTrace };
}
catch (Exception ex)
{
return new string[] { ex.Message, ex.StackTrace };
}
}
确保两个应用程序都代表流量为registered in Azure AD and user consent has been granted。
对于静默令牌获取,请遵循the recommended pattern并先调用AcquireTokenSilentAsync
,然后仅在失败时回退到AcquireTokenAsync
。