Microsoft 365 API身份验证

时间:2016-01-19 08:34:32

标签: c# onedrive office365api office365-restapi

我编写了以下代码。当用户点击超链接时,他被重定向到登录页面,返回URL为https://localhost:44300/Office365/Office365Response。我编写了以下代码来获取访问令牌。但我总是收到如下指定的错误。我哪里错了?

  

很抱歉,但我们在登录时遇到了麻烦。我们收到了不好的消息   请求。其他技术信息:相关ID:   2e875fd4-f5a6-4003-9887-357c4a890e90时间戳:2016-01-19 08:28:20Z   AADSTS90056:此端点仅接受POST请求。

     

其他技术信息:相关ID:   2e875fd4-f5a6-4003-9887-357c4a890e90时间戳:2016-01-19 08:28:20Z   AADSTS90056:此端点仅接受POST请求。

    public ActionResult Office365Response(string code, string session_state)
    {
        string url = "http://login.microsoftonline.com/common/oauth2/token";
        code = "{Code}";
        string postData = "client_id" + "=" + "{ClientId}";
        postData += "&" + "redirect_uri" + "=" + "https://localhost:44300/Office365/Office365Response";
        postData += "&" + "client_secret" + "=" + "{ClientSecret}";
        postData += "&" + "code" + "=" + code;
        postData += "&" + "grant_type=authorization_code";
        postData += "&" + "resource" + "=" + "https://api.office.com/discovery/";

        // Create a request using a URL that can receive a post. 
        WebRequest request = WebRequest.Create(url);
        request.UseDefaultCredentials = true;
        request.PreAuthenticate = true;
        request.Credentials = CredentialCache.DefaultCredentials;
        // Set the Method property of the request to POST.
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        // Create POST data and convert it to a byte array.
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        // Set the ContentType property of the WebRequest.

        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;
        // Get the request stream.
        Stream dataStream = request.GetRequestStream();
        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);
        // Close the Stream object.
        dataStream.Close();
        // Get the response.
        WebResponse response = request.GetResponse();
        // Display the status.
        Console.WriteLine(((HttpWebResponse)response).StatusDescription);
        // Get the stream containing content returned by the server.
        dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
        // Display the content.
        Console.WriteLine(responseFromServer);
        // Clean up the streams.
        reader.Close();
        dataStream.Close();
        response.Close();
}

0 个答案:

没有答案
相关问题