Search code examples
c#oauth-2.0access-tokenimgur

Imgur OAuth2: How to exchange autorization code for an access token


I'm trying to create an c# web app that uploads on Imgur. For the moment I just succeeded to get authorization_code but each time I'm trying to get an access token I receive an error "Missing required fields". As it's written in the API Docs I make POST request:

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

where:

  • CODE is "The authorization code that was returned after the user authorized"

Maybe I'm missing some small details, but that's what the API Doc says.


Solution

  • i have the same problem actually problem is i use x-www-form-urlencoded which send paramaters to URL(just like you do and it seems forbidden by imgur API team can be some security issues) so you need to use form-data. But i didn't find it in api doc. Below i share code sample of 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);
            }
        }
     }