简体   繁体   English

未经授权:访问被拒绝,因为凭证无效。 用于共享点的 Microsoft Graph API

[英]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 .我已设置应用权限https://graph.microsoft.com/Sites.Read.All

Please help.请帮忙。

Application authentication is not currently supported for the query API.查询 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 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 .旁注,通常授权的格式为“ https://login.microsoftonline.com/XXXXX.onmicrosoft.com/v2.0 ”,而不是Redirect Uri You may need to change the ConfidentialClientApplicationBuilder to use .WithAuthority() .您可能需要更改 ConfidentialClientApplicationBuilder 以使用.WithAuthority() You can then use .WithRedirectUri(...) using the value set in your app registration (if you have one as they are optional).然后,您可以使用.WithRedirectUri(...)使用应用程序注册中设置的值(如果您有一个,因为它们是可选的)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C# 的图表 API:401 - 未经授权:由于凭据无效,访问被拒绝。 在 /planner/plans - Graph API for C#: 401 - Unauthorized: Access is denied due to invalid credentials. on /planner/plans IIS8未经授权:由于凭据无效而拒绝访问 - IIS8 Unauthorized: Access is denied due to invalid credentials 调用aspx页的EXE程序获取:401-未经授权:由于凭据无效,访问被拒绝 - EXE program calling aspx page gets: 401 - Unauthorized: Access is denied due to invalid credentials Microsoft Graph API Mail.Send 访问被拒绝 - Microsoft Graph API Mail.Send Access Denied C# 中的 Microsoft Graph“访问被拒绝。检查凭据并重试” - Microsoft Graph "Access is denied. Check credentials and try again" in C# 未经授权:通过Web API拒绝访问 - Getting Unauthorized : Access denied on web api Microsoft Graph API,发送电子邮件响应:StatusCode:401 ReasonPhrase:“未经授权” - Microsoft Graph API, sending email response: StatusCode: 401 ReasonPhrase: 'Unauthorized' 如何使用 Microsoft Graph API 和 Graph Client 添加 SharePoint 选项卡? - How to add a SharePoint tab using Microsoft Graph API and Graph Client? Microsoft Graph API 授权错误:无效的受众 - Microsoft Graph API authorization error: Invalid Audience Microsoft Graph Api令牌无效或未授权? - Microsoft Graph Api token invalid or not authorized?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM