【发布时间】:2016-12-03 14:09:56
【问题描述】:
我的 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
}
以上是用于检索身份验证代码的代码,然后是尝试检索访问令牌的代码。我们没有 client_secret,因为 secret 仅适用于 Web 应用程序,这是一个本机桌面 WPF 应用程序。我读过这不是问题。我在网上关注了很多教程和官方文档,主要是the official Graph authorization doc,但我仍然无法弄清楚我做错了什么。任何帮助将不胜感激,谢谢。
【问题讨论】:
标签: c# azure active-directory oauth-2.0 microsoft-graph-api