Azure AD OAuth2访问令牌请求错误 - 400错误请求
Azure AD OAuth2访问令牌请求错误 - 400错误请求
我的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应用程序。但我已经阅读过,这不是问题。我已经按照许多教程和官方文档上的指导进行了操作,主要是官方图形授权文档,但我仍然无法弄清楚自己做错了什么。感谢你的帮助。
如果你没有使用客户端秘钥,那么你需要配置你的租户来支持隐式授权流。你可以按照这篇博客文章的说明来执行/验证配置。这需要使用 Azure 管理门户来下载、修改应用清单,并上传它。
或者,可能更好的策略是将你的代码切换到使用汇聚的 v2.0 鉴权终结点。它允许使用新的应用注册门户来管理你的应用程序,并很好地支持隐式流和动态范围。你可以在这里找到有关实际鉴权流程的更多信息。它与你现在正在做的事情并没有太大的不同,只需要进行一些小的调整。
如果你在完成上述操作后仍然有问题,请再次联系我们。Fiddler / 网络跟踪非常有帮助。此外,异常内的详细信息也将非常有帮助。
我使用fiddler来调试请求,并发现完整的错误信息:用户或管理员未同意使用该应用程序。我google了一下这个消息,并找到了一些堆栈文章和github问题线程,导致我找到了解决方案:我的请求一直在使用“common”作为租户ID的基本URL,而实际上我需要使用我通过此Stackoverflow答案获取的Azure租户ID。我的新的身份验证请求基本URL现在看起来像:
https://login.microsoftonline.com/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/oauth2/authorize
其中“xxxx- ....xxx”将被您的Azure租户ID替换!