ゲートウェイ ホストで正常に動作している API アプリがありますが、ゲートウェイ ホストが非推奨になったため、移行ガイドに従おうとしています。2.8.1 SDK を使用してサービスを再デプロイし、AAD または Microsoft アカウントを使用してブラウザーでサービスにログインし、Swagger を使用してサービスをテストできます。ただし、ClientId と Secret を使用してクライアントにサービスにアクセスさせようとしています。コードは AAD からアクセス トークンを取得できますが、サービス リソースの 1 つにアクセスしようとすると、常に 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).
問題のように見えるのは、リクエストで提示された Audience は https ですが、validParameters.ValidAudiences コレクションには http しか含まれていないことです。
オーディエンスを構成する方法が見当たりません。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;
}