oAuth2 Web请求在浏览器中有效,但在应用程序中无效

时间:2017-09-07 23:57:59

标签: azure oauth-2.0 xamarin.forms

我有以下代码示例,我正在尝试在Xamarin表单应用程序中验证Azure活动目录用户

URL(我删除了实际的客户端ID)在浏览器中正常工作但在尝试发送http请求时失败

错误消息显示“响应类型必须包含client_id”

            string URL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?"
                        + "client_id=xxxx-xxxxx-xxxxx-xxxxx-xxx"
                        + "&response_type=code"
                        + "&redirect_uri=https://login.microsoftonline.com/common/oauth2/nativeclient"
                        + "&response_mode=query"
                        + "&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fmail.read"
                        + "&state=12345";



            var webRequest = System.Net.WebRequest.Create(URL) as HttpWebRequest;

            System.Console.WriteLine(URL);

            if (webRequest != null)
            {
                webRequest.Method = "POST";
                webRequest.ServicePoint.Expect100Continue = false;
                webRequest.Timeout = 20000;

                webRequest.ContentType = "text/html";
                //POST the data.
                using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
                {
                    requestWriter.Write(postData);
                }
            }

            HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
            Stream resStream = resp.GetResponseStream();
            StreamReader reader = new StreamReader(resStream);

            ret = reader.ReadToEnd();

1 个答案:

答案 0 :(得分:0)

您将参数放在网址中,因此您需要使用GET方法而不是POST(就像您将浏览器粘贴到地址栏中时的浏览器一样)。

所以,替换:

webRequest.Method = "POST";

由:

webRequest.Method = "GET";

并删除:

//POST the data.
using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
  {
    requestWriter.Write(postData);
  }