2015-12-22 54 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。

希望这会有所帮助。