c# - Azure AD OAuth2 访问 token 请求错误 - 400 错误请求

标签 c# azure active-directory oauth-2.0 microsoft-graph-api

我的 WPF 桌面应用程序 (C#) 正在尝试通过 Microsoft Graph API 读取用户的 Outlook 电子邮件。我陷入了身份验证过程;我已经收到身份验证代码,现在尝试从 Azure 获取访问 token ,但在发送访问 token 请求时不断收到 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
}

上面是用于检索身份验证代码的代码,然后尝试检索访问 token 。我们没有 client_secret,因为 secret 仅适用于 Web 应用程序,并且这是 native 桌面 WPF 应用程序。我读到这不是问题。我网上看了很多教程和官方文档,主要是the official Graph authorization doc我仍然不明白我做错了什么。任何帮助将不胜感激,谢谢。

最佳答案

我用了fiddler调试请求,我发现了完整的错误消息:用户或管理员尚未同意使用该应用程序。我在 google 上搜索了这条消息,发现一些堆栈文章和 github 问题线程引导我找到了解决方案:我的请求一直在基本 URL 中使用“common”作为租户 ID,而实际上我需要使用我的 Azure 租户我通过这个获得的IDanswer on stack 。我的身份验证请求的新基本 URL 现在如下所示:

https://login.microsoftonline.com/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/oauth2/authorize 

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

关于c# - Azure AD OAuth2 访问 token 请求错误 - 400 错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38648978/

相关文章:

c# - 如何限制 Winforms MaskedTextbox 中的值

由流分析作业读取时的 azure eventhub 事件持久性

python - Azure Function ImportError 在云上运行时注册函数

Azure AD B2C 邀请电子邮件

通过 Active Directory 2008 进行 Django LDAP 身份验证

Azure CLI : get object id from user name or email address

c# - 如何在C#中实现PsPing TCP ping

c# - HTML Agility Pack W3C 工具的问题

c# - WCF 枚举,如果我不将成员标记为 EnumMember 会怎样?

php - 如何做跨库信息同步?