You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MVC应用调用Graph API获取用户公司信息的技术问询

问题解决分享

感谢各位之前的热心回复,我已经成功实现需求,在这里梳理下核心思路和可用代码:

  • 我最初的核心需求是无需使用密钥获取当前用户(/me接口)的信息,但一开始仅用应用注册(App Reg)的密钥调用/me接口时,本质是对应用进行身份验证,而非关联到具体用户,因此接口调用失效。
  • 如果要通过/me接口获取用户信息,需要分两步:先获取应用注册令牌,再用该令牌请求用户令牌(两次令牌请求),这种方式对应用注册的权限要求更低,但流程相对繁琐。
  • 最终我选择了更直接的方案:通过应用注册权限直接请求指定用户的信息,调用的接口为:
    https://graph.microsoft.com/v1.0/users/{email}?$select=companyName
    

两种方案均可行,以下是我验证通过的代码片段:

public async Task<ActionResult> Index() 
{ 
    string clientId = "xxx"; 
    string clientSecret = "xxx"; 
    var email = User.Identity.Name; 

    AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/xxx.onmicrosoft.com/oauth2/token"); 
    ClientCredential creds = new ClientCredential(clientId, clientSecret); 
    AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", creds); 

    HttpClient http = new HttpClient(); 
    string url = $"https://graph.microsoft.com/v1.0/users/{email}?$select=companyName"; 

    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url); 
    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken); 
    HttpResponseMessage response = await http.SendAsync(request); 

    var json = await response.Content.ReadAsStringAsync(); 
    // 可根据需求将json反序列化为实体类进行后续处理
    return View(); 
}

内容的提问来源于stack exchange,提问作者Thomas Segato

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:56:58