关于ADAL查询安全组及Azure Web API登录WPF应用的技术咨询
用ADAL结合Microsoft Graph API查询Azure AD安全组
嘿,你已经搞定了WPF基于ADAL的Azure AD登录,这步走得很稳!要查询安全组的话,咱们可以借助Microsoft Graph API来实现,刚好你已经拿到了ADAL的访问令牌,直接就能用上。下面给你详细说下实现步骤和代码示例:
第一步:确保应用有对应的API权限
首先得在Azure AD的应用注册里,给你的WPF应用添加Microsoft Graph的权限,比如:
Directory.Read.All(允许读取目录内的所有组信息)- 或者更精细的
User.Read.All+Group.Read.All
记得要给这些权限授予管理员同意,不然普通用户调用的时候会报错。
第二步:用ADAL获取访问Graph API的令牌
你现有的代码是获取针对自己Web API的令牌,现在需要调整下resource参数,改成Graph API的资源ID:https://graph.microsoft.com。这样拿到的令牌就能用来调用Graph接口了:
// 替换成你的租户ID或者域名 string authority = "your-tenant-id-or-domain"; // Graph API的资源标识符 string graphResource = "https://graph.microsoft.com"; string clientId = "your-client-id"; string redirectUri = "your-redirect-uri"; // 比如msal{clientId}://auth(WPF常用的格式) AuthenticationContext authContext = new AuthenticationContext($"https://login.windows.net/{authority}"); // 获取针对Graph API的令牌 AuthenticationResult tokenAuthResult = authContext.AcquireTokenAsync( graphResource, clientId, new Uri(redirectUri), new PlatformParameters(PromptBehavior.Auto) ).Result; if (tokenAuthResult == null) { // 处理令牌获取失败的情况 return; }
第三步:调用Graph API查询安全组
拿到令牌后,就可以用HttpClient来调用Graph的接口了。比如要获取当前登录用户所属的所有安全组,可以调用/me/memberOf端点,然后过滤出安全组类型的结果:
using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenAuthResult.AccessToken); // 调用Graph API获取用户所属的组 HttpResponseMessage response = await client.GetAsync("https://graph.microsoft.com/v1.0/me/memberOf"); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); // 解析JSON,提取安全组信息 // 你可以用Newtonsoft.Json或者System.Text.Json来反序列化 // 示例用System.Text.Json: var groupResponse = JsonSerializer.Deserialize<GroupResponse>(jsonResponse); // 过滤出安全组(groupType包含"Security"的) var securityGroups = groupResponse.Value .Where(g => g.GroupTypes != null && g.GroupTypes.Contains("Security")) .ToList(); // 现在securityGroups里就是当前用户所属的安全组列表了 foreach (var group in securityGroups) { Console.WriteLine($"组名:{group.DisplayName},组ID:{group.Id}"); } } else { // 处理请求失败的情况,比如打印错误信息 string error = await response.Content.ReadAsStringAsync(); Console.WriteLine($"请求失败:{error}"); } } // 对应的实体类,用来反序列化Graph的返回结果 public class GroupResponse { public List<AzureADGroup> Value { get; set; } } public class AzureADGroup { public string Id { get; set; } public string DisplayName { get; set; } public List<string> GroupTypes { get; set; } // 可以根据需要添加更多字段,比如Description、Mail等 }
额外说明
- 如果要查询所有安全组(不是当前用户所属的),可以调用
https://graph.microsoft.com/v1.0/groups?$filter=groupTypes/any(c:c eq 'Security')这个端点。 - 注意ADAL现在已经是维护模式了,微软推荐用MSAL(Microsoft Authentication Library)来替代,不过如果你暂时不想换,上面的方法完全能用。
- 记得处理异步操作,尽量避免用
.Result,而是用await,这样WPF界面不会卡顿。
内容的提问来源于stack exchange,提问作者scottsanpedro
相关产品推荐
相关产品推荐

