v2身份驗證端點當前不支持在沒有UI交互的情況下進行身份驗證的僅應用程序範圍。您可以通過在Azure AD中登錄,使用Microsoft身份驗證庫(MSAL)獲取訪問令牌和刷新令牌。然後,您可以使用訪問令牌和刷新令牌whiteout用戶進行交互。
刷新令牌有效期爲14天,持續使用時可以有效期長達90天。 90天后,用戶將被要求重新認證。
下面是一個樣本是供你參考上傳PDF到OneDrive爲繁茂:
public static void CreateItem(string accessToken)
{
string itemCreateUri = "https://graph.microsoft.com/v1.0/me/drive/root/children";
string itemData = "{\"name\":\"book2.pdf\",\"file\":{}}";
var itemCreatedResult = RESTRequsetHelper.RESTRequsetHelper.PostAsync(itemCreateUri, itemData, accessToken).Result;
DriveItem item = new DriveItem(itemCreatedResult);
string itemUploadUri= $"https://graph.microsoft.com/v1.0/me/drive/items/{item.Id}/content";
System.IO.FileStream fs = System.IO.File.Open(@"C:\users\user1\desktop\book1.pdf",System.IO.FileMode.Open);
StreamContent streamContent = new StreamContent(fs);
var uploadResult= RESTRequsetHelper.RESTRequsetHelper.SendHttpRequest(HttpVerb.PUT, itemUploadUri, streamContent, accessToken).Result;
fs.Close();
}
public static async Task<string> PostAsync(string uri, string jsonBody, string accessToken)
{
return await SendHttpRequest(HttpVerb.POST, uri, jsonBody, accessToken);
}
private static async Task<string> SendHttpRequest(HttpVerb ver, string uri, string jsonBody, string accessToken)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", $"{accessToken}");
var stringContent = new StringContent(jsonBody,Encoding.UTF8,"application/json");
if (ver == HttpVerb.POST)
{
return await client.PostAsync(uri, stringContent).ContinueWith<string>((response) =>
{
return response.Result.Content.ReadAsStringAsync().Result;
});
}
else
{
return await client.PutAsync(uri, stringContent).ContinueWith<string>((response) =>
{
return response.Result.Content.ReadAsStringAsync().Result;
});
}
}
public static async Task<string> SendHttpRequest(HttpVerb ver, string uri, StreamContent steamBody, string accessToken)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", $"{accessToken}");
if (ver == HttpVerb.POST)
{
return await client.PostAsync(uri, steamBody).ContinueWith<string>((response) =>
{
return response.Result.Content.ReadAsStringAsync().Result;
});
}
else
{
return await client.PutAsync(uri, steamBody).ContinueWith<string>((response) =>
{
return response.Result.Content.ReadAsStringAsync().Result;
});
}
}
}
謝謝。真的需要具有僅應用程序範圍的身份驗證,無需UI交互。 希望團隊可以帶來這個功能 – Jens