使用证书的Azure Active Directory守护程序客户端

Muh*_*eed 7 azure azure-active-directory

我一直在使用GitHub上Azure Active Directory的证书示例查看守护程序应用程序中的Azure AD官方身份验证.Web API服务似乎不了解客户端.

  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.

dst*_*kis 3

好问题,这无疑是误导性的。答案是肯定的 - 在 Azure AD 租户中注册的任何 Web 客户端都可以使用代码示例中描述的客户端凭据流程获取令牌来访问 Web API。

如果您不希望出现这种行为,您有 2 个选择:

  1. 通过编辑应用程序清单,为您的 Web API至少定义一个应用程序角色(请参阅此示例)。您可以定义一些有意义的内容,例如“admin”或更通用的内容,例如“full_access”。在 Web API 代码中,您可以在授权请求之前检查相应的角色声明是否存在。如果选择此策略,Azure AD 租户管理员将能够按照您的预期使用“其他应用程序的权限”部分向各个客户端授予访问权限。
  2. 另一种策略是简单地根据某种 ACL 或白名单检查传入令牌的声明。常见的做法是检查appid声明中是否有特定的知名客户端 ID。

示例代码对范围声明的使用确实具有误导性。该 API 旨在与代表用户(委托令牌)和使用应用程序身份(客户端凭据)访问 API 的客户端配合使用。这就是为什么你会在那里看到范围声明。

在运行时,您引用的验证逻辑会发现scopeClaim == null. 然后,它将使用ClaimTypes.NameIdentifier声明(也称为sub声明)来识别客户端应用程序以及属于该特定应用程序的 POST 或 GET 待办事项。

此示例不限制 Azure AD 租户中的哪些客户端可以访问 Web API。

希望这可以帮助。