简体   繁体   中英

Unauthorized: Access is denied due to invalid credentials . Microsoft Graph API for sharepoint

I am using below code:

  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;
    });

When i run this code , i get this exception:

Unauthorized: Access is denied due to invalid credentials. You do not have permission to view this directory or page using the credentials that you supplied. I have set app permission https://graph.microsoft.com/Sites.Read.All .

Please help.

Application authentication is not currently supported for the query API. Refer to the search documentation , you will need the delegated permission(s) listed depending on what you are searching for:

  • Mail.Read
  • Files.Read.All
  • Calendars.Read
  • ExternalItem.Read.All

Side note, typically the Authority is in the format of " https://login.microsoftonline.com/XXXXX.onmicrosoft.com/v2.0 ", not the Redirect Uri . You may need to change the ConfidentialClientApplicationBuilder to use .WithAuthority() . You can then use .WithRedirectUri(...) using the value set in your app registration (if you have one as they are optional).

See snippet of code from a sample:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM