2017-02-14 112 views
2

我使用適用於Web API的Visual Studio 2015 Update 3創建了一個基本項目(沒有任何自定義,裸露骨骼),並按照here指令將其部署到Azure(免費帳戶)。 然後我用下面的代碼創建了一個控制檯客戶端。從Azure Web API獲取未經授權

public static async Task<bool> ReadValues() 
    { 
     try 
     { 
      // Authenticate the user and get a token from Azure AD 
      //AuthenticationResult authResult = await AuthContext.AcquireTokenSilentAsync(Resource, ClientId); 
      AuthenticationResult authResult = AuthContext.AcquireToken(Resource, ClientId, RedirectUri); 

      // Create an HTTP client and add the token to the Authorization header 
      HttpClient httpClient = new HttpClient(); 
      httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
       //"Bearer" 
       authResult.AccessTokenType 
       , authResult.AccessToken); 

      // Call the Web API to get the values 
      var requestUri = new Uri(WebApiUri, "api/values"); 
      Console.WriteLine("Reading values from '{0}'.", requestUri); 
      HttpResponseMessage httpResponse = await httpClient.GetAsync(requestUri); 
      Console.WriteLine("HTTP Status Code: '{0}'", httpResponse.StatusCode.ToString()); 
      //Console.WriteLine("HTTP Header: '{0}'", httpClient.DefaultRequestHeaders.Authorization.ToString()); 
      if (httpResponse.IsSuccessStatusCode) 
      { 
       // 
       // Code to do something with the data returned goes here. 
       // 
       var s = await httpResponse.Content.ReadAsStringAsync(); 
       Console.WriteLine(s); 
      } 
      else 
      { 
       Console.ForegroundColor = ConsoleColor.Red; 
       Console.WriteLine(httpResponse.ReasonPhrase); 
      } 
      return (httpResponse.IsSuccessStatusCode); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
     } 
     return false; 
    } 

它正常工作,當我在本地調試從Visual Studio運行Web API,但是當我把它部署到Azure的,它返回未經授權。 一些常見的事情,我可能會問:

  1. 我收到有效承載令牌
  2. 我在Azure的AD的機器人HTHE WEB API和客戶端
  3. 所創建的應用程序註冊客戶端和Web API使用了正確的重定向,資源URI
  4. 我使用的登錄賬號相同,用於創建Azure的帳戶之一,它具有域/ AD/API中的全部特權

在API方面,這是整個startup.auth.cs

using System.Configuration; 
using System.IdentityModel.Tokens; 
using Microsoft.Owin; 
using Microsoft.Owin.Security.ActiveDirectory; 
using Owin; 
using WebApi; 

[assembly: OwinStartup("default", typeof(Startup))] 

namespace WebApi 
{ 
    public partial class Startup 
    { 
     // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 
     public void ConfigureAuth(IAppBuilder app) 
     { 
      app.UseWindowsAzureActiveDirectoryBearerAuthentication(
       new WindowsAzureActiveDirectoryBearerAuthenticationOptions 
       { 
        Tenant = ConfigurationManager.AppSettings["ida:Tenant"], 
        TokenValidationParameters = new TokenValidationParameters { 
         ValidAudience = ConfigurationManager.AppSettings["ida:Audience"] 
        }, 
       }); 
     } 
    } 
} 

我還需要檢查?

其他參考資料

https://www.simple-talk.com/cloud/security-and-compliance/azure-active-directory-part-3-developing-native-client-applications/

+0

您可以在您註冊身份驗證中間件的位置添加代碼(我假設您使用的是OWIN)。 – juunas

+0

那麼,auth配置看起來與我所做的API非常相似。如果'aud'聲明值與'ida:Audience'和'ida:Tenant'的配置文件匹配,那麼它可能是OWIN中間件根本沒有運行嗎? – juunas

+0

嗨Juaunas,用其他代碼更新了這個問題。我跟蹤了我共享的兩個鏈接,所有代碼都來自VS代碼模板和這兩個鏈接。 – Diceyus

回答

0

感謝來自Juunas誰與工作副本提供給我的幫助,我是能夠縮小的原因。當我將一個調試器附加到Web API的Azure實例時,我能夠看到壞Audience的異常。在試圖追溯我的步驟時,我發現從Visual Studio進行部署時,我選擇了導致問題導致web.config發生更改的設置中的Enterprise Authentication。不選擇該選項,我可以通過不記名令牌訪問API。

相關問題