【发布时间】:2019-09-24 11:57:19
【问题描述】:
我正在开发一个应用程序,我需要使用 Microsoft Graph 来访问 OneDrive for Business 上的文件。我在 Azure 上创建了一个 Web 应用程序,并设法获取了身份验证令牌,并且能够使用 https://graph.microsoft.com/v1.0/me 检索用户信息。但是,如果我尝试使用 https://graph.microsoft.com/v1.0/me/drive/root/children 获取 OneDrive 的内容,则会收到拒绝访问错误。
我已经在 Graph Explorer 上进行了检查,并且能够毫无问题地获得查询结果。对于我的网络应用,我使用以下图表权限:
- People.Read - 委托
- Sites.ReadWrite.All - 委托
- Sites.ReadWrite.All - 应用程序
- Tasks.ReadWrite - 委托
- User.Export.All -Delegated
- User.Export.All - 应用程序
- User.Invite.All - 委托
- User.Invite.All - 应用程序
- User.Read - 委托
- User.Read.All - 委托
- User.Read.All - 应用程序
- User.ReadBasic.All - 委托
- User.ReadWrite - 委托
- User.ReadWrite.All - 委托
- User.ReadWrite.All - 应用程序
- offline_access - 委托
- openid - 委托
public async Task<string> GetTokenAsync()
{
HttpResponseMessage resp;
using(var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var req = new HttpRequestMessage(HttpMethod.Post,
$"https://login.microsoftonline.com/{tenant}/oauth2/token/");
req.Content = new FormUrlEncodedContent(new Dictionary<string, string>
{ { "grant_type", "password" },
{ "client_id", clientId },
{ "client_secret", clientSecret },
{ "resource", "https://graph.microsoft.com" },
{ "username", username },
{ "password", password },
{ "scope", "https%3A%2F%2Fgraph.microsoft.com%2F.default" }
});
resp = await httpClient.SendAsync(req);
string content = await resp.Content.ReadAsStringAsync();
var jsonObj = new JavaScriptSerializer().Deserialize<dynamic>(content);
string token = jsonObj["access_token"];
Console.WriteLine(token);
return token;
}
}
public async Task<string> SendGraphRequest(string requestUrl)
{
using(HttpClient httpClient = new HttpClient())
{
// Set up the HTTP GET request
HttpRequestMessage apiRequest =
new HttpRequestMessage(HttpMethod.Get, requestUrl);
apiRequest.Headers.UserAgent
.Add(new ProductInfoHeaderValue("OAuthStarter", "2.0"));
apiRequest.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", await GetTokenAsync());
// Send the request and return the response
HttpResponseMessage response = await httpClient.SendAsync(apiRequest);
var s = response.Content.ReadAsStringAsync();
Console.WriteLine(s.Result);
return s.Result;
}
}
我对图形 api 的调用是:
SendGraphRequest("https://graph.microsoft.com/v1.0/me/drive").Wait();
我从中得到的结果是:
{
"error": {
"code": "accessDenied",
"message": "There has been an error authenticating the request.",
"innerError": {
"request-id": "request-id",
"date": "2019-09-24T11:03:29"
}
}
}
【问题讨论】:
标签: microsoft-graph-api onedrive