仅从具有有限权限的 Azure AD 查询基本 UserInfo

Query only basic UserInfo from Azure AD with limited permissions

我正在尝试建立我们公司所有员工的电子邮件地址列表。 这是在 Azure 上的 Web 应用 运行 中,使用 Azure AD 身份验证。该应用程序使用 .NET Framework 4.6,并使用 Microsoft.Owin.Security 包连接到 Azure AD。

我可以进行身份​​验证,我已通过应用注册中定义的角色获得授权。到目前为止,一切都很好。 我可以查看我自己的用户配置文件。这使用 Microsoft.Azure.ActiveDirectory.GraphClient 包来构建查询,而不是手动创建 HTTPRequests。

string userObjectID = ClaimsPrincipal.Current
    .FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,
    async () => await authorizationHelper.GetTokenForApplication());

var result = await activeDirectoryClient.Users
    .Where(u => u.ObjectId.Equals(userObjectID))
    .ExecuteAsync();

IUser user = result.CurrentPage.ToList().First();

AD 计算我的查询,发现它只有 returns 我,并推断出我可以查看自己的信息。执行成功,只返回我。

在另一个页面上,我想显示公司使用的邮件地址(标记用户、提前输入、检查是否存在等)我尝试以下操作:

result = await activeDirectoryClient.Users
    .ExecuteAsync();
return result.CurrentPage
    .ToList();

这失败了,"insufficient privileges"。我不允许查看我猜的整个用户。我的委派权限是 "Read all users' basic profiles"、meaning:

Allows the app to read the basic profile of all users in the organization on behalf of the signed-in user. The following properties comprise a user’s basic profile: display name, first and last name, photo, and email address.

所以,我尝试过滤:

result = await activeDirectoryClient.Users
    .Where(u => u.Mail.StartsWith(str))
    .ExecuteAsync();
return result.CurrentPage
    .ToList();

但这仍然给了我整个用户,我又一次被 "insufficient privileges" 击中了。所以我尝试

result = await activeDirectoryClient.Users
    .Where(u => u.Mail.StartsWith(str))
    .Select (u => u.Mail)
    .ExecuteAsync();
return result.CurrentPage
    .ToList();

这给出了神秘的运行时错误(来自荷兰语的免费翻译)

GenericArguments[1], System.String, Microsoft.Azure.ActiveDirectory.GraphClient.Extensions
.ReadOnlyQueryableSet.`2[TSource,TISource] conflicts with type TISource.

而且我很茫然。 ActiveDirectoryClient好像没有源码,常用的GraphAPIdoesn't even mention selecting only basic info.

"easy" 解决方案是 "just get more app permissions",但这需要大量时间来通过官僚机构。而且我应该能够获取所有用户的邮件,对吗?

首先,您不需要为 "Query only basic UserInfo from Azure AD with limited permissions" 做任何特别的事情。您只需查询用户,它会将您无权访问的任何字段初始化为 nullInsufficient privileges 表示您根本不允许查看用户。红旗.

起初我以为我的tokencache有问题。它是。然后我修好了。仍然有错误。

通过使用 Nan Yu 链接的 online tool 查看不同应用程序中的几个令牌,我发现我缺少在我的令牌中查看用户基本配置文件的实际权限。 还是没有得到token中的权限,发现虽然勾选了"Delegated Permissions"下的checkbox,但是后面的"Grant Permissions"选项没有成功使用

PSA:不要假设所有勾选的框实际上都被授予了。检查应用服务它具有哪些权限。如果你的公司允许的话,那就是。