2015-12-22 52 views
4

我一直在尋找官方Authenticating to Azure AD in daemon apps with certificates在GitHub上的Azure Active Directory示例。 Web API服務似乎沒有任何客戶知識。Azure活動目錄守護進程客戶端使用證書

  1. 您不會被告知登錄到Azure並使用「權限到其他應用程序」部分爲守護程序客戶端添加訪問Web API的權限。
  2. Web API控制器操作不檢查調用者的聲明以確保它是客戶端應用程序。它有這樣的代碼,雖然我不完全理解:
 
public IEnumerable Get() 
{ 
    // 
    // The Scope claim tells you what permissions the client application has in the service. 
    // In this case we look for a scope value of user_impersonation, or full access to the service as the user. 
    // 
    Claim scopeClaim = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope"); 
    if (scopeClaim != null) 
    { 
     if (scopeClaim.Value != "user_impersonation") 
     { 
      throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, ReasonPhrase = "The Scope claim does not contain 'user_impersonation' or scope claim not found" }); 
     } 
    } 

    // A user's To Do list is keyed off of the NameIdentifier claim, which contains an immutable, unique identifier for the user. 
    Claim subject = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier); 

    return from todo in todoBag 
      where todo.Owner == subject.Value 
      select todo; 
} 

我是在想,我的Azure的AD註冊的任何客戶端可以訪問Web API,與此樣本的安裝方式糾正。

回答

2

好問題,這是無可否認的誤導。答案是肯定的 - 在Azure AD租戶中註冊的任何Web客戶端都可以使用代碼示例中描述的客戶端憑據流獲取令牌以訪問Web API。

如果不希望這種行爲,你有兩個選擇:

  1. 通過編輯應用程序清單(see this sample)定義爲您的Web API至少一個應用程序角色。你可以定義一些像「admin」這樣有意義的東西,或者像「full_access」這樣的更通用的東西。在您的Web API代碼中,您可以在授權請求之前檢查是否存在相應的角色聲明。如果您選擇此策略,則Azure AD租戶管理員將能夠按照您的預期,使用權限到其他應用程序部分向個別客戶端授予訪問權限。
  2. 另一種策略是簡單地檢查傳入的令牌對某種ACL或白名單的聲明。通常的做法是檢查針對特定衆所周知的客戶端ID的索賠appid索賠。

示例代碼確實誤導了其使用範圍索賠。該API被編寫爲與代表用戶(委託令牌)和使用應用程序身份(客戶端憑證)訪問API的客戶端一起工作。這就是爲什麼你在那裏看到範圍要求。

在運行時,您引用的驗證邏輯將找到scopeClaim == null。然後它將使用ClaimTypes.NameIdentifier聲明(又名sub聲明)來標識屬於該特定應用程序的客戶端應用程序和POST或GET todo。

此示例不限制Azure AD租戶中的哪些客戶端可以訪問任何Web API。

希望這會有所幫助。