Imgur OAuth2:如何交换访问令牌的授权码

时间:2015-04-07 12:29:01

标签: c# oauth-2.0 access-token imgur

我正在尝试创建一个在Imgur上传的c#网络应用。目前我刚刚成功获得authorization_code,但每次我试图获取访问令牌时,都会收到错误“Missing required fields”。正如它在API Docs我写的POST请求中所写:

https://api.imgur.com/oauth2/token?client_id=MY_CLIENT_ID&client_secret=MY_CLIENT_SECRET&grant_type=authorization_code&code=CODE

其中:

  • CODE是“用户之后返回的授权码 授权“

也许我错过了一些小细节,但这就是API Doc所说的。

1 个答案:

答案 0 :(得分:2)

我有同样的问题实际问题是我使用x-www-form-urlencoded将paramaters发送到URL(就像你做的那样,似乎imgur API团队禁止这可能是一些安全问题)所以你需要使用表单数据。但是我没有在api doc中找到它。下面我分享C#的代码示例

using System.IO;
using System;
using System.Net;
using System.Text;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

class Program
{
    static void Main()
    {
        sendRequest("https://api.imgur.com/oauth2/token");
    }

    private static void sendRequest(String url){

        using(WebClient client = new WebClient())
        {
            System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
            reqparm.Add("client_id", "Your client_id");
            reqparm.Add("client_secret", "Your client_secret");
            reqparm.Add("grant_type", "authorization_code");
            reqparm.Add("code", "your returned code");

            ServicePointManager.ServerCertificateValidationCallback = 
                delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) 
                    { return true; };
            System.Net.ServicePointManager.Expect100Continue = false;
            byte[] responsebytes = client.UploadValues(url, "POST", reqparm);
            string responsebody = Encoding.UTF8.GetString(responsebytes);
            Console.WriteLine(responsebody);
        }
    }
 }