Azure AD OAuth2 访问令牌请求错误 - 400 错误请求

Obs*_*ian 3 c# active-directory azure oauth-2.0 microsoft-graph-api

我的 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
}
Run Code Online (Sandbox Code Playgroud)

以上是用于检索身份验证代码的代码,然后是尝试检索访问令牌的代码。我们没有 client_secret,因为机密仅适用于 Web 应用程序,并且这是本机桌面 WPF 应用程序。我已经读到这不是问题。我在网上看了很多教程和官方文档,主要是官方的Graph授权文档,但我仍然无法弄清楚我做错了什么。任何帮助将不胜感激,谢谢。

Obs*_*ian 5

我使用fiddler调试请求,发现完整的错误信息:The user or administrator has not allowed to use the application。我在谷歌上搜索了这条消息,发现了一些堆栈文章和 github 问题线程,它们引导我找到解决方案:我的请求一直在基本 URL 中使用“common”作为租户 ID,而实际上我需要使用我的 Azure 租户我通过stack 上的这个答案获得的 ID 。我的身份验证请求的新基本 URL 现在看起来像:

https://login.microsoftonline.com/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/oauth2/authorize 
Run Code Online (Sandbox Code Playgroud)

其中“xxxx-....xxx”将替换为您的 Azure 租户 ID!