我尝试从Office 365 excel访问我的excel,但是失败。
这是我的代码:
namespace active_directory_wpf_msgraph_v2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
//Set the API Endpoint to Graph 'me' endpoint
string graphAPIEndpoint = "https://graph.microsoft.com/v1.0/me/drive/root/search(q='Book.xlsx')";
//Set the scope for API call to user.read
string[] scopes = new string[] { "user.read","Files.ReadWrite", "Files.ReadWrite.Selected" };
public MainWindow()
{
InitializeComponent();
}
/// <summary>
/// Call AcquireToken - to acquire a token requiring user to sign-in
/// </summary>
private async void CallGraphButton_Click(object sender, RoutedEventArgs e)
{
TokenCache tokenCache = new TokenCache();
// load tokens from file
string tokenPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Excel365Test");
if (!System.IO.Directory.Exists(tokenPath)) { System.IO.Directory.CreateDirectory(tokenPath); }
tokenPath = Path.Combine(tokenPath, "tokens.dat");
if (System.IO.File.Exists(tokenPath))
{
tokenCache.Deserialize(System.IO.File.ReadAllBytes(tokenPath));
}
// this is the OAUTH 2.0 TOKEN ENDPOINT from https://portal.azure.com/ -> Azure Active Directory -> App Registratuons -> End Points
var authenticationContext = new AuthenticationContext(graphAPIEndpoint, tokenCache);
// only prompt when needed, you'll get a UI the first time you run
var platformParametes = new PlatformParameters(PromptBehavior.Auto);
var authenticationResult = authenticationContext.AcquireTokenAsync("https://graph.microsoft.com/",
"MyclientID", // Application ID from https://portal.azure.com/
new Uri("https://login.live.com/oauth20_desktop.srf"), // Made up redirect URL, also from https://portal.azure.com/
platformParametes).Result;
string token = authenticationResult.AccessToken;
// save token so we don't need to re-authorize
System.IO.File.WriteAllBytes(tokenPath, tokenCache.Serialize());
// use the token with Microsoft.Graph calls
GraphServiceClient client = new GraphServiceClient(new DelegateAuthenticationProvider(
(requestMessage) =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
return Task.FromResult(0);
}));
}
/// <summary>
/// Perform an HTTP GET request to a URL using an HTTP Authorization header
/// </summary>
public async Task<string> GetHttpContentWithToken(string url, string token)
{
var httpClient = new System.Net.Http.HttpClient();
System.Net.Http.HttpResponseMessage response;
try
{
var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
//Add the token in Authorization header
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
response = await httpClient.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
return content;
}
catch (Exception ex)
{
return ex.ToString();
}
}
}
}
在那里在authenticationResult弹出错误。 错误显示:
请帮助我解决这个问题。