未经授权:访问权限由于凭据无效而被拒绝。用于共享点的Microsoft Graph API

时间:2020-03-17 15:13:06

标签: c# sharepoint microsoft-graph-api

我正在使用以下代码:

  string cSecret = "XXXXXXXXXXXX";
    string cId = "XXXXXXXXXXXXXXX";
    var scopes = new string[] { "https://graph.microsoft.com/.default" };
    var confidentialClient = ConfidentialClientApplicationBuilder
  .Create(cId)
  .WithRedirectUri($"https://login.microsoftonline.com/XXXXX.onmicrosoft.com/v2.0")
  .WithClientSecret(cSecret)
  .Build();

    string requestUrl;
    GraphServiceClient graphClient =
    new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
    {
        var authResult = await confidentialClient
.AcquireTokenForClient(scopes)
.ExecuteAsync();

        // Add the access token in the Authorization header of the API request.
        requestMessage.Headers.Authorization =
        new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
    }));


    requestUrl = "https://graph.microsoft.com/beta/search/query";

    var searchRequest = new
    {
        requests = new[]
                {
        new
        {
            entityTypes = new[] {"microsoft.graph.driveItem"},
            query = new
            {
                query_string = new
                {
                    query = "policy AND filetype:docx"
                }
            },
            from = 0,
            size = 25
        }
    }
    };
    //construct a request
    var message = new HttpRequestMessage(HttpMethod.Post, requestUrl);
    var jsonPayload = graphClient.HttpProvider.Serializer.SerializeObject(searchRequest);
    message.Content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
    await graphClient.AuthenticationProvider.AuthenticateRequestAsync(message);
    var response = await graphClient.HttpProvider.SendAsync(message);
    //process response 
    var content = await response.Content.ReadAsStringAsync();
    var result = JObject.Parse(content);
    var searchItems = result["value"].First["hitsContainers"].First["hits"].Select(item =>
    {
        var itemUrl = (string)item["_source"]["webUrl"];
        return itemUrl;
    });

运行此代码时,出现此异常:

未授权:由于凭据无效,访问被拒绝。 您无权使用您提供的凭据查看此目录或页面。 我已设置应用权限https://graph.microsoft.com/Sites.Read.All

请帮助。

1 个答案:

答案 0 :(得分:0)

查询API当前不支持应用程序身份验证。参考search documentation,您将需要根据要搜索的内容列出委派的权限:

  • 邮件阅读
  • Files.Read.All
  • 日历。阅读
  • ExternalItem.Read.All

旁注,通常 Authority 的格式为“ {https://login.microsoftonline.com/XXXXX.onmicrosoft.com/v2.0”,而不是 Redirect Uri 。您可能需要更改ConfidentialClientApplicationBuilder以使用 .WithAuthority()。然后,您可以使用 .WithRedirectUri(...)使用您在应用程序注册中设置的值(如果您有一个,因为它们是可选的)。

请参阅示例代码段:

var redirectUri = "https://localhost:8080";    
var authority = $"https://login.microsoftonline.com/{config["tenantId"]}/v2.0";

List<string> scopes = new List<string>();
scopes.Add("https://graph.microsoft.com/.default");

var cca = ConfidentialClientApplicationBuilder.Create(clientId)
                                              .WithAuthority(authority)
                                              .WithRedirectUri(redirectUri)
                                              .WithClientSecret(clientSecret)
                                              .Build();