![](/img/trans.png)
[英]Graph API for C#: 401 - Unauthorized: Access is denied due to invalid credentials. on /planner/plans
[英]Unauthorized: Access is denied due to invalid credentials . Microsoft Graph API for sharepoint
我正在使用以下代碼:
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 。
請幫忙。
查詢 API 當前不支持應用程序身份驗證。 請參閱搜索文檔,您將需要根據您要搜索的內容列出的委派權限:
旁注,通常授權的格式為“ 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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.