4

I got the following problem:

I am trying to implement Instagram into my website. However I am stuck on the step where I need to get the Acces token. The api's documentation says I need to request it like this :

curl \-F 'client_id=CLIENT-ID' \
-F 'client_secret=CLIENT-SECRET' \
-F 'grant_type=authorization_code' \
-F 'redirect_uri=YOUR-REDIRECT-URI' \
-F 'code=CODE' \https://api.instagram.com/oauth/access_token

I use ASP.NET so I found this equivalent OAuth 2.0 In .NET With Instagram API:

NameValueCollection parameters = new NameValueCollection();
            parameters.Add("client_id", "ssdfsdfsdfsdfsdf");
            parameters.Add("client_secret", "sdsdfdsfsdfsdfsdfsdfsdf");
            parameters.Add("grant_type", "authorization_code");
            parameters.Add("redirect_uri", "http://localhost:2422/LoginsGuests/GetLoginPage");
            parameters.Add("code", code);

            WebClient client = new WebClient();
            var result = client.UploadValues("https://api.instagram.com/oauth/access_token", parameters);

            var response = System.Text.Encoding.Default.GetString(result);

However I keep getting: System.Net.WebException: The remote server returned an error: (400) Bad Request.

What I am i doing wrong?

Community
  • 1
  • 1
Jan
  • 71
  • 1
  • 7

2 Answers2

3

Almost there the instagram api expects a POST not a GET.

Add the "POST" parameter.

var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);

Also check the instagram settings -> redirect url.

Then this may help don't forget to add a reference to Newtonsoft.Json. Is in .Net version 4.5.1:

using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;

namespace Instagram
{
    public class InstagramClient
    {
        public InstagramClient(string code)
        {
            GetToken(code);
        }

        private void GetToken(string code)
        {
            using (var wb = new WebClient())
            {
                var parameters = new NameValueCollection
                                 {
                                     {"client_id", "ClientId"},
                                     {"client_secret", "ClientSecret"},
                                     {"grant_type", "authorization_code"},
                                     {"redirect_uri", "RedirectUri"},
                                     {"code", code}
                                 };

                var response = wb.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
                string json = Encoding.ASCII.GetString(response);

                try
                {
                    var OauthResponse = (InstagramOAuthResponse)    Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(InstagramOAuthResponse));
                }
                catch (Exception ex)
                {
                    //handle ex if needed.
                }
            }
        }

        public class InstagramOAuthResponse
        {
            public string access_token { get; set; }
            public User user { get; set; }
        }

        public class User : System.Security.Principal.IIdentity
        {
            public string username { get; set; }
            public string website { get; set; }
            public string profile_picture { get; set; }
            public string full_name { get; set; }
            public string bio { get; set; }
            public string id { get; set; }

            public string OAuthToken { get; set; }

            public string AuthenticationType
            {
                get { return "Instagram"; }
            }

            public bool IsAuthenticated
            {
                get { return !string.IsNullOrEmpty(id); }
            }

            public string Name
            {
                get
                {
                    return String.IsNullOrEmpty(full_name) ? "unknown" : full_name;
                }
            }
        }
    }
}
Igor
  • 298
  • 3
  • 8
  • 1
    Hi, thanks for your anwser. However this doesn't make any difference. Still getting the 400 error sadly. – Jan Aug 04 '14 at 07:11
  • I realized that the API returns that response even when they successfully processed your request but can not retrieve the code, not because you throw a bad request but because other reason like: " Matching code was not found or was already used" or "Redirect URI does not match registered redirect URI". Check whether that's your case or not. From my point of view, they should return 200 OK response to these scenarios, although it was not the expected result, they successfully processed your request after all. – e_v_e Nov 25 '15 at 10:54
0

If you prefer HttpWebRequest class:

var request = (HttpWebRequest)WebRequest.Create("https://api.instagram.com/oauth/access_token/");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";

var requestDetails = "client_id=" + AppConfig.InstagramClientId;
requestDetails += "&client_secret=" + AppConfig.InstagramClientSecret;
requestDetails += "&grant_type=authorization_code";
requestDetails += "&redirect_uri=" + redirectUrl;
requestDetails += "&code=" + exchangeCode;

byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
request.ContentLength = bytes.Length;

using (Stream outputStream = request.GetRequestStream())
{
    outputStream.Write(bytes, 0, bytes.Length);
}

var response = request.GetResponse();
var code = ((HttpWebResponse)response).StatusCode;

if (code == HttpStatusCode.OK)
{
    using (var streamReader = new StreamReader(response.GetResponseStream()))
    {
        var jsonString = streamReader.ReadToEnd();
        var accessToken = ParseAccessToken(jsonString);
        return accessToken;
    }
}
Victor Stagurov
  • 4,566
  • 1
  • 15
  • 15
  • How would you actually go about getting the exchangeCode? – Andrew Garrison Jul 23 '18 at 20:54
  • You need to make a call to the following URL: var url = $"https://api.instagram.com/oauth/authorize/?client_id={AppConfig.InstagramClientId}&redirect_uri={urlEncodedCallbackUrl}&state={controlledUserId}&scope=basic+public_content&response_type=code"; – Victor Stagurov Jul 24 '18 at 18:07