如何通过Azure AD Graph API获取/搜索域名及子域名下的用户
用Microsoft Graph API检索指定域名及子域名下的用户
当然可以通过Microsoft Graph API实现这个需求,核心是利用users端点结合$filter参数进行条件筛选,以下是具体实现方式:
1. 精确匹配主域名(如avinash.com)
如果要获取所有邮箱/用户主体名称(UPN)后缀为avinash.com的用户,可使用endswith函数进行过滤:
基于邮箱字段筛选
GET https://graph.microsoft.com/v1.0/users?$filter=endswith(mail,'@avinash.com')
基于用户主体名称(UPN)筛选
如果部分用户未设置mail字段,用userPrincipalName更可靠(UPN格式通常为xxx@domain.com):
GET https://graph.microsoft.com/v1.0/users?$filter=endswith(userPrincipalName,'@avinash.com')
2. 匹配指定子域名(如IT.avinash.com、Finance.avinash.com)
方式一:指定多个子域名精确匹配
如果子域名是固定的几个,直接用or连接多个endswith条件:
GET https://graph.microsoft.com/v1.0/users?$filter=endswith(mail,'@it.avinash.com') or endswith(mail,'@finance.avinash.com') or endswith(mail,'@avinash.com')
方式二:匹配所有avinash.com的子域名(含主域名)
如果要覆盖所有以avinash.com为后缀的子域名(不管二级域名是什么),可以通过字符串替换+结尾匹配实现,避免误匹配类似avinash.com.cn的域名:
GET https://graph.microsoft.com/v1.0/users?$filter=endsWith(replace(mail, '@', '.'), '.avinash.com')
这个逻辑是把邮箱里的@替换成.,然后判断是否以.avinash.com结尾,这样xxx@avinash.com、xxx@it.avinash.com、xxx@finance.avinash.com都会被匹配到。
3. 注意事项
- 权限要求:确保你的访问令牌拥有
User.Read.All或Directory.Read.All权限,否则无法读取所有用户数据。 - 字段可用性:部分用户可能未配置
mail字段,优先使用userPrincipalName可提升兼容性。 - 分页处理:如果符合条件的用户数量较多,API会返回分页结果,需通过响应中的
@odata.nextLink获取后续数据。 - Postman操作:在Postman中发起请求时,直接将
$filter参数添加到请求的Params中即可,无需手动拼接URL。
内容的提问来源于stack exchange,提问作者Avinash Reddy
相关产品推荐
相关产品推荐

