我的WPF桌面应用程序(C#)试图通过Microsoft Graph API读取用户的Outlook电子邮件。我卡在了身份验证过程中;我已经收到了身份验证代码,现在我正在尝试从Azure获取访问令牌,但是每当发送请求以获取访问令牌时,都会收到HTTP 400错误代码:
/**** Auth Code Retrieval ****/
string authCodeUrl = "https://login.microsoftonline.com/common/oauth2/authorize";
authCodeUrl += "?client_id" = clientId;
authCodeUrl += "&redirect_uri=" + redirectUri;
authCodeUrl += "&response_type=code";
authCodeUrl += "&resource=https%3A%2F%2Fgraph.microsoft.com%2F";
Process.start(authUrl); // User logs in, we get the auth code after login
string code = "......"; // Hidden for this post
/**** Access Token Retrieval ****/
string tokenUrl = "https://login.microsoftonline.com/common/oauth2/token"
string content = "grant_type=authorization_code";
content += "&client_id=" + clientId;
content += "&resource=https%3A%2F%2Fgraph.microsoft.com%2F";
content += "&code=" + code;
content += "&redirect_uri=" + redirectUri;
WebRequest request = WebRequest.Create(tokenUrl);
request.ContentType = "application/x-www-form-urlencoded";
byte[] data = Encoding.UTF8.GetBytes(content);
request.ContentLength = data.Length;
request.Method = "POST";
try
{
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
WebResponse response = request.GetResponse(); // This throws exception
}
catch (Exception error) // This catches the exception
{
Console.WriteLine(error.Message); // Outputs 400, bad request
}
上面的代码用于检索授权代码,然后尝试检索访问令牌。我们没有客户机密,因为机密仅适用于 Web 应用程序,而这是一款本地桌面 WPF 应用程序。我已经阅读过许多在线教程和官方文档,主要包括官方 Graph 授权文档,但我仍然无法弄清楚自己做错了什么。如有任何帮助,将不胜感激,谢谢。