我有一個API已與網關主機一起正常工作,現在網關主機已被棄用,我正在嘗試遵循Migration Guide。我已經使用2.8.1 SDK重新部署了我的服務,並且可以使用AAD或Microsoft帳戶通過瀏覽器登錄服務,並使用Swagger來測試該服務。但是,我試圖讓客戶端使用ClientId和Secret來訪問服務。代碼能夠從AAD獲取訪問令牌,但每當我嘗試訪問其中一個服務資源時,我總是會收到401錯誤。使用AAD向Azure API應用程序進行身份驗證時出現401錯誤
當我調試我在日誌中看到以下服務:
Microsoft.Azure.AppService.Authentication Verbose: 0 : Received request: GET https://[myService].azurewebsites.net/api/[myResource]
Microsoft.Azure.AppService.Authentication Warning: 0 : JWT validation failed: IDX10214: Audience validation failed. Audiences: 'https://[myService].azurewebsites.net/'. Did not match: validationParameters.ValidAudience: '[AAD ClientId]' or validationParameters.ValidAudiences: 'http://[myService].azurewebsites.net'.
Microsoft.Azure.AppService.Authentication Information: 0 : Sending response: 401.71 Unauthorized
The thread 0x3b00 has exited with code 0 (0x0).
什麼似乎是問題是,帶有請求的觀衆爲https,但validParameters.ValidAudiences集合只包含HTTP。
我看不到任何配置Audience的方式,並且在Visual Studio 2015創建App Service時看起來基於http的觀衆正在設置。有沒有手動編輯ValidAudience集合的方法?
僅供參考我的客戶端代碼:
private static void Main(string[] args)
{
string app_id_url = "https://[myService].azurewebsites.net/";
string authority = "https://login.windows.net/[myDirectory].onmicrosoft.com/";
string clientId = "[AAD ClientId]";
string clientSecret = "[AAD Client Secret]";
string apiBaseUrl = "https://[myService].azurewebsites.net/";
string aadToken = GetTokenForApplication(authority, clientId, clientSecret, app_id_url);
var apiClient = new HttpClient { BaseAddress = new Uri(apiBaseUrl) };
apiClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", aadToken);
var apiResponse = apiClient.GetAsync(apiBaseUrl + @"api/[myResource]").Result;
string apiResponseContent = apiResponse.Content.ReadAsStringAsync().Result;
Console.WriteLine(apiResponseContent);
}
public static string GetTokenForApplication(string authority, string clientId, string clientSecret, string resourceUrl)
{
AuthenticationContext authenticationContext = new AuthenticationContext(authority, false);
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
AuthenticationResult authenticationResult = authenticationContext.AcquireToken(resourceUrl, clientCred);
string token = authenticationResult.AccessToken;
return token;
}
您需要用部署中的實際參數替換方括號中的標識符。 – MvdD
感謝@MvdD,但是我將這些實際參數用於本文。正如你可以從帖子的頂部看到的,這用於工作,現在沒有。 –
嗨@GraemeWilson,你是否仍然需要回答這個問題,或者你找到了解決方案? – juvchan