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

使用RestSharp请求Microsoft Graph返回未授权,求Token获取方案

解决Microsoft Graph未授权问题:添加访问令牌到RestSharp请求

你当前的请求返回未授权,核心原因是没有在请求中携带Microsoft Graph的有效访问令牌。结合你已经用OpenIDConnect完成Azure初始授权的场景,下面分两种常见授权方式给出解决方案:


方式1:使用用户上下文的Delegated权限(推荐,适配已有用户登录场景)

既然用户已经通过OpenIDConnect登录,你可以从当前用户的身份凭证中获取针对Microsoft Graph的访问令牌,添加到RestSharp请求的Authorization头中。

步骤:

  1. 确保你的OpenIDConnect授权请求中包含了Microsoft Graph的必要权限(比如User.Read),否则无法获取对应的令牌。
  2. 从当前请求上下文提取访问令牌,添加到RestSharp请求头。

修改后的代码:

protected void btnRestSharp_Click(object sender, EventArgs e)
{
    ClaimsIdentity identity = this.User.Identity as ClaimsIdentity;
    string email = identity.Claims.FirstOrDefault(x => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name")?.Value;

    // 获取Microsoft Graph的访问令牌(Web Forms环境下通过Context获取)
    string accessToken = Context.GetTokenAsync("access_token").Result;

    var client = new RestSharp.RestClient("https://graph.microsoft.com");

    var request = new RestSharp.RestRequest($"/v1.0/users/{email}?$select=jobTitle,employeeId,officeLocation,department", RestSharp.Method.Get);
    // 添加Authorization认证头
    request.AddHeader("Authorization", $"Bearer {accessToken}");

    var callbackResult = client.Execute(request);

    if (callbackResult.StatusCode == HttpStatusCode.OK)
    {
        lblRestSharp.Text = "OK";
        // 可进一步解析返回的JSON数据,比如用JsonConvert反序列化到实体类
    }
    else
    {
        lblRestSharp.Text = $"status code: {callbackResult.StatusCode.ToString()}, 错误信息: {callbackResult.Content}";
    }
}

方式2:使用应用权限(Client Credentials流,无用户上下文)

如果你的场景不需要依赖用户登录,直接用应用身份访问Graph,就需要通过Client ID和Client Secret获取令牌,再调用接口。

步骤:

  1. 在Azure AD应用注册中添加Microsoft Graph的应用权限(比如User.Read.All),并完成管理员同意操作。
  2. 调用Azure AD令牌端点获取access token,再将令牌带入Graph请求。

代码示例:

// 封装获取Graph访问令牌的方法
private string GetGraphAccessToken()
{
    var client = new RestSharp.RestClient("https://login.microsoftonline.com/{你的租户ID}/oauth2/v2.0/token");
    var request = new RestSharp.RestRequest(RestSharp.Method.Post);
    
    request.AddParameter("client_id", "{你的Client ID}");
    request.AddParameter("scope", "https://graph.microsoft.com/.default");
    request.AddParameter("client_secret", "{你的Client Secret}");
    request.AddParameter("grant_type", "client_credentials");

    var response = client.Execute(request);
    if (response.StatusCode == HttpStatusCode.OK)
    {
        // 解析返回的JSON提取access_token
        var tokenData = JsonConvert.DeserializeObject<dynamic>(response.Content);
        return tokenData.access_token;
    }
    else
    {
        throw new Exception($"获取Token失败: {response.Content}");
    }
}

// 修改后的按钮点击方法
protected void btnRestSharp_Click(object sender, EventArgs e)
{
    ClaimsIdentity identity = this.User.Identity as ClaimsIdentity;
    string email = identity.Claims.FirstOrDefault(x => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name")?.Value;

    try
    {
        string accessToken = GetGraphAccessToken();

        var client = new RestSharp.RestClient("https://graph.microsoft.com");
        var request = new RestSharp.RestRequest($"/v1.0/users/{email}?$select=jobTitle,employeeId,officeLocation,department", RestSharp.Method.Get);
        request.AddHeader("Authorization", $"Bearer {accessToken}");

        var callbackResult = client.Execute(request);

        if (callbackResult.StatusCode == HttpStatusCode.OK)
        {
            lblRestSharp.Text = "OK";
        }
        else
        {
            lblRestSharp.Text = $"status code: {callbackResult.StatusCode.ToString()}, 错误信息: {callbackResult.Content}";
        }
    }
    catch (Exception ex)
    {
        lblRestSharp.Text = $"错误: {ex.Message}";
    }
}

注意事项:

  • 替换代码中的{你的租户ID}、{你的Client ID}、{你的Client Secret}为Azure AD应用注册中的实际值。
  • 权限配置需匹配场景:Delegated权限依赖用户登录,应用权限需要管理员提前同意。
  • 生产环境中禁止硬编码Client Secret,建议用Azure Key Vault等安全存储方式托管敏感信息。

内容的提问来源于stack exchange,提问作者Brenda Lynn Anderson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 20:12:05