2015-12-16 24 views
5

我有一個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; 
    } 
+0

您需要用部署中的實際參數替換方括號中的標識符。 – MvdD

+0

感謝@MvdD,但是我將這些實際參數用於本文。正如你可以從帖子的頂部看到的,這用於工作,現在沒有。 –

+0

嗨@GraemeWilson,你是否仍然需要回答這個問題,或者你找到了解決方案? – juvchan

回答

7

你的問題有什麼做的有效受衆。您可能有兩種選擇:

選項1.嘗試獲取帶有WebAPI客戶端ID的令牌作爲AcquireToken方法的「資源」參數,而不是其Uri。

選項2.如果以前的方法不起作用,您必須使用Azure Resources Explorer來修改App Service API的身份驗證設置。導航到您的Web API,在config節點下找到authSettings JSON文檔,並修改(在更改爲讀取/寫入模式後)陣列allowedAudiences以滿足您的需求。在你的情況下,你可能需要更改httphttps

+0

我還會補充說,當Loul說「導航到您的Web API」時,他意味着您應該使用資源管理器頂部的搜索框。如果您在搜索之前開始擴展提供商和訂閱,那麼它似乎不起作用。 最終我發現我的API在訂閱/ mysubname/resourceGroups/myresourcegroupname/providers/Microsoft.Web/sites –

0

在我的ASP.NET 4.5 Web應用程序中,我發現我必須指定有效的受衆以避免引發運行時異常。

public partial class Startup 
{ 
    private static string _aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"]; 
    private static string _tenant = ConfigurationManager.AppSettings["ida:Tenant"]; 
    private static string _realm = ConfigurationManager.AppSettings["ida:Wtrealm"]; 
    private static string _metadataAddress = string.Format("{0}/{1}/federationmetadata/2007-06/federationmetadata.xml", _aadInstance, _tenant); 
    private static string _authority = String.Format(CultureInfo.InvariantCulture, _aadInstance, _tenant); 

    public void ConfigureAuth(IAppBuilder app) 
    { 
     app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); 

     app.UseCookieAuthentication(new CookieAuthenticationOptions()); 

     app.UseWsFederationAuthentication(
      new WsFederationAuthenticationOptions 
      { 
       Wtrealm = _realm, 
       MetadataAddress = _metadataAddress, 
       TokenValidationParameters = new TokenValidationParameters 
       { 
        ValidAudiences = new string[] { "spn:" + _realm } 
       } 
      } 
     ); 
    } 
} 
相關問題